#!/usr/bin/env python3
# precheck_hub.py: check a Hugging Face model repo BEFORE pulling it, without downloading any weights.
# Run it before downloading a model. After the download, check_gguf.py reads every byte.
#
# What it checks, from the hub's API and from each file's HEADER only (fetched with an HTTP range request):
#   WHO: the uploader's account age and history; the same repo name under an older owner (Mir2k copied AtomicChat's name);
#        a disabled repo; files that can run code (pickles, .py, auto_map).
#   WHERE THE FILE HIDES THINGS: for every GGUF and safetensors file, the size the header says the model data ends at versus
#        the real file size (a tail payload shows up before a byte of it is downloaded), the padding after the header
#        (must be zero), and for safetensors, gaps between tensors.
#   THE TEMPLATE: walks the card's base_model chain to the lab that trained the model, fetches every chat template that lab
#        ever published (all commits), and compares each template in the repo, byte for byte. Anything else gets a diff.
# Exit 0 = GO. Exit 1 = LOOK: read the flags before pulling.
#
# RUNS ON: any box with python3 + numpy:
#   python3 precheck_hub.py <owner/repo> [--rev <commit>] [--files <regex>] [--out <dir>]
#       --gguf-py <llama.cpp/gguf-py> [--gguf-py <fork's gguf-py> ...]
import argparse, datetime as dt, io, json, os, re, sys, urllib.error, urllib.parse, urllib.request
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
import check_gguf as C

HF = "https://huggingface.co"
UA = {"User-Agent": "precheck-hub/1.0"}
if os.environ.get("HF_TOKEN"): UA["Authorization"] = "Bearer " + os.environ["HF_TOKEN"]     # used by name, never printed
# Organisations that train base models. A template is judged against THEIR published versions. A chain that never reaches one
# of these is a LOOK (check it by hand), not a GO. Add a lab here only after checking it is the real lab's account.
LABS = {"Qwen", "google", "meta-llama", "mistralai", "deepseek-ai", "microsoft", "nvidia", "zai-org", "THUDM", "moonshotai", "openai",
        "ibm-granite", "LiquidAI", "allenai", "HuggingFaceTB", "CohereLabs", "CohereForAI", "tencent", "baidu", "inclusionAI",
        "stepfun-ai", "MiniMaxAI", "xai-org", "apple", "ByteDance-Seed", "XiaomiMiMo", "swiss-ai", "openbmb", "internlm", "upstage", "thinkingmachines"}
NEW_ACCOUNT_DAYS = 90
CODE_FILES = re.compile(r"\.(py|pkl|pickle|pt|pth|ckpt|bin|sh|exe|dll|ps1|bat|cmd|so|dylib|jar|msi|scr|vbs|js)$", re.I)

def get(url, rng=None, as_json=False):
    h = dict(UA)
    if rng: h["Range"] = f"bytes={rng[0]}-{rng[1]}"
    with urllib.request.urlopen(urllib.request.Request(url, headers=h), timeout=60) as r:
        b = r.read()
        if rng and r.status != 206 and len(b) > rng[1] - rng[0] + 1: b = b[: rng[1] - rng[0] + 1]   # server ignored the range
    return json.loads(b) if as_json else b

def api(path):
    try: return get(HF + "/api/" + path, as_json=True)
    except urllib.error.HTTPError as e: return {"_error": e.code}

def when(s): return dt.datetime.fromisoformat(s.replace("Z", "+00:00")) if s else None
def days_ago(t): return (dt.datetime.now(dt.timezone.utc) - t).days if t else None

def who(owner, repo_info, look, info):
    # the owner's own history: oldest repo they hold, how many, and the account itself where the API tells
    models = api(f"models?author={urllib.parse.quote(owner)}&sort=createdAt&direction=1&limit=1000") or []
    models = models if isinstance(models, list) else []
    first = min((when(m.get("createdAt")) for m in models if m.get("createdAt")), default=None)
    acct = api(f"users/{owner}/overview")
    if "_error" in acct: acct = api(f"organizations/{owner}/overview")
    created = when(acct.get("createdAt")) if isinstance(acct, dict) else None
    info["owner"] = {"name": owner, "account_created": str(created)[:10] if created else None, "first_repo": str(first)[:10] if first else None,
                     "repos": len(models), "is_lab": owner in LABS}
    age = days_ago(created) if created else days_ago(first)
    if age is None: look.append(f"could not read how old the account {owner} is")
    elif age < NEW_ACCOUNT_DAYS: look.append(f"the account {owner} is only {age} days old (Mir2k and timdedid were brand new)")
    # the same repo name under another owner, older than this one = a possible copied name
    name = repo_info["id"].split("/", 1)[1]
    same = [m for m in (api(f"models?search={urllib.parse.quote(name)}&limit=100") or []) if isinstance(m, dict)
            and m.get("id", "").split("/", 1)[-1].lower() == name.lower() and m["id"] != repo_info["id"]]
    mine = when(repo_info.get("createdAt"))
    older = [m for m in same if mine and when(m.get("createdAt")) and when(m["createdAt"]) < mine]
    info["same_name_elsewhere"] = [{"id": m["id"], "created": m.get("createdAt", "")[:10], "downloads": m.get("downloads")} for m in same]
    if older: look.append(f'the name "{name}" already existed under {", ".join(m["id"] for m in older)} before this copy: is this the real one?')

def chain(repo, info, depth=0, seen=None):
    """the base_model chain up to the lab(s)"""
    seen = seen if seen is not None else []
    if depth > 8 or repo in seen: return seen
    seen.append(repo)
    d = api(f"models/{repo}")
    bm = (d.get("cardData") or {}).get("base_model") if isinstance(d, dict) else None
    for b in ([bm] if isinstance(bm, str) else bm or []): chain(b, info, depth + 1, seen)
    return seen

def lab_templates(labs, refdir):
    os.makedirs(refdir, exist_ok=True); n = 0
    for lab in labs:
        commits = api(f"models/{lab}/commits/main")
        for c in (commits if isinstance(commits, list) else []):
            cid = c["id"]; base = f"{HF}/{lab}/resolve/{cid}/"; tag = lab.replace("/", "_") + "@" + cid[:7]
            for fn in ("chat_template.jinja", "tokenizer_config.json", "chat_template.json"):
                try: raw = get(base + fn).decode("utf-8")
                except Exception: continue
                if fn == "chat_template.jinja": items = {"": raw}
                else:
                    try: ct = json.loads(raw).get("chat_template")
                    except Exception: ct = None
                    items = {"": ct} if isinstance(ct, str) else {"." + x.get("name", ""): x.get("template", "") for x in ct} if isinstance(ct, list) else {}
                for k, v in items.items():
                    open(os.path.join(refdir, f"{tag}{k}.{fn.split('.')[0]}.jinja"), "w", encoding="utf-8").write(v); n += 1
    return n

def head_gguf(url, size, tables):
    want = 16 << 20
    while True:
        b = get(url, (0, min(want, size) - 1))
        try:
            ver, kv, tensors, hdr_end, align, data_start = C.gguf_header_f(io.BytesIO(b))
            if data_start <= len(b): return b, kv, tensors, hdr_end, data_start
        except Exception:
            if want >= size or want >= (512 << 20): raise
        want *= 4

def main():
    ap = argparse.ArgumentParser()
    ap.add_argument("repo"); ap.add_argument("--rev"); ap.add_argument("--files", default=".")
    ap.add_argument("--out"); ap.add_argument("--gguf-py", action="append", required=True)
    ap.add_argument("--lab", action="append", default=[], help="name the lab by hand when the card's base_model chain is broken "
                    "(e.g. a Heretic recipe says google/gemma-4-31B-it); say where you read it in the notes")
    a = ap.parse_args()
    look, info = [], {"repo": a.repo, "checked_at": dt.datetime.now().isoformat(timespec="seconds")}
    r = api(f"models/{a.repo}?blobs=true" + (f"&revision={a.rev}" if a.rev else ""))
    if "_error" in r: print(f"cannot read {a.repo}: HTTP {r['_error']}"); sys.exit(1)
    rev = a.rev or r["sha"]; info.update(rev=rev, created=r.get("createdAt"), downloads=r.get("downloads"), likes=r.get("likes"), gated=r.get("gated"))
    out = a.out or os.path.expanduser(f"~/model-precheck/{a.repo.replace('/', '__')}__{rev[:7]}")
    os.makedirs(out, exist_ok=True)
    if r.get("disabled"): look.append("the hub has DISABLED this repo")
    who(a.repo.split("/")[0], r, look, info)
    ch = chain(a.repo, info); labs = [x for x in ch if x.split("/")[0] in LABS]
    for lb in a.lab:
        assert lb.split("/")[0] in LABS, f"--lab {lb} is not one of the known labs"
        labs.append(lb); info.setdefault("labs_named_by_hand", []).append(lb)
    info["base_chain"] = ch; info["labs"] = labs
    if not labs: look.append(f"the base_model chain {ch} never reaches a known lab: no official template to compare with")
    refs = {}
    if labs:
        n = lab_templates(labs, os.path.join(out, "lab-templates")); refs = C.load_refs(os.path.join(out, "lab-templates"))
        info["lab_template_versions"] = n
        if not refs: look.append(f"no chat template found in any commit of {labs}")
    tables = C.load_type_tables(a.gguf_py); tdir = os.path.join(out, "templates"); os.makedirs(tdir, exist_ok=True)
    files, total = [], 0
    for s in r.get("siblings", []):
        fn = s["rfilename"]; size = s.get("size") or (s.get("lfs") or {}).get("size") or 0
        if not re.search(a.files, fn) and not fn.endswith((".json", ".jinja")): continue
        url = f"{HF}/{a.repo}/resolve/{rev}/{urllib.parse.quote(fn)}"; row = {"file": fn, "size": size, "look": []}
        try:
            if fn.endswith(".gguf"):
                b, kv, tensors, hdr_end, data_start = head_gguf(url, size, tables)
                unknown = sorted({t["type"] for t in tensors if C.type_info(tables, t["type"]) is None})
                if unknown: row["look"].append(f"tensor types no reader knows: {unknown}: cannot work out where the data ends")
                else:
                    end = max(data_start + t["offset"] + int(C.np.prod(t["dims"], dtype=C.np.int64)) // C.type_info(tables, t["type"])[1] * C.type_info(tables, t["type"])[2] for t in tensors)
                    row["data_end"] = end; row["trailing"] = size - end
                    if size != end: row["look"].append(f"{size - end} bytes after the end of the model data (a known hiding place)")
                pad = b[hdr_end:data_start]
                if any(pad): row["look"].append(f"{sum(1 for x in pad if x)} nonzero bytes in the padding after the header")
                row["templates"] = {}
                if not refs:                        # the card named no lab: try the base-model fields the GGUF carries itself
                    hdr = [m.group(1) for k2, v2 in kv.items() if isinstance(v2, str) and k2.startswith("general.") and "repo_url" in k2
                           for m in [re.match(r"https?://huggingface\.co/([^/\s]+/[^/\s?#]+)", v2)] if m]
                    hl = [x for r2 in dict.fromkeys(hdr) for x in chain(r2, {}) if x.split("/")[0] in LABS]
                    if hl:
                        lab_templates(hl, os.path.join(out, "lab-templates")); refs = C.load_refs(os.path.join(out, "lab-templates"))
                        labs = list(dict.fromkeys(hl)); info["labs"] = labs; info["lab_template_versions"] = len(refs)
                        look[:] = [l for l in look if "never reaches a known lab" not in l]
                for k, v in kv.items():
                    if isinstance(v, str) and "template" in k.lower():
                        if refs:
                            j = C.judge_template(v, refs, tdir, os.path.basename(fn) + "." + k); row["templates"][k] = j
                            if j["verdict"] == "DIFFERS": row["look"].append(f'template {k} differs from every version {labs} published: read {j["diff"]}')
                        open(os.path.join(tdir, os.path.basename(fn) + "." + k + ".jinja"), "w", encoding="utf-8").write(v)
                        hits, acc = C.text_hits(v)
                        if hits or acc: row["look"].append(f"template {k} words: {hits} accented: {acc}")
                    elif isinstance(v, str) and k not in C.SKIP_KV_ARRAYS:
                        hits = [h for h in C.text_hits(v)[0] if h not in ("https://", "http://")]
                        if hits: row["look"].append(f"header text {k}: {hits}")
            elif fn.endswith(".safetensors"):
                n = int.from_bytes(get(url, (0, 7)), "little"); head = json.loads(get(url, (8, 8 + n - 1)))
                head.pop("__metadata__", None)
                spans = sorted(tuple(v["data_offsets"]) for v in head.values()); pos = 0; gaps = 0
                for s0, s1 in spans: gaps += max(0, s0 - pos); pos = max(pos, s1)
                row["data_end"] = 8 + n + pos; row["trailing"] = size - row["data_end"]
                if row["trailing"]: row["look"].append(f'{row["trailing"]} bytes after the end of the model data')
                if gaps: row["look"].append(f"{gaps} unclaimed bytes between tensors")
            elif fn in ("chat_template.jinja", "tokenizer_config.json", "chat_template.json"):
                raw = get(url).decode("utf-8")
                if fn == "chat_template.jinja": items = {fn: raw}
                else:
                    ct = json.loads(raw).get("chat_template")
                    items = {fn: ct} if isinstance(ct, str) else {f'{fn}[{x.get("name")}]': x.get("template", "") for x in ct} if isinstance(ct, list) else {}
                row["templates"] = {}
                for k, v in items.items():
                    if refs:
                        j = C.judge_template(v, refs, tdir, k); row["templates"][k] = j
                        if j["verdict"] == "DIFFERS": row["look"].append(f'template {k} differs from every version {labs} published: read {j["diff"]}')
            elif fn == "config.json":
                d = json.loads(get(url))
                if "auto_map" in d: row["look"].append(f'auto_map: custom code would run with trust_remote_code: {d["auto_map"]}')
            elif CODE_FILES.search(fn):
                row["look"].append("a file that can run code (program, script or pickle)")
            else:
                continue
        except Exception as e:
            row["look"].append(f"could not check: {e!r}"[:300])
        files.append(row); total += size
        for l in row["look"]: look.append(f"{fn}: {l}")
        tv = "; ".join(f'{k.split(".")[-1]}={j["verdict"]}' for k, j in row.get("templates", {}).items())
        print(f'{"⚠ LOOK" if row["look"] else "ok    "} {size/1e9:7.2f} GB  {"tail " + str(row.get("trailing")) if "trailing" in row else ""}  {tv}  {fn}', flush=True)
    info["files"] = files; info["look"] = look
    json.dump(info, open(os.path.join(out, "PRECHECK.json"), "w"), indent=1, default=str)
    o = info["owner"]
    print(f'\n{a.repo} @ {rev[:7]} · owner {o["name"]}: account {o["account_created"]}, first repo {o["first_repo"]}, {o["repos"]} repos'
          f'{" (a lab)" if o["is_lab"] else ""} · chain {" → ".join(ch)} · {info.get("lab_template_versions", 0)} lab template versions')
    if info.get("same_name_elsewhere"): print("same name elsewhere:", info["same_name_elsewhere"])
    print(("\nLOOK before pulling:\n- " + "\n- ".join(look)) if look else "\nGO: nothing found. Pull pinned to this commit, sha256 every file, then run check_gguf.py on it.")
    print(f"Report: {os.path.join(out, 'PRECHECK.json')}")
    sys.exit(1 if look else 0)

if __name__ == "__main__":
    main()
