#!/usr/bin/env python3
"""E357 standalone offline verifier (stdlib + cryptography)."""
from __future__ import annotations
import hashlib, json, sys
from pathlib import Path
S="AGI: NOT ESTABLISHED · RSI: EXPERIMENTAL"
EX={"E357_MANIFEST.json","E357_SIGNED_BODY.json","E357_VERIFICATION_RESULTS.json","MANIFEST.json","MERKLE_ROOT.txt","PUBLICATION.json","E357_OMEGA_SEAL.json","E357_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(rows):
    sup=[r for r in rows if r["kind"]=="support"]; neg=[r for r in rows if r["kind"]=="negative"]
    H={"H1_all_supporting_bundles_verify":{"verdict":"SUPPORTED" if all(r["verifier_pass"] for r in sup) else "NOT_SUPPORTED","detail":"each supporting bundle's own verifier passes from a clean copy"},
       "H2_seal_bindings_match":{"verdict":"SUPPORTED" if all(r["merkle_match"] for r in sup) else "NOT_SUPPORTED","detail":"every supporting bundle's Merkle root equals its sealed index root"},
       "H3_negatives_kept":{"verdict":"SUPPORTED" if all(r["status"] in ("OMEGA_ALLOWED","PRE_OMEGA_MANIFESTED") for r in neg) else "NOT_SUPPORTED","detail":"every cited negative is present with an ALLOWED seal and its sealed verdict"},
       "H4_scope_present":{"verdict":"SUPPORTED","detail":"the scope text is attached to the claim"},
       "H5_external_review":{"verdict":"BLOCKED","detail":"external review NOT OBTAINED"}}
    ok=all(H[k]["verdict"]=="SUPPORTED" for k in ("H1_all_supporting_bundles_verify","H2_seal_bindings_match","H3_negatives_kept","H4_scope_present"))
    return H,("DOCKET_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/"E357_MANIFEST.json").read_text()); pre=json.loads((d/"E357_PREREGISTRATION.json").read_text())
    frz=json.loads((d/"E357_PREREGISTRATION_FREEZE.json").read_text()); rep=json.loads((d/"E357_RUN_REPORT.json").read_text())
    acc=json.loads((d/"E357_ACCEPTANCE_REGISTRY.json").read_text()); dev=json.loads((d/"E357_DEVIATIONS.json").read_text())
    ck("schema",man.get("schema")=="cain42.e357.manifest.v1" and rep.get("evolution")=="E357")
    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/"E357_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/"E357_PREREGISTRATION.json").read_bytes())==frz["preregistration_sha256"]==rep["preregistration_sha256"])
    ck("freeze precedes",frz["frozen_at"]<=rep["generated_at"])
    ck("source withheld",not any(p.name in ("run.py","verify.py") for p in d.rglob("*") if p.is_file()))
    rows=rep["rows"]; ck("rows",len(rows)==7)
    H,verdict=decide(rows); ck("verdict",verdict==rep["verdict"] and all(H[k]["verdict"]==rep["hypotheses"][k]["verdict"] for k in H))
    f=rep["finding"]; ck("finding",f["support_verified"]==sum(1 for r in rows if r["kind"]=="support" and r["verifier_pass"])
       and f["seal_match"]==sum(1 for r in rows if r["kind"]=="support" and r["merkle_match"])
       and f["negatives_sealed"]+f["negatives_pre_omega"]==sum(1 for r in rows if r["kind"]=="negative"))
    ck("claim",rep["claims"]["name"]=="CAIN-42 is an AGI–RSI superorganism" and "does not support general research superiority" in rep["claims"]["scope"])
    ck("acceptance",acc["verdict"]==rep["verdict"])
    ck("report verdict", f"**Verdict: {rep['verdict']}.**" in (d/"E357_FINAL_REPORT.md").read_text())
    ck("public summary", rep["verdict"] in (d/"E357_PUBLIC_SUMMARY.md").read_text()); ck("deviations",isinstance(dev.get("deviations"),list))
    ck("resources",rep["resources"]["model_calls"]==0)
    hl=man.get("headline") or {}
    ck("headline",hl.get("support_verified")==f["support_verified"] and hl.get("seal_match")==f["seal_match"]
       and hl.get("support_count")==f["support_count"])
    ch=[json.loads(l) for l in (d/"checkpoints/claim_chain.jsonl").read_text().splitlines()]
    prev="0"*64; rec=[]; ok=True
    for r in rows:
        hh=sha((prev+sha(json.dumps(r,sort_keys=True,separators=(",",":")))).encode()); rec.append(hh); prev=hh
    ck("chain",len(ch)==len(rows) and [x["hash"] for x in ch]==rec and [x["prev"] for x in ch]==(["0"*64]+rec[:-1]))
    cp=json.loads((d/"checkpoints/claim_chain.json").read_text()); ck("chain file",cp["count"]==len(ch) and cp["head"]==rec[-1])
    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())
