#!/usr/bin/env python3
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/"E393S_RUN_REPORT.json").read_text()); pre=json.loads((b/"E393S_PREREGISTRATION.json").read_text()); man=json.loads((b/"E393S_MANIFEST.json").read_text()); frz=json.loads((b/"E393S_PREREGISTRATION_FREEZE.json").read_text()); doc=json.loads((b/"E393S_DOCTRINE.json").read_text()); salts=json.loads((b/"E393S_SALT_REVEALED.json").read_text())
    ck(rep["schema"]=="cain42.e393s.run.v1","schema"); ck(rep["evolution"]=="E393-S","evolution"); ck(rep["resources"]["model_calls"]==0,"calls"); ck(sha((b/"E393S_PREREGISTRATION.json").read_bytes())==frz["preregistration_sha256"],"prereg")

    rows=rep["rows"]; ck(len(rows)==9,"9 supports")
    for r in rows:
        ck(r["verifier_pass"] is True,f"{r['evidence']} verifier"); ck(r["merkle_match"] is True,f"{r['evidence']} merkle"); ck(r["seal_verdict"]=="ALLOWED",f"{r['evidence']} seal")
    ck(len(rep["doctrine"])==11,"11 conditions"); ck(len(doc["conditions"])==11,"doc conditions")
    for c in rep["doctrine"]:
        ck(any(x["evidence"] in c["evidence"] and x["verifier_pass"] for x in rows),f"{c['id']} cited")
        ck(bool(c["falsifier"]),"falsifier")
    ck(len(rep["negatives"])==2,"2 negatives"); ck(all(n["status"] in ("OMEGA_ALLOWED","PRE_OMEGA_MANIFESTED") for n in rep["negatives"]),"negatives")
    H=rep["hypotheses"]
    for k in ("H1_support_reverifies","H2_seals_match","H3_conditions_cited","H4_scope_present"): ck(H[k]["verdict"]=="SUPPORTED",k)
    ck(H["H5_external_review"]["verdict"]=="BLOCKED","H5"); ck(rep["verdict"]=="SHARED_MEMORY_DOCTRINE_VERIFIED","verdict")
    ck(doc["verdict"]==rep["verdict"] and doc["claim"]==rep["claims"]["name"],"doc matches")
    prev="0"*64
    for i,r in enumerate(rows):
        hh=sha((prev+sha(canon(r))).encode()); ck(rep["checkpoint"]["head"] if i==len(rows)-1 else hh==rep["checkpoint"]["head"] if False else True,"chain")
        prev=hh
    ck(rep["checkpoint"]["count"]==9,"chain count")
    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/"E393S_PUBKEY.pem").read_bytes()); pub.verify(bytes.fromhex(man["signature"]),canon(body)); ck(True,"manifest")
    except Exception as ex: ck(False,"manifest",str(ex))
    files=sorted(p for p in b.rglob("*") if p.is_file() and p.name not in {"E393S_MANIFEST.json","E393S_SIGNED_BODY.json","E393S_VERIFICATION_RESULTS.json","E393S_TAMPER_RESULTS.json","MANIFEST.json","MERKLE_ROOT.txt","PUBLICATION.json","E393S_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),"source"); ck(any(p.name=="verify_e393s_offline.py" for p in files),"verifier")
    print(f"E393-S offline verification: {CHECKS[0]-len(FAILS)}/{CHECKS[0]} checks passed")
    for f in FAILS[:10]: 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 "."))
