#!/usr/bin/env python3
"""Standalone E372-N 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/"E372N_RUN_REPORT.json").read_text()); pre=json.loads((b/"E372N_PREREGISTRATION.json").read_text()); man=json.loads((b/"E372N_MANIFEST.json").read_text()); frz=json.loads((b/"E372N_PREREGISTRATION_FREEZE.json").read_text()); salts=json.loads((b/"E372N_SALT_REVEALED.json").read_text())
    ck(rep["schema"]=="cain42.e372n.run.v1","schema"); ck(rep["evolution"]=="E372-N","evolution"); ck(rep["model_calls"]==0 and rep["api_spend_usd"]==0.0,"zero calls"); ck(sha((b/"E372N_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")
    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["E"]==[e["r1"]],f"{tag} E")
        p=e["policies"]; ck(len(p)==15,f"{tag} 15 cells")
        for pol in ("SINGLE","R3","SEL","FULL"):
            ck(p[f"{pol}@0.0"]["final_correct"] is True and p[f"{pol}@0.0"]["false_revocations"]==0,f"{tag} {pol} clean")
        ck(p["TOL1@0.0"]["wrong_uses"]==50 and p["TOL1@0.0"]["final_correct"] is False,f"{tag} tolerance blind")
        ck(p["R3@0.01"]["final_correct"] is True and p["R3@0.01"]["false_revocations"]<=2,f"{tag} R3 noisy")
        ck(p["SEL@0.05"]["labels"]<=0.7*p["R3@0.05"]["labels"],f"{tag} SEL cost")
        ck(p["FULL@0.05"]["labels"]==15360,f"{tag} full labels")
    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); c=g[0]["policies"] if g else {}
        clean=sum(1 for e in g if all(e["policies"][f"{p}@0.0"]["final_correct"] and e["policies"][f"{p}@0.0"]["false_revocations"]==0 for p in ("SINGLE","R3","SEL","FULL")))
        single=sum(1 for e in g if e["policies"]["SINGLE@0.01"]["false_revocations"]>=1)
        r3=sum(1 for e in g if e["policies"]["R3@0.01"]["false_revocations"]<=2 and e["policies"]["R3@0.01"]["final_correct"])
        sel=sum(1 for e in g if e["policies"]["SEL@0.05"]["labels"]<=0.7*e["policies"]["R3@0.05"]["labels"])
        tol=sum(1 for e in g if e["policies"]["TOL1@0.0"]["wrong_uses"]==50)
        uni=sum(1 for e in g if e["policies"]["R3@0.0"]["final_correct"])
        return {"H1":clean==n,"H2":single>=n//2 and r3>=n-2,"H3":sel==n,"H4":tol==n,"H5":uni==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_clean_lease","H2_single_noise_false_revocations","H3_selective_is_cheaper","H4_tolerance_hides_drift","H5_union_coverage_kept","H6_replication"): ck(rep["hypotheses"][k]["verdict"]=="SUPPORTED",f"reported {k}")
    ck(rep["hypotheses"]["H7_external_review"]["verdict"]=="BLOCKED","H7"); ck(rep["verdict"]=="NOISY_UNION_LEASE_MAPPED","verdict"); ck(rep["replication_verdict"]=="SUPPORTED","replication")
    a=rep["summaries"]["all"]["cells"]
    ck(a["TOL1@0.0"]["final_correct"]==0,"summary tol"); ck(a["R3@0.01"]["final_correct"]==48,"summary R3"); ck(a["SINGLE@0.05"]["final_correct"]<10,"summary single 5%")
    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/"E372N_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 {"E372N_MANIFEST.json","E372N_SIGNED_BODY.json","E372N_VERIFICATION_RESULTS.json","E372N_TAMPER_RESULTS.json","MANIFEST.json","MERKLE_ROOT.txt","PUBLICATION.json","E372N_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_e372n_offline.py" for p in files),"verifier shipped")
    print(f"E372-N 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 "."))
