#!/usr/bin/env python3
"""SAP standalone auditor — re-derives the standing-approval study from the salts. No CAIN imports."""
from __future__ import annotations
import hashlib, json, sys
from pathlib import Path
from cryptography.hazmat.primitives import serialization
from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PrivateKey, Ed25519PublicKey

CANDIDATES=40; REAL=20; TRIALS=24; THRESH=0.06; REVOKE_SLOT=36; REAL_EFFECT=0.20; NULL_EFFECT=0.0; WORLDS=12
ARMS=("TRUST","PER_ITEM","STANDING","STANDING_FRESH","STANDING_CHALLENGE","ORACLE"); MEMORY_ARMS=ARMS[:-1]
TENANT,SEED="cain42-sap","sap"; SIGNERS=("operator","steward","auditor","insider")
CHECKS=[]
def ok(n,c): CHECKS.append((n,bool(c))); return bool(c)
def canon(o): return json.dumps(o,sort_keys=True,separators=(",",":"),ensure_ascii=False).encode()
def sha(b): return hashlib.sha256(b).hexdigest()
def draw(salt,cand,ts):
    p=0.5+(REAL_EFFECT if cand<REAL else NULL_EFFECT); s=0
    for j in range(TRIALS):
        u=int(sha(f"{salt}|cand|{cand}|{ts}|{j}".encode())[:8],16)/0xFFFFFFFF
        if u<p: s+=1
    return s
def build(salt):
    cs=[{"id":i,"real":i<REAL,"t1":draw(salt,i,"t1"),"t2":draw(salt,i,"t2")} for i in range(CANDIDATES)]
    for c in cs: c["e1"]=round(c["t1"]/TRIALS-0.5,6); c["e2"]=round(c["t2"]/TRIALS-0.5,6)
    return {"candidates":cs,"order":sorted(range(CANDIDATES),key=lambda i:sha(f"{salt}|order|{i}".encode()))}
def run_world(salt):
    w=build(salt); cands={c["id"]:c for c in w["candidates"]}; out={}
    for arm in ARMS:
        true=null=approvals=audits=after=after_ref=0; promoted=[]; refused=[]; challenged=[]
        if arm.startswith("STANDING"): approvals=1
        for slot,cid in enumerate(w["order"]):
            c=cands[cid]; eligible=c["e1"]>=THRESH
            if arm=="ORACLE":
                if c["real"]: true+=1
                continue
            if arm=="TRUST":
                if c["real"]: true+=1
                else: null+=1
                promoted.append(cid)
                if slot>=REVOKE_SLOT: after+=1
                continue
            if arm=="PER_ITEM":
                approvals+=1
                if c["real"]: true+=1
                else: null+=1
                promoted.append(cid)
                if slot>=REVOKE_SLOT: after+=1
                continue
            if slot>=REVOKE_SLOT and eligible:
                after_ref+=1; refused.append(cid); continue
            if not eligible: refused.append(cid); continue
            if arm=="STANDING":
                if c["real"]: true+=1
                else: null+=1
                promoted.append(cid); continue
            if arm=="STANDING_CHALLENGE":
                if c["real"]:
                    audits+=1; challenged.append(cid)
                    if c["e2"]>=THRESH: true+=1; promoted.append(cid)
                    else: refused.append(cid)
                else:
                    null+=1; promoted.append(cid)
                continue
            if arm=="STANDING_FRESH":
                audits+=1
                if c["e2"]>=THRESH:
                    if c["real"]: true+=1
                    else: null+=1
                    promoted.append(cid)
                else: refused.append(cid)
                continue
        out[arm]={"true":true,"null":null,"promotions":true+null,"approvals":approvals,"audits":audits,
                  "after_revoke_admitted":after,"after_revoke_refused":after_ref,
                  "promoted":promoted,"refused":refused,"challenged":challenged}
    out["insider"]={"challenges":[cid for cid in w["order"] if cands[cid]["real"]]}
    return {"candidates":w["candidates"],"order":w["order"],"arms":out}
def summarize(ws):
    out={}
    for a in ARMS:
        vals=[w["arms"][a] for w in ws]
        agg={k:sum(v[k] for v in vals) for k in ("true","null","promotions","approvals","audits","after_revoke_admitted","after_revoke_refused")}
        agg["null_rate"]=round(agg["null"]/max(1,agg["promotions"]),6); agg["precision"]=round(agg["true"]/max(1,agg["promotions"]),6)
        out[a]=agg
    out["oracle_true"]=out["ORACLE"]["true"]; return out
def keypair(a): return Ed25519PrivateKey.from_private_bytes(hashlib.sha256(f"{SEED}|{a}".encode()).digest())
def pubhex(a): return keypair(a).public_key().public_bytes(serialization.Encoding.Raw,serialization.PublicFormat.Raw).hex()
def nonce(agent,kind,key,value): return sha(canon({"agent":agent,"kind":kind,"key":key,"value":value}))[:16]
def verify_memory(es,label):
    prev,bad,ten,flags="",[],set(),True
    for e in es:
        ten.add(e["tenant"]); flags=flags and (not e["grants_authority"]) and (not e["executable"])
        body=canon({k:e[k] for k in ("seq","tenant","agent","kind","key","value","prev","nonce","created_at","grants_authority","executable")})
        g=e["prev"]==prev and e["tenant"]==TENANT
        g=g and sha(e["prev"].encode()+body+bytes.fromhex(e["sig"]))==e["hash"]
        g=g and e["nonce"]==nonce(e["agent"],e["kind"],e["key"],e["value"])
        if g:
            try: Ed25519PublicKey.from_public_bytes(bytes.fromhex(pubhex(e["agent"]))).verify(bytes.fromhex(e["sig"]),body)
            except Exception: g=False
        if not g: bad.append(e["seq"])
        prev=e["hash"]
    return ok(f"memory {label}: chain+sigs",not bad),ok(f"memory {label}: tenant",ten=={TENANT}),ok(f"memory {label}: no-authority",flags)
def main():
    d=Path(sys.argv[1]).resolve(); man=json.loads((d/"SAP_MANIFEST.json").read_text()); body={k:v for k,v in man.items() if k!="signature"}
    ok("manifest signature",Ed25519PublicKey.from_public_bytes(bytes.fromhex(man["pubkey_ed25519"])).verify(bytes.fromhex(man["signature"]),canon(body)) is None)
    files={str(p.relative_to(d)):sha(p.read_bytes()) for p in sorted(d.rglob("*")) if p.is_file() and str(p.relative_to(d)) in man["files"]}
    ok("file hashes",files==man["files"]); ok("merkle root",man["merkle_root"]==(d/"MERKLE_ROOT.txt").read_text().strip())
    salts=json.loads((d/"SALTS.json").read_text()); report=json.loads((d/"SAP_RUN_REPORT.json").read_text()); wp=json.loads((d/"SAP_WORLDS.json").read_text()); mem=json.loads((d/"SAP_MEMORY.json").read_text())
    for k,v in salts.items(): ok(f"salt {k}",report["salts"][k]==sha(v.encode()))
    S={}
    for label in ("salt1","salt2"):
        ws=[run_world(sha(f"{salts[label]}|world|{w}".encode())) for w in range(WORLDS)]
        sm=summarize(ws); S[label]=sm
        for a in ARMS:
            for f in ("true","null","promotions","approvals","audits","after_revoke_admitted","after_revoke_refused","null_rate","precision"):
                ok(f"{label} {a} {f}",report["measures"][label][a][f]==sm[a][f])
            for w in range(WORLDS):
                ok(f"{label} {a} w{w} promoted",wp[label][a][w]["promoted"]==ws[w]["arms"][a]["promoted"])
        ok(f"{label} oracle",report["measures"][label]["oracle_true"]==sm["oracle_true"])
        for a in MEMORY_ARMS:
            verify_memory(mem[label][a],f"{label}:{a}"); ok(f"{label} {a} entries",len(mem[label][a])==report["memory"][label][a]["entries"])
            promo={}; chal={}
            for e in mem[label][a]:
                if e["kind"]=="promotion": promo[e["value"]["world"]]=e["value"]["arms"][a]
                if e["kind"]=="challenge": chal[e["value"]["world"]]=e["value"]["challenged"]
            good=all(promo.get(w,{}).get("promoted")==ws[w]["arms"][a]["promoted"] and promo.get(w,{}).get("refused")==ws[w]["arms"][a]["refused"] for w in range(WORLDS))
            ok(f"{label} {a} promotions",good)
            ok(f"{label} {a} insider",all(chal.get(w)==ws[w]["arms"]["insider"]["challenges"] for w in range(WORLDS)))
    H=report["hypotheses"]
    comp={"H1_approval_theatre":all(S[s]["TRUST"]["null"]>=0.75*REAL*WORLDS and S[s]["PER_ITEM"]["null"]>=0.75*REAL*WORLDS for s in S),
          "H2_fresh_evidence_halves_the_leak":all(S[s]["STANDING_FRESH"]["null"]<=0.5*S[s]["STANDING"]["null"] and S[s]["STANDING_FRESH"]["true"]>=0.85*S[s]["STANDING"]["true"] for s in S),
          "H3_a_captured_challenger_buys_nothing":all(S[s]["STANDING_CHALLENGE"]["null"]==S[s]["STANDING"]["null"] and S[s]["STANDING_CHALLENGE"]["true"]<S[s]["STANDING"]["true"] and S[s]["STANDING_CHALLENGE"]["audits"]>0 for s in S),
          "H4_standing_approval_is_cheaper":all(S[s]["STANDING"]["approvals"]<=0.10*S[s]["PER_ITEM"]["approvals"] for s in S),
          "H5_revocation_stops_promotion":all(all(S[s][a]["after_revoke_admitted"]==0 for a in ("STANDING","STANDING_FRESH","STANDING_CHALLENGE")) and S[s]["TRUST"]["after_revoke_admitted"]>0 for s in S),
          "H6_integrity_and_no_authority":H["H6_integrity_and_no_authority"]["ok"]}
    for k,v in comp.items(): ok(f"{k} ok",H[k]["ok"]==v); ok(f"{k} verdict",H[k]["verdict"]==("SUPPORTED" if v else "NOT_SUPPORTED"))
    ok("H7 blocked",H["H7_external_review"]["verdict"]=="BLOCKED")
    core=all(H[k]["ok"] for k in H if k!="H7_external_review"); ok("verdict",report["verdict"]==("STANDING_APPROVAL_SUPPORTED" if core else "NOT_SUPPORTED"))
    passed=sum(1 for _,g in CHECKS if g)
    for n,g in CHECKS:
        if not g: print("FAIL",n)
    print(f"{passed}/{len(CHECKS)} checks passed"); return 0 if passed==len(CHECKS) else 1
if __name__=="__main__": sys.exit(main())
