#!/usr/bin/env python3
"""verify_archive.py - check files from www.david-medeiros.com against the site's AI data manifest (SHA-256).
Added December 1, 2026 (Release GAP18). Python 3, standard library only.
  python verify_archive.py                    download every listed file and check it
  python verify_archive.py --only datasets/   check only paths that start with this text
  python verify_archive.py --dir FOLDER       check copies you already have (FOLDER/<path as listed>)
A match proves only that the bytes are the ones listed. It does not prove that a record is true.
A filing is not a finding."""
import argparse, gzip, hashlib, json, os, sys, urllib.request

MANIFEST = 'https://www.david-medeiros.com/for-ai/manifest.json'


def get(url):
    req = urllib.request.Request(url, headers={'User-Agent': 'verify_archive.py'})
    with urllib.request.urlopen(req, timeout=120) as r:
        return r.read()


def main():
    ap = argparse.ArgumentParser(description='Check archive files against the AI data manifest.')
    ap.add_argument('--manifest', default=MANIFEST, help='manifest URL or local file')
    ap.add_argument('--dir', help='folder with files you already downloaded')
    ap.add_argument('--only', default='', help='check only paths that start with this text')
    a = ap.parse_args()
    raw = get(a.manifest) if a.manifest.startswith('http') else open(a.manifest, 'rb').read()
    files = json.loads(raw.decode('utf-8-sig'))['files']
    ok = bad = missing = 0
    for f in files:
        if not f['path'].startswith(a.only):
            continue
        try:
            data = open(os.path.join(a.dir, *f['path'].split('/')), 'rb').read() if a.dir else get(f['url'])
        except Exception as e:
            missing += 1
            print('MISSING ', f['path'], '-', e)
            continue
        h = hashlib.sha256(data).hexdigest()
        if h != f['sha256'] and data[:2] == b'\x1f\x8b':   # a plain address that is served from its .gz copy
            h = hashlib.sha256(gzip.decompress(data)).hexdigest()
        if h == f['sha256']:
            ok += 1
        else:
            bad += 1
            print('MISMATCH', f['path'], 'listed', f['sha256'], 'got', h)
    print('checked %d: %d match, %d mismatch, %d missing' % (ok + bad + missing, ok, bad, missing))
    sys.exit(1 if bad or missing else 0)


if __name__ == '__main__':
    main()
