#!/usr/bin/env python3
"""E442-X verifier — imports no CAIN code. Recomputes the price table and the hypotheses."""
import hashlib,json,sys
from pathlib import Path
from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PublicKey
S="AGI: NOT ESTABLISHED · RSI: EXPERIMENTAL"
CELLS=[(f,g) for f in range(4) for g in range(4)]
POL=["trust1","union3","hash3","union_hash","full_scan"]
def canon(o): return json.dumps(o,sort_keys=True,separators=(",",":"),ensure_ascii=False).encode()
def sha(b): return hashlib.sha256(b).hexdigest()
def merkle(ps):
    l=sorted(sha(p.read_bytes()) for p in ps)
    while len(l)>1:
        if len(l)%2: l.append(l[-1])
        l=[sha((l[i]+l[i+1]).encode()) for i in range(0,len(l),2)]
    return l[0] if l else sha(b"")
def exact(c):
    f,g=c
    if f==0 and g==0: return "trust1"
    if f>0 and g==0: return "union3"
    if f==0 and g>0: return "hash3"
    if f>0 and g>0 and f<3: return "union_hash"
    return "full_scan"
def h(*a): return int(hashlib.sha256("|".join(map(str,a)).encode()).hexdigest()[:8],16)
class Fail(Exception): pass
def ck(c,m):
    if not c: raise Fail(m)
def main(b):
    B=Path(b);r=json.loads((B/"E442X_RUN_REPORT.json").read_text())
    pre=json.loads((B/"E442X_PREREGISTRATION.json").read_text());frz=json.loads((B/"E442X_PREREGISTRATION_FREEZE.json").read_text())
    salts=json.loads((B/"SALTS.json").read_text());man=json.loads((B/"E442X_MANIFEST.json").read_text());n=0
    def ok(c,m):
        nonlocal n;ck(c,m);n+=1
    pub=Ed25519PublicKey.from_public_bytes(bytes.fromhex(man["pubkey_ed25519"]))
    pub.verify(bytes.fromhex(man["signature"]),canon({k:v for k,v in man.items() if k!="signature"}));ok(True,"manifest signature")
    EX={"E442X_MANIFEST.json","E442X_SIGNED_BODY.json","MANIFEST.json","MERKLE_ROOT.txt","PUBLICATION.json","E442X_OMEGA_SEAL.json"}
    fs=sorted(p for p in B.rglob("*") if p.is_file() and str(p.relative_to(B)) not in EX and "__pycache__" not in p.parts and not p.name.endswith(("-wal","-shm")))
    ok({str(p.relative_to(B)):sha(p.read_bytes()) for p in fs}==man["files"],"file hashes")
    ok(merkle(fs)==man["merkle_root"],"merkle root")
    ok(sha((B/"E442X_PREREGISTRATION.json").read_bytes())==frz["preregistration_sha256"],"preregistration hash")
    ok(pre["salts_commitment"]==frz["salt_commitments"] and all(sha(salts[k].encode())==pre["salts_commitment"][k] for k in ("salt1","salt2")),"salts")
    ok(r["status"]==S and r["model_calls"]==0,"status / zero model calls")
    for salt in ("salt1","salt2"):
        nm=sum(1 for c in CELLS if exact(c) in sorted(POL,key=lambda p:h(salts[salt],c,p))[:3])
        arms={"HONEST":(16,80),"TRUST_DONE":(0,64),"SAMPLE25":(4,84),"NO_MEMORY":(nm,48)}
        for k in (0,1,2,4,8):
            arms[f"DECISION_{k}"]=(16,80+16*k); arms[f"RERUN_ALL_{k}"]=(16,80+80*k)
        for k,v in arms.items():
            ok(v[0]==r["measurements"][salt][k]["accuracy"] and v[1]==r["measurements"][salt][k]["trials"],f"{salt}: {k}")
    a1,a2=r["measurements"]["salt1"],r["measurements"]["salt2"]
    H={"H1_trust":a1["TRUST_DONE"]["accuracy"]==0 and a2["TRUST_DONE"]["accuracy"]==0,
       "H2_decision":a1["DECISION_1"]["accuracy"]==16 and a2["DECISION_1"]["accuracy"]==16 and a1["DECISION_1"]["trials"]<=96,
       "H3_rerun_all":a1["RERUN_ALL_1"]["accuracy"]==16 and a2["RERUN_ALL_1"]["accuracy"]==16 and a1["RERUN_ALL_1"]["trials"]>=a1["DECISION_1"]["trials"]+48,
       "H4_sample":a1["SAMPLE25"]["accuracy"]<=8 and a2["SAMPLE25"]["accuracy"]<=8,
       "H5_no_memory":a1["NO_MEMORY"]["accuracy"]<=12 and a2["NO_MEMORY"]["accuracy"]<=12}
    for k,v in H.items(): ok(r["hypotheses"][k]["verdict"]==("SUPPORTED" if v else "NOT_SUPPORTED"),f"reported {k}")
    ok(r["hypotheses"]["H6_external_review"]["verdict"]=="BLOCKED","reported H6")
    ok(r["verdict"]==("DENIAL_PRICE_MAPPED" if all(H.values()) else "NOT_SUPPORTED"),"verdict")
    print(f"OK {n}/{n}  verdict={r['verdict']}")
if __name__=="__main__":
    try: main(sys.argv[1] if len(sys.argv)>1 else "."); sys.exit(0)
    except Fail as ex: print(f"VERIFY FAILED: {ex}"); sys.exit(1)
