#!/usr/bin/env python3
import hashlib,json,sys
from pathlib import Path
S="AGI: NOT ESTABLISHED · RSI: EXPERIMENTAL"
EX={"E295_MANIFEST.json","MANIFEST.json","E295_SIGNED_BODY.json","MERKLE_ROOT.txt","PUBLICATION.json","E295_OMEGA_SEAL.json","E295_VERIFICATION_RESULTS.json"}
def canon(o): return json.dumps(o,sort_keys=True,separators=(",",":"),ensure_ascii=False).encode()
def sha(b): return hashlib.sha256(b if isinstance(b,bytes) else b.encode()).hexdigest()
def merkle(ps):
    lv=sorted(sha(p.read_bytes()) for p in ps)
    if not lv: return sha(b"")
    while len(lv)>1:
        if len(lv)%2: lv.append(lv[-1])
        lv=[sha((lv[i]+lv[i+1]).encode()) for i in range(0,len(lv),2)]
    return lv[0]
def main(b):
    ck=[]; add=lambda n,ok,d=None: ck.append({"check":n,"ok":bool(ok),"detail":d})
    pre=json.loads((b/"E295_PREREGISTRATION.json").read_text()); frz=json.loads((b/"E295_PREREGISTRATION_FREEZE.json").read_text()); rep=json.loads((b/"E295_RUN_REPORT.json").read_text())
    add("prereg",sha((b/"E295_PREREGISTRATION.json").read_bytes())==frz["preregistration_sha256"])
    add("cases30",len(rep["cases"])==30,len(rep["cases"]))
    add("reproduced",all(c["reproduced"] for c in rep["cases"]))
    fails=[c for c in rep["cases"] if c["role"]=="false_accept"]; ctrl=[c for c in rep["cases"] if c["role"]=="control"]
    add("six_failures",len(fails)==6)
    h1=all(c["rejected"] for c in fails); h2=sum(1 for c in ctrl if not c["rejected"])>=22
    add("h1_recomputed",(rep["hypotheses"]["H1_rejects_all_false"]["verdict"]=="SUPPORTED")==h1)
    add("h2_recomputed",(rep["hypotheses"]["H2_keeps_controls"]["verdict"]=="SUPPORTED")==h2)
    v="COMPLETE_VERSION_SPACE_CATCHES_BLIND_SPOT" if h1 and h2 else "PARTIAL" if h1 else "NOT_SUPPORTED"
    add("verdict",rep["verdict"]==v,v)
    add("zero_labels",rep["resources"]["new_labels"]==0 and rep["resources"]["model_calls"]==0)
    add("status",rep["status"]==S)
    mp=b/"E295_MANIFEST.json"
    if mp.exists():
        m=json.loads(mp.read_text()); signed=(b/"E295_SIGNED_BODY.json").read_bytes()
        add("signed",canon({k:v for k,v in m.items() if k!="signature"})==signed)
        fs=sorted(x for x in b.rglob("*") if x.is_file() and x.name not in EX and "__pycache__" not in x.parts)
        add("hashes",m["files"]=={str(x.relative_to(b)):sha(x.read_bytes()) for x in fs})
        add("merkle",merkle(fs)==m["merkle_root"] and (b/"MERKLE_ROOT.txt").read_text().strip()==m["merkle_root"])
        try:
            from cryptography.hazmat.primitives import serialization
            pub=bytes.fromhex(m["pubkey_ed25519"]); pk=serialization.load_der_public_key(b"\x30\x2a\x30\x05\x06\x03\x2b\x65\x70\x03\x21\x00"+pub)
            pk.verify(bytes.fromhex(m["signature"]),signed); add("signature",True)
        except Exception as e: add("signature",False,str(e)[:120])
    p=sum(1 for x in ck if x["ok"]); print(json.dumps({"schema":"cain42.e295.verification.v1","checks":len(ck),"passed":p,"failed":[x for x in ck if not x["ok"]],
      "verdict":rep["verdict"],"h1":h1,"h2":h2,"kept":sum(1 for c in ctrl if not c["rejected"]),"rejected_false":sum(1 for c in fails if c["rejected"])})); return 0 if p==len(ck) else 1
if __name__=="__main__": sys.exit(main(Path(sys.argv[1] if len(sys.argv)>1 else Path(__file__).resolve().parent)))
