#!/usr/bin/env python3
"""E118 standalone verifier. Standard library only; imports no CAIN code."""
from __future__ import annotations
import hashlib, json, math, sys
from pathlib import Path
C = []
def check(n, ok, d=""): C.append((n, bool(ok), str(d)))
def mcnemar(a,b):
    ao=sum(1 for x,y in zip(a,b) if x and not y); bo=sum(1 for x,y in zip(a,b) if y and not x); n=ao+bo
    if n==0: return 1.0
    p=[math.comb(n,i)*0.5**n for i in range(n+1)]
    return min(1.0,sum(x for x in p if x<=p[ao]+1e-15))
def main():
    root=Path(sys.argv[1] if len(sys.argv)>1 else ".")
    import ast
    tree=ast.parse(Path(__file__).read_text()); banned=[]
    for node in ast.walk(tree):
        if isinstance(node,ast.Import): banned += [a.name for a in node.names if a.name.split(".")[0]=="cain"]
        elif isinstance(node,ast.ImportFrom) and (node.module or "").split(".")[0]=="cain": banned.append(node.module)
    check("verifier imports no CAIN code", not banned, banned)
    man=json.loads((root/"MANIFEST.json").read_text())
    bad=[r for r,h in man["files"].items() if not (root/r).exists() or hashlib.sha256((root/r).read_bytes()).hexdigest()!=h]
    check(f"manifest hashes ({len(man['files'])})", not bad, bad[:5])
    d=json.loads((root/"E118_RAW_RESULTS.json").read_text())
    base,o,si,rw,tr,col,gates=d["baseline"],d["ood"],d["self_improvement"],d["real_world"],d["transfer"],d["collective"],d["gates"]
    check("E117 baseline reproduced", base["e117"]["tests"]==6 and base["e117"]["verifier"]=="28/28", base["e117"])
    check("E116 baseline reproduced", base["e116"]["tests"]==6 and base["e116"]["verifier"]=="54/54", base["e116"])
    check("E115 baseline reproduced", base["e115"]["tests"]==18 and base["e115"]["verifier"]=="7/7", base["e115"])
    check("held-out primitives exist", len(o["heldout_ops"])>=8 and len(o["seen_ops"])>=8, (len(o["seen_ops"]),len(o["heldout_ops"])))
    pr=o["primary"]
    f=[r["correct"] for r in o["raw"]["sealed"]["full"]]; b=[r["correct"] for r in o["raw"]["sealed"][pr["strongest_baseline"]]]
    check("primary accuracy recomputed", round(sum(f)/len(f),4)==pr["full_accuracy"], (sum(f),len(f)))
    check("primary gain >= 0.15", pr["gain"]>=0.15, pr["gain"])
    check("primary p < 0.01", pr["mcnemar_p"]<0.01, pr["mcnemar_p"])
    check("primary replicated p < 0.05", pr["second_p"]<0.05 and pr["second_gain"]>=0.15, pr["second_p"])
    check("three capabilities", len(o["capabilities"])==3)
    check("at least two capabilities pass", sum(1 for c in o["capabilities"].values() if c["passed"])>=2, [c["passed"] for c in o["capabilities"].values()])
    check("memory beats no memory", o["memory"]["full_with_memory"]>o["memory"]["depth3_no_memory"] and o["memory"]["mcnemar_memory"]<0.05, o["memory"])
    check("memory survives restart", o["memory"]["restart_retained"]>0.9, o["memory"]["restart_retained"])
    check("self-improvement positive and not enabled", si["status"].startswith("PROMOTED") and si["promotion"]["enabled"] is False, si["status"])
    check("self-improvement sealed p<0.05", si["sealed"]["mcnemar_p"]<0.05 and si["sealed2"]["mcnemar_p"]<0.05, si["sealed"])
    check("real datasets improved", rw["counts"]["improved"]>=2, rw["counts"])
    check("transfer supported", tr["counts"]["statistically_supported"]>=2, tr["counts"])
    check("collective routing beats single specialist", col["arms"]["C_specialist_team_routed"]["accuracy"]>col["arms"]["A_best_single_agent"]["accuracy"], col["arms"])
    valid={"PASS","PARTIAL","FAIL","BLOCKED","NOT TESTED"}
    check("gate statuses valid", all(v["status"] in valid for v in gates.values()))
    counts={}
    for v in gates.values(): counts[v["status"]]=counts.get(v["status"],0)+1
    check("gate counts consistent", counts==json.loads((root/"E118_GATE_MATRIX.json").read_text())["counts"], counts)
    check("primary gate PASS", gates["G4_primary_ood"]["status"]=="PASS")
    check("continuous 6h not PASS", gates["G11_continuous_6h"]["status"]!="PASS", gates["G11_continuous_6h"]["status"])
    check("external reviewer BLOCKED", gates["G10_external_reviewer"]["status"]=="BLOCKED")
    check("no proof of AGI claimed", "NOT" in d["claim"] or "not" in d["claim"], d["claim"])
    if (root/"E118_REMOTE_VERIFICATION.json").exists():
        rv=json.loads((root/"E118_REMOTE_VERIFICATION.json").read_text())
        check("remote verifier execution passed", rv.get("returncode")==0, rv.get("tail"))
    passed=sum(1 for _,ok,_ in C if ok)
    for n,ok,x in C: print(("PASS " if ok else "FAIL ")+n+(f" [{x}]" if (not ok and x) else ""))
    print(f"\n{passed}/{len(C)} checks passed")
    return 0 if passed==len(C) else 1
if __name__=="__main__": raise SystemExit(main())
