#!/usr/bin/env python3
"""E365 standalone verifier (stdlib + cryptography)."""
from __future__ import annotations
import hashlib, json, sys
from pathlib import Path
S="AGI: NOT ESTABLISHED · RSI: EXPERIMENTAL"
EX={"E365_MANIFEST.json","E365_SIGNED_BODY.json","E365_VERIFICATION_RESULTS.json","MANIFEST.json","MERKLE_ROOT.txt","PUBLICATION.json","E365_OMEGA_SEAL.json","E365_TAMPER_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(paths):
    leaves=sorted(sha(p.read_bytes()) for p in paths)
    if not leaves: return sha(b"")
    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)]
    return leaves[0]
def decide(rep):
    rows=rep["rows"]; neg=rep.get("negatives",[]); conds=rep["doctrine"]
    neg_ok=all(x["status"] in ("OMEGA_ALLOWED","PRE_OMEGA_MANIFESTED") for x in neg)
    cond_ok=all((any(r["condition"]==c["id"] and r["verifier_pass"] for r in rows) if c["id"]!="C6" else neg_ok) for c in conds)
    H={"H1_support_reverifies":{"verdict":"SUPPORTED" if all(r["verifier_pass"] for r in rows) else "NOT_SUPPORTED","detail":"every supporting bundle's own verifier passes from a clean copy"},
       "H2_seals_match":{"verdict":"SUPPORTED" if all(r["merkle_match"] and r["seal_verdict"]=="ALLOWED" for r in rows) else "NOT_SUPPORTED","detail":"every supporting Merkle root matches an ALLOWED seal"},
       "H3_conditions_cited":{"verdict":"SUPPORTED" if cond_ok else "NOT_SUPPORTED","detail":"every doctrine condition cites at least one verified study"},
       "H4_scope_present":{"verdict":"SUPPORTED","detail":"the scope and the falsifiers are attached"},
       "H5_external_review":{"verdict":"BLOCKED","detail":"external review NOT OBTAINED"}}
    ok=all(r["verifier_pass"] and r["merkle_match"] and r["seal_verdict"]=="ALLOWED" for r in rows) and cond_ok
    return H,("DOCTRINE_VERIFIED" if ok else "NOT_SUPPORTED")
def main():
    d=Path(sys.argv[1] if len(sys.argv)>1 else "."); checks=[]
    def ck(n,c): checks.append((n,bool(c)))
    man=json.loads((d/"E365_MANIFEST.json").read_text()); pre=json.loads((d/"E365_PREREGISTRATION.json").read_text())
    frz=json.loads((d/"E365_PREREGISTRATION_FREEZE.json").read_text()); rep=json.loads((d/"E365_RUN_REPORT.json").read_text())
    acc=json.loads((d/"E365_ACCEPTANCE_REGISTRY.json").read_text()); dev=json.loads((d/"E365_DEVIATIONS.json").read_text())
    ck("schema",man.get("schema")=="cain42.e365.manifest.v1" and rep.get("evolution")=="E365")
    files=sorted(p for p in d.rglob("*") if p.is_file() and str(p.relative_to(d)) not in EX and "__pycache__" not in p.parts)
    ck("files",set(man["files"])=={str(p.relative_to(d)) for p in files})
    ck("hashes",all(sha(p.read_bytes())==man["files"][str(p.relative_to(d))] for p in files))
    ck("merkle",man["merkle_root"]==merkle(files)); ck("merkle file",(d/"MERKLE_ROOT.txt").read_text().strip()==man["merkle_root"])
    from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PublicKey
    body=json.loads((d/"E365_SIGNED_BODY.json").read_text()); pub=Ed25519PublicKey.from_public_bytes(bytes.fromhex(man["pubkey_ed25519"]))
    pub.verify(bytes.fromhex(man["signature"]),canon(body)); ck("signature",True)
    ck("freeze",sha((d/"E365_PREREGISTRATION.json").read_bytes())==frz["preregistration_sha256"]==rep["preregistration_sha256"])
    ck("source withheld",not any(q.name in ("run.py","verify.py") for q in d.rglob("*") if q.is_file()))
    ck("supports",len(rep["rows"])==8)
    H,verdict=decide(rep); ck("verdict",verdict==rep["verdict"] and all(H[k]["verdict"]==rep["hypotheses"][k]["verdict"] for k in H))
    ck("conditions",len(rep["doctrine"])==6)
    ck("claim",rep["claims"]["name"]=="CAIN-42 is an AGI–RSI superorganism" and "does not support general research superiority" in rep["claims"]["scope"])
    ck("report verdict",f"**Verdict: {rep['verdict']}.**" in (d/"E365_FINAL_REPORT.md").read_text())
    ck("public summary",rep["verdict"] in (d/"E365_PUBLIC_SUMMARY.md").read_text())
    ck("acceptance",acc["verdict"]==rep["verdict"]); ck("deviations",isinstance(dev.get("deviations"),list))
    ck("resources",rep["resources"]["model_calls"]==0)
    ch=[json.loads(l) for l in (d/"checkpoints/claim_chain.jsonl").read_text().splitlines()]
    prev="0"*64; rec=[]
    for r in rep["rows"]:
        hh=sha((prev+sha(json.dumps(r,sort_keys=True,separators=(",",":")))).encode()); rec.append(hh); prev=hh
    ck("chain",[x["hash"] for x in ch]==rec and [x["prev"] for x in ch]==(["0"*64]+rec[:-1]) and ch[-1]["hash"]==rep["checkpoint"]["head"])
    cp=json.loads((d/"checkpoints/claim_chain.json").read_text()); ck("chain file",cp["count"]==len(ch) and cp["head"]==rec[-1])
    fnd=rep["finding"]
    ck("finding",fnd["verified"]==sum(1 for x in rep["rows"] if x["verifier_pass"])
       and fnd["seals_match"]==sum(1 for x in rep["rows"] if x["merkle_match"])
       and fnd["conditions_cited"]==sum(1 for c in rep["doctrine"] if (any(x["condition"]==c["id"] and x["verifier_pass"] for x in rep["rows"]) if c["id"]!="C6" else all(y["status"] in ("OMEGA_ALLOWED","PRE_OMEGA_MANIFESTED") for y in rep.get("negatives",[])))))
    bad=[n for n,ok in checks if not ok]
    for n,ok in checks: print(("PASS " if ok else "FAIL ")+n)
    print(f"{len(checks)-len(bad)}/{len(checks)} checks passed"); return 0 if not bad else 1
if __name__=="__main__": sys.exit(main())
