#!/usr/bin/env python3
"""REAL standalone verifier: the evidence record, not a re-query. No CAIN imports."""
import hashlib, json, sys
from pathlib import Path
from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PublicKey
def canon(o): return json.dumps(o,sort_keys=True,separators=(",",":"),ensure_ascii=False).encode()
def sha(b): return hashlib.sha256(b).hexdigest()
def main():
    d=Path(sys.argv[1]); cks=[]; fails=[]
    def ck(n,ok):
        cks.append(n)
        if not ok: fails.append(n)
    man=json.loads((d/"MANIFEST.json").read_text())
    try:
        Ed25519PublicKey.from_public_bytes(bytes.fromhex(man["pubkey_ed25519"])).verify(bytes.fromhex(man["signature"]),canon({k:v for k,v in man.items() if k!="signature"})); ck("manifest signature",True)
    except Exception: ck("manifest signature",False)
    fs=sorted(p for p in d.rglob("*") if p.is_file() and p.name not in ("MANIFEST.json","MERKLE_ROOT.txt","PUBLICATION.json","REAL_OMEGA_SEAL.json","REAL_PUBKEY.pem","REAL_SIGNED_BODY.json","REAL_VERIFICATION.json"))
    h={str(p.relative_to(d)):sha(p.read_bytes()) for p in fs}
    ck("file hashes",all(man["files"].get(k)==v for k,v in h.items())); ck("no unlisted file",set(man["files"])==set(h))
    l=sorted(man["files"].values())
    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)]
    ck("merkle root",(l[0] if l else sha(b""))==man["merkle_root"])
    run=json.loads((d/"REAL_RUN.json").read_text()); rows=json.loads((d/"REAL_ROWS.json").read_text())
    dec=json.loads((d/"REAL_DECISIONS.json").read_text()); rec=json.loads((d/"REAL_RECOMPUTE.json").read_text())
    mem=json.loads((d/"REAL_MEMORY.json").read_text()); neg=json.loads((d/"REAL_NEGATIVE.json").read_text())
    ck("real data declared",run["data"]["rows_in_table"]>3_000_000 and run["data"]["provenance"].startswith("REAL PRODUCTION TRAFFIC"))
    ck("governed reads",run["governed_reads"]==8 and run["denied_reads"]==0)
    ck("every read has a result",all((x["result"] is not None)==(x["decision"]=="ALLOW") for x in dec))
    ck("result digests",all(x["result_sha256"]==sha(canon(next(y["result"] for y in dec if y["i"]==x["i"]))) for x in rows if x["result_sha256"]))
    ck("independent recompute 4/4",len(rec)==4 and all(x["match"] for x in rec) and run["all_recomputed"] is True)
    ck("no ip_hash exported",all("ip_hash" not in json.dumps(x.get("result") or {}) for x in dec))
    ck("negative: unlisted tool not allowed",any(x["case"]=="unlisted_tool" and not x["allowed"] for x in neg))
    ck("negative: replay blocked",any(x["case"]=="jit_replay" and x["second"][0] is False for x in neg))
    ck("negative: forbidden column blocked",any(x["case"]=="forbidden_column_executed" and x["blocked"] for x in neg))
    ck("memory entries",len(mem)==8 and run["probe"]["entries"]==8)
    ck("status line",run["status"]=="AGI: NOT ESTABLISHED · RSI: EXPERIMENTAL")
    ck("no model calls",run["model_calls"]==0)
    print(f"{len(cks)-len(fails)}/{len(cks)} checks passed")
    for n in fails: print("FAIL",n)
    print("verdict","REAL_WORKLOAD_VERIFIED" if not fails else "NOT_VERIFIED")
    return 0 if not fails else 1
if __name__=="__main__": raise SystemExit(main())
