#!/usr/bin/env python3
"""E231 standalone record verifier. No CAIN imports; engine source withheld.

Recomputes the paired statistics from the published per-task solved sets, checks the
salt commitments, task manifests, deviation record, private same-code reproduction,
signature and file hashes, and rejects overclaims. Record-level: the engine is not
re-executed here.
"""
from __future__ import annotations
import hashlib
import json
import sys
from math import comb
from pathlib import Path

STATUS = "AGI: NOT ESTABLISHED · RSI: EXPERIMENTAL"
ENGINE = {"engine.py", "run.py", "prereg.py"}


def canon(o):
    return json.dumps(o, sort_keys=True, separators=(",", ":")).encode()


def sha(b):
    return hashlib.sha256(b).hexdigest()


def merkle(paths):
    leaves = sorted(sha(p.read_bytes()) for p in paths)
    if not leaves:
        return sha(b"")
    while len(leaves) > 1:
        if len(leaves) % 2:
            leaves.append(leaves[-1])
        leaves = [sha((leaves[i] + leaves[i + 1]).encode()) for i in range(0, len(leaves), 2)]
    return leaves[0]


def mc(child, parent):
    b = len(set(child) - set(parent))
    c = len(set(parent) - set(child))
    n = b + c
    p = sum(comb(n, k) for k in range(b, n + 1)) / (2 ** n) if n else 1.0
    return {"child_only": b, "parent_only": c, "n": n, "p_one_sided": p}


def holm(pairs):
    order = sorted(pairs, key=lambda x: x[1])
    out, prev = {}, 0.0
    for i, (name, p) in enumerate(order):
        a = min(1.0, max(prev, (len(order) - i) * p))
        out[name] = a
        prev = a
    return out


def main():
    B = Path(sys.argv[1] if len(sys.argv) > 1 else ".")
    checks = []

    def ck(name, ok, detail=""):
        checks.append({"check": name, "ok": bool(ok), "detail": str(detail)[:300]})

    man = json.loads((B / "E231_MANIFEST.json").read_text())
    ck("status", man.get("status") == STATUS)
    ck("label", man.get("label") == "TRANSFER_SUPPORTED")
    body = {k: v for k, v in man.items() if k != "signature"}
    try:
        from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PublicKey
        Ed25519PublicKey.from_public_bytes(bytes.fromhex(man["pubkey_ed25519"])).verify(bytes.fromhex(man["signature"]), canon(body))
        ck("signature", True)
    except Exception as ex:
        ck("signature", False, ex)

    files = man.get("files", {})
    ck("files exist", all((B / k).exists() for k in files))
    bad = [k for k, h in files.items() if (B / k).exists() and sha((B / k).read_bytes()) != h]
    ck("hashes", not bad, bad[:3])
    ck("merkle", merkle(sorted(B / k for k in files if (B / k).exists())) == man.get("merkle_root"))
    present = {str(x.relative_to(B)) for x in B.rglob("*") if x.is_file() and "__pycache__" not in x.parts and x.suffix != ".pyc"}
    allowed_extra = {"E231_MANIFEST.json", "E231_SIGNED_BODY.json", "E231_VERIFICATION_RESULTS.json", "PUBLICATION.json", "E231_OMEGA_SEAL.json", "E231_TAMPER_RESULTS.json"}
    unlisted = sorted(present - set(files) - allowed_extra)
    ck("no unlisted", not unlisted, unlisted[:5])
    ck("engine withheld", not any((B / n).exists() for n in ENGINE))
    ck("no secrets", not any(x.endswith((".pem", ".key", ".env", ".db")) for x in present))

    pre = json.loads((B / "E231_PREREGISTRATION.json").read_text())
    fr = json.loads((B / "E231_PREREGISTRATION_FREEZE.json").read_text())
    rep = json.loads((B / "E231_RUN_REPORT.json").read_text())
    hyp = json.loads((B / "E231_HYPOTHESIS_RESULTS.json").read_text())
    ck("prereg hash", sha((B / "E231_PREREGISTRATION.json").read_bytes()) == fr["preregistration_sha256"])
    ck("freeze before run", fr["frozen_at"] <= rep["generated_at"])
    salts = json.loads((B / "E231_SALTS_REVEALED.json").read_text())["salts"]
    ck("salt commitments", {k: sha(bytes.fromhex(v)) for k, v in salts.items()} == pre["salt_commitments_sha256"])
    ck("salt master", sha(json.dumps({k: sha(bytes.fromhex(v)) for k, v in salts.items()}, sort_keys=True).encode()) == pre["salt_master_commitment_sha256"])

    sealed = json.loads((B / "E231_SEALED_TASKS.json").read_text())
    dev = json.loads((B / "E231_DEV_TASKS.json").read_text())
    for d in ("d0", "d1", "d2"):
        ck(f"{d} 30 sealed", len(sealed["sealed"][d]) == 30)
        ck(f"{d} 30 dev", len(dev["dev"][d]) == 30)
        ck(f"{d} 3+7", all(len(t["examples"]) == 3 and len(t["heldout"]) == 7 for t in sealed["sealed"][d]))
        ck(f"{d} sealed manifest", sha(json.dumps(sealed["sealed"][d], sort_keys=True).encode()) == rep["sealed_manifest_sha256"][d])
        ck(f"{d} dev manifest", sha(json.dumps(dev["dev"][d], sort_keys=True).encode()) == rep["dev_manifest_sha256"][d])

    def ks(name):
        return {tuple(x) for x in rep[name]}

    ctx, raw, scr, comp = ks("context_final"), ks("raw_final"), ks("scratch"), ks("compute")
    ck("context 59", len(ctx) == 59)
    ck("raw 54", len(raw) == 54)
    ck("scratch 37", len(scr) == 37)
    ck("compute 37", len(comp) == 37)
    for d in ("d0", "d1", "d2"):
        pd = rep["per_domain"][d]
        ck(f"{d} counts",
           pd["context"] == len({x for x in ctx if x[0] == d}) and pd["raw"] == len({x for x in raw if x[0] == d})
           and pd["scratch"] == len({x for x in scr if x[0] == d}) and pd["compute"] == len({x for x in comp if x[0] == d}))
    h1 = mc(ctx, raw)
    h2 = mc(ctx, scr)
    hc = mc(ctx, comp)
    hp = holm([("H1", h1["p_one_sided"]), ("H2", h2["p_one_sided"])])
    h1_ok = h1["child_only"] > h1["parent_only"] and hp["H1"] < 0.05
    h2_ok = h2["child_only"] > h2["parent_only"] and hp["H2"] < 0.05
    negative = len(scr - ctx) > len(ctx - scr)
    verdict = "TRANSFER_SUPPORTED" if (h1_ok and h2_ok) else ("NEGATIVE_TRANSFER" if negative else "NOT_SUPPORTED")
    ck("H1 recomputed", h1 == rep["hypotheses"]["H1"]["contrast"] and abs(hp["H1"] - rep["hypotheses"]["H1"]["holm"]) < 1e-15)
    ck("H2 recomputed", h2 == rep["hypotheses"]["H2"]["contrast"] and abs(hp["H2"] - rep["hypotheses"]["H2"]["holm"]) < 1e-15)
    ck("compute contrast", hc == rep["hypotheses"]["EXPLORATORY_compute"]["contrast"])
    ck("verdict recomputed", verdict == rep["verdict"] and verdict == hyp["verdict"])
    ck("hypothesis verdicts",
       all(rep["hypotheses"][k]["verdict"] == v for k, v in {"H1": "SUPPORTED", "H2": "SUPPORTED", "H11": "SUPPORTED", "EXPLORATORY_compute": "SUPPORTED"}.items()))
    ck("H11 no losses", len(scr - ctx) == 0)

    devi = json.loads((B / "E231_DEVIATIONS.json").read_text())["deviations"]
    ck("deviation recorded", len(devi) == 1 and devi[0]["id"] == "DEVIATION-1" and devi[0]["before_freeze"] != devi[0]["after_freeze"])
    ck("executed engine hash", devi[0]["after_freeze"] == rep["executed_engine_sha256"])
    rex = json.loads((B / "E231_PRIVATE_REEXECUTION.json").read_text())
    ck("same-code reproduction", rex.get("agreement") is True and rex.get("checks_total", 0) >= 24)
    ck("reproduction engine hash", rex.get("engine_sha256") == rep["executed_engine_sha256"])

    rpt = (B / "E231_FINAL_REPORT.md").read_text()
    pub = (B / "E231_PUBLIC_SUMMARY.md").read_text()
    ck("report status", STATUS in rpt and "TRANSFER_SUPPORTED" in rpt)
    ck("method-transfer limit", "method transfer, not content transfer" in rpt.lower() and "method transfer, not content transfer" in pub.lower())
    ck("public status", STATUS in pub)

    ok = all(x["ok"] for x in checks)
    print(json.dumps({"checks": len(checks), "passed": sum(x["ok"] for x in checks), "ok": ok,
                      "verification": "E231 record; engine source withheld; recomputed paired statistics"}))
    for x in checks:
        if not x["ok"]:
            print("FAIL", x["check"], x["detail"])
    return 0 if ok else 1


if __name__ == "__main__":
    sys.exit(main())
