#!/usr/bin/env python3
"""E126.a standalone offline verifier. Standard library only. Imports no CAIN code."""
from __future__ import annotations

import hashlib
import json
import sys
from pathlib import Path

FAILS = []
CHECKS = 0


def ok(cond, name, detail=""):
    global CHECKS
    CHECKS += 1
    print(("PASS " if cond else "FAIL ") + name + (" " + detail if detail else ""))
    if not cond:
        FAILS.append(name)


def sha(p):
    h = hashlib.sha256()
    with p.open("rb") as fh:
        for c in iter(lambda: fh.read(1 << 20), b""):
            h.update(c)
    return h.hexdigest()


def load(p):
    return json.loads(p.read_text())


def main():
    root = Path(sys.argv[1]) if len(sys.argv) > 1 else Path(__file__).resolve().parent
    print("E126.a verifier root=" + str(root))
    man = load(root / "MANIFEST.json")
    for e in man["files"]:
        p = root / e["path"]
        ok(p.exists() and sha(p) == e["sha256"], "manifest:" + e["path"], "" if p.exists() else "MISSING")

    reg = load(root / "E126A_EVIDENCE_REGISTRY.json")
    ok(reg["agi_status"] == "NOT ACHIEVED", "agi_status", "")
    ok(len(reg["records"]) == 21, "registry_records", str(len(reg["records"])))
    statuses = {"PASS", "PARTIAL", "FAIL", "BLOCKED", "RUNNING", "NOT_TESTED", "SUPERSEDED", "INTERIM"}
    for r in reg["records"]:
        ok(r["scientific_status"] in statuses and r["integrity_status"] in {"PASS", "PARTIAL", "FAIL", "BLOCKED"},
           "registry_status:" + r["claim_id"], r["scientific_status"] + "/" + r["integrity_status"])
        for p, h in r["sha256"].items():
            if h == "MISSING":
                continue
            candidates = [root / "sources" / p, root / p]
            try:
                candidates.insert(0, root.parents[2] / p)
            except IndexError:
                pass
            q = next((x for x in candidates if x.exists()), None)
            ok(q is not None and sha(q) == h, "registry_hash:" + p, "" if q else "MISSING")

    home = load(root / "E126A_HOMEPAGE_MATRIX.json")
    ok(len(home["surfaces"]) == 3, "homepage_surfaces", "3")
    for s in home["surfaces"]:
        ok(s["marker"] is True and s["agi_status"] is True, "homepage:" + s["site"], s.get("headline", ""))
    ok(len({s["headline"] for s in home["surfaces"]}) == 3, "distinct_headlines", "3")

    gates = load(root / "E126A_GATE_MATRIX.json")
    ok(len(gates["gates"]) == 32, "gate_count", "32")
    for g in gates["gates"]:
        ok(g["status"] in {"PASS", "PARTIAL", "FAIL", "BLOCKED", "NOT TESTED"}, "gate:" + g["id"], g["status"])

    tests = load(root / "E126A_TEST_RESULTS.json")
    ok(tests.get("passed", 0) >= 12 and tests.get("failed", 1) == 0, "tests", str(tests.get("passed")))

    lineage = load(root / "E126A_CLAIM_LINEAGE.json")
    ok(any(x.get("claim_id") == "HIST-SWEBENCH" for x in lineage["lineage"]), "lineage_swebench", "")
    ok(any(x.get("claim_id") == "HIST-48H" for x in lineage["lineage"]), "lineage_48h", "")

    env = load(root / "evidence" / "env_results.json")
    ok(abs(env["arms"]["full"]["completion"] - 0.87) < 1e-9, "metric_env_full", "0.87")
    ok(abs(env["arms"]["retrieval"]["completion"] - 0.78) < 1e-9, "metric_env_retrieval", "0.78")

    for p in (root / "E126A_REPORT.md", root / "E126A_BASELINE_AUDIT.md", root / "E126A_REPRODUCE.md",
              root / "E126A_OFFLINE_VERIFIER.py"):
        ok(p.exists(), "present:" + p.name, "")

    screens = root / "E126A_SCREENSHOTS"
    ok(screens.exists(), "screenshots_dir", "BLOCKED README present" if screens.exists() else "MISSING")

    # tamper detection: a changed record status must break the registry hash in the manifest
    if reg["records"]:
        copy = json.loads(json.dumps(reg))
        copy["records"][0]["scientific_status"] = "PASS" if copy["records"][0]["scientific_status"] != "PASS" else "FAIL"
        h1 = hashlib.sha256(json.dumps(reg, sort_keys=True).encode()).hexdigest()
        h2 = hashlib.sha256(json.dumps(copy, sort_keys=True).encode()).hexdigest()
        ok(h1 != h2, "tamper_detection", "a changed status changes the registry hash")

    print(f"\n{CHECKS - len(FAILS)}/{CHECKS} checks passed; {len(FAILS)} failed")
    if FAILS:
        print("FAILURES:", FAILS)
        return 1
    return 0


if __name__ == "__main__":
    raise SystemExit(main())
