#!/usr/bin/env python3
"""E425-L ledger verifier — imports no CAIN code. Recomputes every gap and hypothesis
from the cited snapshot numbers and checks the signed manifest."""
import hashlib, json, sys
from pathlib import Path
from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PublicKey
S="AGI: NOT ESTABLISHED · RSI: EXPERIMENTAL"
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"")
class Fail(Exception): pass
def ck(c,m):
    if not c: raise Fail(m)
def main(b):
    B=Path(b); r=json.loads((B/"LEDGER_RUN_REPORT.json").read_text())
    pre=json.loads((B/"LEDGER_PREREGISTRATION.json").read_text()); frz=json.loads((B/"LEDGER_PREREGISTRATION_FREEZE.json").read_text())
    man=json.loads((B/"LEDGER_MANIFEST.json").read_text()); src=json.loads((B/"LEDGER_SOURCES.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={"LEDGER_MANIFEST.json","LEDGER_SIGNED_BODY.json","MANIFEST.json","MERKLE_ROOT.txt","PUBLICATION.json","LEDGER_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/"LEDGER_PREREGISTRATION.json").read_bytes())==frz["preregistration_sha256"],"preregistration hash")
    ok(r["status"]==S and len(src)==8,"status / eight sources")
    ok(all(s["seal"] and s["seal_verdict"]=="ALLOWED" and s["verdict"] for s in src.values()),"all cited seals ALLOWED")
    e=sources=src
    parity={
      "E419-S":{"single":[e["E419-S"]["headline"]["solo_salt1"],e["E419-S"]["headline"]["solo_salt2"]],
                "colony":[e["E419-S"]["headline"]["shared_salt1"],e["E419-S"]["headline"]["shared_salt2"]]},
      "SMF":{"single":[e["SMF"]["headline"]["generalist_salt1"],json.loads((B/"SMF_ARMS.json").read_text())["salt2"]["GENERALIST"]],
             "colony":[e["SMF"]["headline"]["full_salt1"],e["SMF"]["headline"]["full_salt2"]]},
      "E422-M":{"single":[e["E422-M"]["headline"]["single_correct"]],"colony":[e["E422-M"]["headline"]["shared_correct"][0]]}}
    gaps={k:[c-s for c,s in zip(v["colony"],v["single"])] for k,v in parity.items()}
    ok(all(abs(g)<=2 for v in gaps.values() for g in v),"parity gaps <= 2")
    div=e["E420-M"]["headline"]; dg=div["primary"]["gen3"]["rate"]-div["solo"]["gen3"]["rate"]
    ok(dg>=0.10,"content exception")
    p=e["PRSI"]["headline"]; over=[p["top3_any"][0]-p["oracle"][0],p["top3_any"][1]-p["oracle"][1]]; lift=[p["top3_any"][0]-p["top1"][0],p["top3_any"][1]-p["top1"][1]]
    ok(over[0]<=1e-9 and 0<over[1]<=0.05 and lift[0]==0,"bounded combination gain")
    ok(e["E422-N"]["verdict"] and e["E423-N"]["verdict"],"axes classified")
    H={"H1_equal_experience_parity":all(abs(g)<=2 for v in gaps.values() for g in v),
       "H2_content_exception":dg>=0.10,
       "H3_bounded_combination_gain":(over[0]<=1e-9 and 0<over[1]<=0.05 and lift[0]==0),
       "H4_axes_classified":bool(e["E422-N"]["verdict"] and e["E423-N"]["verdict"]),
       "H5_evidence_integrity":all(s["seal"] and s["seal_verdict"]=="ALLOWED" and s["verdict"] for s in src.values())}
    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"]==("EQUAL_EXPERIENCE_LEDGER_VERIFIED" if all(H.values()) else "NOT_SUPPORTED"),"verdict")
    ok("falsifier" in r["doctrine"] and "identical total experience" in r["doctrine"]["falsifier"],"falsifier present")
    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)
