#!/usr/bin/env python3
"""Standalone E369-U verifier — stdlib only, imports no CAIN code."""
from __future__ import annotations
import hashlib, json, sys
from pathlib import Path
FAILS=[]; CHECKS=[0]
def ck(c,n,d=""):
    CHECKS[0]+=1
    if not c: FAILS.append(f"{n}: {d}")
def sha(b): return hashlib.sha256(b).hexdigest()
def canon(o): return json.dumps(o,sort_keys=True,separators=(",",":"),ensure_ascii=False).encode()
def main(d):
    b=Path(d); rep=json.loads((b/"E369U_RUN_REPORT.json").read_text()); pre=json.loads((b/"E369U_PREREGISTRATION.json").read_text()); man=json.loads((b/"E369U_MANIFEST.json").read_text()); frz=json.loads((b/"E369U_PREREGISTRATION_FREEZE.json").read_text()); salts=json.loads((b/"E369U_SALT_REVEALED.json").read_text())
    ck(rep["schema"]=="cain42.e369u.run.v1","schema"); ck(rep["evolution"]=="E369-U","evolution"); ck(rep["model_calls"]==0 and rep["api_spend_usd"]==0.0,"zero calls"); ck(sha((b/"E369U_PREREGISTRATION.json").read_bytes())==frz["preregistration_sha256"],"prereg"); ck(pre["salt_commitment_sha256"]==rep["salt_commitment_sha256"],"salts")
    for s in ("primary","replication"): ck(sha(bytes.fromhex(salts[s]))==pre["salt_commitment_sha256"][s],f"salt {s}")
    eps=rep["episodes"]; ck(len(eps)==48,"48 episodes"); ck(sum(1 for e in eps if e["salt"]=="primary")==24,"24 primary")
    def comp_det(e):
        E=set(e["E"]); cursor=0
        for use in range(60):
            comp=[r for r in e["comp_perm"] if r not in E]
            if use>=10:
                block=[comp[(cursor+k)%len(comp)] for k in range(min(32,len(comp)))]
                if e["r2"] in block: return use
            cursor=(cursor+32)%len(comp)
        return None
    for e in eps:
        tag=e["id"]; r0=int(e["r0_mask"],16); f1=r0^(1<<e["r1"]); f2=r0 if e["drift"]=="INSIDE" else f1^(1<<e["r2"])
        ck(f1==int(e["f1_mask"],16) and f2==int(e["f2_mask"],16),f"{tag} masks"); ck(e["r1"] not in e["cert_rows"],f"{tag} r1 outside cert"); ck(e["E"]==[e["r1"]],f"{tag} E")
        p=e["policies"]; ck(p["PERMANENT"]["wrong_uses"]==50 and p["PERMANENT"]["detection_use"] is None,f"{tag} permanent")
        ck(p["UNION"]["final_correct"] is True,f"{tag} union exact"); ck(p["FULL"]["wrong_uses"]==0 and p["FULL"]["detection_use"]==10,f"{tag} full"); ck(p["FULL"]["labels"]==256*60,f"{tag} full labels")
        ck(p["UNION"]["labels_per_use"]<=0.14*256,f"{tag} union cost")
        if e["drift"]=="INSIDE":
            ck(p["COMPLEMENT_ONLY"]["wrong_uses"]==50 and p["COMPLEMENT_ONLY"]["detection_use"] is None,f"{tag} comp blind")
            ck(p["E_ONLY"]["wrong_uses"]==0 and p["E_ONLY"]["detection_use"]==10,f"{tag} E only")
            ck(p["UNION"]["wrong_uses"]==0 and p["UNION"]["detection_use"]==10,f"{tag} union inside")
        else:
            det=comp_det(e)
            ck(p["COMPLEMENT_ONLY"]["detection_use"]==det and p["COMPLEMENT_ONLY"]["wrong_uses"]==det-10,f"{tag} comp outside")
            ck(p["E_ONLY"]["wrong_uses"]==50 and p["E_ONLY"]["detection_use"] is None,f"{tag} E blind")
            ck(p["UNION"]["detection_use"]==det and p["UNION"]["wrong_uses"]==det-10,f"{tag} union outside")
    prev="0"*64; ok=True
    for i,row in enumerate(rep["chain"]):
        hh=sha((prev+sha(canon(eps[i]))).encode())
        if row["hash"]!=hh or row["prev"]!=prev or row["i"]!=i: ok=False
        prev=hh
    ck(ok,"chain"); ck(len(rep["chain"])==48,"chain length")
    def ev(g):
        n=len(g); out=[e for e in g if e["drift"]=="OUTSIDE"]; ins=[e for e in g if e["drift"]=="INSIDE"]
        a=sum(1 for e in out if e["policies"]["COMPLEMENT_ONLY"]["wrong_uses"]<=7); b=sum(1 for e in ins if e["policies"]["COMPLEMENT_ONLY"]["wrong_uses"]==50)
        c=sum(1 for e in ins if e["policies"]["E_ONLY"]["wrong_uses"]==0); d=sum(1 for e in out if e["policies"]["E_ONLY"]["wrong_uses"]==50)
        e1=sum(1 for e in g if (e["policies"]["UNION"]["wrong_uses"]==0 if e["drift"]=="INSIDE" else e["policies"]["UNION"]["wrong_uses"]<=7))
        f=sum(1 for e in g if e["policies"]["UNION"]["labels_per_use"]<=0.14*256); h=sum(1 for e in g if e["policies"]["UNION"]["final_correct"])
        return {"H1":a==len(out) and b==len(ins),"H2":c==len(ins) and d==len(out),"H3":e1==n,"H4":f==n,"H5":h==n}
    p=ev([e for e in eps if e["salt"]=="primary"]); r=ev([e for e in eps if e["salt"]=="replication"])
    for k in ("H1","H2","H3","H4","H5"): ck(p[k],f"{k} primary")
    ck(all(r[k] for k in ("H1","H2","H3","H4","H5")),"H6 replication")
    for k in ("H1_complement_blind_inside","H2_e_only_blind_outside","H3_union_covers_both","H4_union_cost","H5_union_exact_after","H6_replication"): ck(rep["hypotheses"][k]["verdict"]=="SUPPORTED",f"reported {k}")
    ck(rep["hypotheses"]["H7_external_review"]["verdict"]=="BLOCKED","H7"); ck(rep["verdict"]=="EXCEPTION_LEASE_UNION_SUPPORTED","verdict"); ck(rep["replication_verdict"]=="SUPPORTED","replication verdict")
    a=rep["summaries"]["all"]; ck(a["final_correct"]["UNION"]==48,"summary union exact"); ck(a["by_drift"]["INSIDE"]["wrong_uses_mean"]["COMPLEMENT_ONLY"]==50,"summary inside blind"); ck(a["by_drift"]["OUTSIDE"]["wrong_uses_mean"]["E_ONLY"]==50,"summary outside blind")
    try:
        from cryptography.hazmat.primitives import serialization
        body={k:v for k,v in man.items() if k!="signature"}; pub=serialization.load_pem_public_key((b/"E369U_PUBKEY.pem").read_bytes()); pub.verify(bytes.fromhex(man["signature"]),canon(body)); ck(True,"signature")
    except Exception as ex: ck(False,"signature",str(ex))
    files=sorted(p for p in b.rglob("*") if p.is_file() and p.name not in {"E369U_MANIFEST.json","E369U_SIGNED_BODY.json","E369U_VERIFICATION_RESULTS.json","E369U_TAMPER_RESULTS.json","MANIFEST.json","MERKLE_ROOT.txt","PUBLICATION.json","E369U_OMEGA_SEAL.json"} and "__pycache__" not in p.parts)
    leaves=sorted(sha(p.read_bytes()) for p in files)
    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)]
    ck(leaves[0]==man["merkle_root"],"merkle"); ck(not any(p.suffix==".py" and "verify" not in p.name and "tamper" not in p.name for p in files),"no source"); ck(any(p.name=="verify_e369u_offline.py" for p in files),"verifier shipped")
    print(f"E369-U offline verification: {CHECKS[0]-len(FAILS)}/{CHECKS[0]} checks passed")
    for f in FAILS[:20]: print("FAIL:",f)
    return 0 if not FAILS else 1
if __name__=="__main__": sys.exit(main(sys.argv[1] if len(sys.argv)>1 else "."))
