#!/usr/bin/env python3
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]); c=[]; f=[]
    def ck(n,ok):
        c.append(n)
        if not ok: f.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","SCOPE_OMEGA_SEAL.json","SCOPE_PUBKEY.pem","SCOPE_SIGNED_BODY.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"])
    r=json.loads((d/"rows.json").read_text()); run=json.loads((d/"run.json").read_text())
    ck("4 in-scope executed",sum(1 for x in r if x["case"].startswith("in_scope") and x["executed"])==4)
    ck("4 attacks refused",sum(1 for x in r if x["case"].startswith("attack") and not x["executed"])==4)
    ck("typed reasons",sorted(x["scope_reason"] for x in r if x["case"].startswith("attack"))==sorted(["COLUMN_NOT_IN_SCOPE","ROW_CAP_EXCEEDED","PURPOSE_MISMATCH","SCOPE_SIGNATURE_INVALID"]))
    ck("boundary allowed all 8",run["boundary_allowed_all"] is True)
    ck("no ip_hash in results",all("ip_hash" not in json.dumps(x.get("result_sha256") or "") for x in r))
    ck("status line",run["status"]=="AGI: NOT ESTABLISHED · RSI: EXPERIMENTAL")
    ck("no model calls",run["model_calls"]==0)
    print(f"{len(c)-len(f)}/{len(c)} checks passed")
    for n in f: print("FAIL",n)
    print("verdict","SIGNED_CALL_SCOPE_VERIFIED" if not f else "NOT_VERIFIED")
    return 0 if not f else 1
if __name__=="__main__": raise SystemExit(main())
