#!/usr/bin/env python3
import hashlib,json,re,sys
from pathlib import Path
FAILS=[]; CHECKS=[0]
Q="superorganism capability not supported by E155 (sealed, preregistered); E356 supports only governed collective correctness under Byzantine error"
KEY=["clawx-site/index.html","platform-gateway/frontend/index.html","platform-gateway/frontend/mcpgate_home.html","clawx-site/labs.html","clawx-site/agi-evidence-index.html","clawx-site/llms.txt","platform-gateway/frontend/llms.txt"]
def ck(c,n,d=""):
    CHECKS[0]+=1
    if not c: FAILS.append(f"{n}: {d}")
def sha(b): return hashlib.sha256(b if isinstance(b,bytes) else b.encode()).hexdigest()
def canon(o): return json.dumps(o,sort_keys=True,separators=(",",":"),ensure_ascii=False).encode()
def plain(s): return re.sub(r"\s+"," ",re.sub(r"<[^>]+>"," ",s))
def main(d):
    b=Path(d); ROOT=Path('.'); rep=json.loads((b/"E398Q_RUN_REPORT.json").read_text()); pre=json.loads((b/"E398Q_PREREGISTRATION.json").read_text()); man=json.loads((b/"E398Q_MANIFEST.json").read_text()); frz=json.loads((b/"E398Q_PREREGISTRATION_FREEZE.json").read_text()); scan=json.loads((b/"E398Q_QUALIFIER_SCAN.json").read_text())
    ck(rep["schema"]=="cain42.e398q.run.v1","schema"); ck(rep["evolution"]=="E398-Q","evolution"); ck(rep["model_calls"]==0,"calls"); ck(sha((b/"E398Q_PREREGISTRATION.json").read_bytes())==frz["preregistration_sha256"],"prereg")
    ck(rep["files_changed"]==18,"18 changed"); ck(len(rep["changed"])==18,"list 18"); ck(rep["files_changed"]==scan["files_changed"],"scan count")
    for p in rep["changed"]:
        ck(not ("/evidence/" in p or p.startswith("clawx-site/evidence") or p.startswith("platform-gateway/frontend/evidence") or "/proof/bundle/" in p or p.endswith("-snapshot.json") or p.startswith("artifacts/")),f"non-evidence {p}")
    ck(rep["stale_key_surfaces"]==[],"stale"); ck(rep["key_surfaces_missing"]==[],"missing"); ck(rep["status_surfaces"]==3,"status"); ck(rep["evidence_paths_untouched"] is True,"evidence"); ck(rep["evidence_files_hashed"]>50000,"hashes")
    H=rep["hypotheses"]
    for k in ("H1_stale_removed","H2_key_surfaces","H3_status_line","H4_evidence_untouched","H5_qualifier_text"): ck(H[k]["verdict"]=="SUPPORTED",k)
    ck(H["H6_external_review"]["verdict"]=="BLOCKED","H6"); ck(rep["verdict"]=="QUALIFIER_CONSISTENCY_VERIFIED","verdict")
    prev="0"*64
    for i,row in enumerate(rep["chain"]):
        hh=sha((prev+sha(canon(rep["changed_hashes"][i]))).encode()); ck(row["hash"]==hh,f"chain {i}"); prev=hh
    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/"E398Q_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 {"E398Q_MANIFEST.json","E398Q_SIGNED_BODY.json","E398Q_VERIFICATION_RESULTS.json","E398Q_TAMPER_RESULTS.json","MANIFEST.json","MERKLE_ROOT.txt","PUBLICATION.json","E398Q_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_e398q_offline.py" for p in files),"verifier")
    print(f"E398-Q 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 "."))
