#!/usr/bin/env python3
"""Re-check the BSV uncensored local AI list against the Hugging Face Hub API, and optionally local files.
Usage: python3 verify.py [picks.json] [--local DIR]   (standard library only)"""
import json, sys, urllib.request, hashlib, os
src = sys.argv[1] if len(sys.argv) > 1 and not sys.argv[1].startswith("--") else "picks.json"
local = sys.argv[sys.argv.index("--local") + 1] if "--local" in sys.argv else None
doc = json.load(open(src))
bad = 0
for p in doc["picks"]:
    d = json.load(urllib.request.urlopen(f"https://huggingface.co/api/models/{p['repo']}/revision/{p['revision']}?blobs=true", timeout=60))
    sib = {s["rfilename"]: s for s in d.get("siblings", [])}
    for f in p["files"] + ([p["projector_file"]] if p.get("projector_file") else []):
        s = sib.get(f["path"]); lfs = (s or {}).get("lfs") or {}
        ok = s is not None and (s.get("size") or lfs.get("size")) == f["bytes"] and lfs.get("sha256") == f["sha256"]
        line = ("OK  " if ok else "DIFF") + f" {p['id']} {f['path']}"
        if local and f.get("sha256"):
            path = os.path.join(local, os.path.basename(f["path"]))
            if os.path.exists(path):
                h = hashlib.sha256()
                with open(path, "rb") as fh:
                    for chunk in iter(lambda: fh.read(1 << 24), b""): h.update(chunk)
                same = h.hexdigest() == f["sha256"]; ok = ok and same
                line += "  local:" + ("match" if same else "MISMATCH")
        bad += 0 if ok else 1
        print(line)
print("all entries match" if bad == 0 else f"{bad} entries differ")
sys.exit(1 if bad else 0)
