#!/usr/bin/env python3
"""TRG standalone auditor — re-derives the triage 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; REAL_EFFECT=0.20; NULL_EFFECT=0.0; WORLDS=12
HUMAN=(0.95,0.70); ARMS=("GATE","HUMAN_ALL","TRIAGE","REVERSE","ORACLE"); MEMORY_ARMS=ARMS[:-1]
TENANT,SEED="cain42-trg","trg"; SIGNERS=("operator","reviewer","steward","auditor")
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 _u(salt,w,cid,tag): return int(sha(f"{salt}|human|{w}|{cid}|{tag}".encode())[:8],16)/0xFFFFFFFF
def approve(salt,w,c,a,d):
    return _u(salt,w,c["id"],"a")<a if c["real"] else _u(salt,w,c["id"],"d")<(1.0-d)
def gate(c): return c["e1"]>=THRESH and c["e2"]>=THRESH
def run_world(salt,w):
    wd=build(salt); cands={c["id"]:c for c in wd["candidates"]}; out={}
    for arm in ARMS:
        true=null=reviews=audits=0; promoted=[]; refused=[]
        for cid in wd["order"]:
            c=cands[cid]
            if arm=="ORACLE":
                if c["real"]: true+=1
                continue
            if arm=="GATE":
                if c["e1"]>=THRESH: audits+=1
                if gate(c):
                    if c["real"]: true+=1
                    else: null+=1
                    promoted.append(cid)
                else: refused.append(cid)
                continue
            h=approve(salt,w,c,*HUMAN)
            if arm=="HUMAN_ALL":
                reviews+=1
                if h:
                    if c["real"]: true+=1
                    else: null+=1
                    promoted.append(cid)
                else: refused.append(cid)
                continue
            if arm=="TRIAGE":
                if c["e1"]>=THRESH: audits+=1
                if gate(c):
                    reviews+=1
                    if h:
                        if c["real"]: true+=1
                        else: null+=1
                        promoted.append(cid)
                    else: refused.append(cid)
                else: refused.append(cid)
                continue
            if arm=="REVERSE":
                if h:
                    reviews+=1
                    if c["e1"]>=THRESH: audits+=1
                    if gate(c):
                        if c["real"]: true+=1
                        else: null+=1
                        promoted.append(cid)
                    else: refused.append(cid)
                else: refused.append(cid)
                continue
        out[arm]={"true":true,"null":null,"promotions":true+null,"reviews":reviews,"audits":audits,
                  "promoted":promoted,"refused":refused}
    return {"candidates":wd["candidates"],"order":wd["order"],"arms":out}
def summarize(ws):
    out={}
    for a in ARMS:
        v=[w["arms"][a] for w in ws]
        agg={k:sum(x[k] for x in v) for k in ("true","null","promotions","reviews","audits")}
        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/"TRG_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/"TRG_RUN_REPORT.json").read_text())
    wp=json.loads((d/"TRG_WORLDS.json").read_text()); mem=json.loads((d/"TRG_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()),w) for w in range(WORLDS)]
        sm=summarize(ws); S[label]=sm
        for a in ARMS:
            for f in ("true","null","promotions","reviews","audits","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={}
            for e in mem[label][a]:
                if e["kind"]=="promotion": promo[e["value"]["world"]]=e["value"]["arms"][a]
            good=all(promo.get(w,{}).get("true")==ws[w]["arms"][a]["true"] and promo.get(w,{}).get("null")==ws[w]["arms"][a]["null"] for w in range(WORLDS))
            ok(f"{label} {a} promotions",good)
    H=report["hypotheses"]
    comp={"H1_the_human_alone_passes_more_nulls":all(S[s]["HUMAN_ALL"]["null"]>S[s]["TRIAGE"]["null"] for s in S),
          "H2_the_triage_cuts_nulls_without_losing_much":all(S[s]["TRIAGE"]["null"]<=0.5*S[s]["GATE"]["null"] and S[s]["TRIAGE"]["true"]>=0.90*S[s]["GATE"]["true"] for s in S),
          "H3_the_triage_spares_the_reviewer":all(S[s]["TRIAGE"]["reviews"]<=0.55*S[s]["HUMAN_ALL"]["reviews"] for s in S),
          "H4_the_outcome_is_order_insensitive":all(S[s]["TRIAGE"]["true"]==S[s]["REVERSE"]["true"] and S[s]["TRIAGE"]["null"]==S[s]["REVERSE"]["null"] for s in S),
          "H5_the_cost_is_order_sensitive":all(S[s]["TRIAGE"]["reviews"]<S[s]["REVERSE"]["reviews"] 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"]==("TRIAGE_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())
