#!/usr/bin/env python3
"""E119 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/"E119_RAW_RESULTS.json").read_text())
    g=d["grammar"]; ow=d["open_world"]; sh=d["six_hour"]; gates=d["gates"]
    check("E118 baseline reproduced", d["baseline"]["e118"]["tests"]==6 and d["baseline"]["e118"]["verifier"]=="26/26", d["baseline"]["e118"])
    check("macros learned", g["macro_count"]>=5, g["macro_count"])
    check("learned grammar gain >= 0.15", g["primary"]["gain"]>=0.15, g["primary"]["gain"])
    check("learned grammar p < 0.01", g["primary"]["mcnemar_p"]<0.01, g["primary"]["mcnemar_p"])
    check("learned grammar replicated p < 0.05", g["primary"]["second_p"]<0.05 and g["primary"]["second_gain"]>=0.15, g["primary"]["second_p"])
    check("real tasks attempted", ow["total"]>=6, ow["total"])
    check("real tasks independently checkable", ow["independently_checkable"]>=4, ow["independently_checkable"])
    sm=sh.get("summary",{})
    six_ok=(sh.get("state")=="DONE" and sm.get("status")=="PASS"
            and float(sm.get("elapsed_s",0))>=21600 and bool(sm.get("journal_ok")))
    if sh.get("state")=="DONE":
        check("6h PASS backed by >=21600s and intact journal",
              six_ok and gates["G7_six_hour"]["status"]=="PASS", sm)
    else:
        check("6h not claimed as PASS while running",
              sh.get("state")!="PASS" and gates["G7_six_hour"]["status"]!="PASS", sh.get("state"))
    check("external reviewer BLOCKED", gates["G6_external_reviewer"]["status"]=="BLOCKED")
    check("independent admin BLOCKED", gates["G8_independent_admin"]["status"]=="BLOCKED")
    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/"E119_GATE_MATRIX.json").read_text())["counts"], counts)
    check("no AGI claim", "not" in d["claim"].lower() or "NOT" in d["claim"], d["claim"])
    if (root/"E119_REMOTE_SEPARATE_USER.json").exists():
        rv=json.loads((root/"E119_REMOTE_SEPARATE_USER.json").read_text())
        check("separate-user 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())
