#!/usr/bin/env python3
"""RHV standalone auditor — re-derives the review-value 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
HUMANS={"THEATRE":(1.00,0.00),"WEAK":(0.99,0.20),"TYPICAL":(0.95,0.70),"STRONG":(0.95,0.95),"SAFE_ONLY":(0.75,1.00)}
ARMS=("TRUST",)+tuple(HUMANS)+("STANDING_FRESH","ORACLE"); MEMORY_ARMS=ARMS[:-1]
SWEEP=tuple(round(0.50+0.01*i,2) for i in range(50))
TENANT,SEED="cain42-rhv","rhv"; 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 run_world(salt,w):
    wd=build(salt); cands={c["id"]:c for c in wd["candidates"]}; out={}
    for arm in ARMS:
        true=null=approvals=audits=0; promoted=[]; refused=[]
        if arm.startswith("STANDING"): approvals=1
        for cid in wd["order"]:
            c=cands[cid]
            if arm=="ORACLE":
                if c["real"]: true+=1
                continue
            if arm=="TRUST":
                if c["real"]: true+=1
                else: null+=1
                promoted.append(cid); continue
            if arm=="STANDING_FRESH":
                if c["e1"]>=THRESH:
                    audits+=1
                    if c["e2"]>=THRESH:
                        if c["real"]: true+=1
                        else: null+=1
                        promoted.append(cid)
                    else: refused.append(cid)
                else: refused.append(cid)
                continue
            a,d=HUMANS[arm]; approvals+=1
            if approve(salt,w,c,a,d):
                if c["real"]: true+=1
                else: null+=1
                promoted.append(cid)
            else: refused.append(cid)
        out[arm]={"true":true,"null":null,"promotions":true+null,"approvals":approvals,"audits":audits,
                  "promoted":promoted,"refused":refused}
    sweep=[]
    for q in SWEEP:
        t=n=0
        for cid in wd["order"]:
            c=cands[cid]
            if approve(salt,w,c,q,q):
                if c["real"]: t+=1
                else: n+=1
        sweep.append({"q":q,"true":t,"null":n})
    return {"candidates":wd["candidates"],"order":wd["order"],"arms":out,"sweep":sweep}
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","approvals","audits")}
        agg["precision"]=round(agg["true"]/max(1,agg["promotions"]),6); agg["null_rate"]=round(agg["null"]/max(1,agg["promotions"]),6)
        out[a]=agg
    out["oracle_true"]=out["ORACLE"]["true"]
    out["sweep"]=[{"q":q,"true":sum(w["sweep"][i]["true"] for w in ws),"null":sum(w["sweep"][i]["null"] for w in ws)} for i,q in enumerate(SWEEP)]
    return out
def crossing(sm):
    f=sm["STANDING_FRESH"]
    for x in sm["sweep"]:
        if x["null"]<=f["null"] and x["true"]>=f["true"]: return x
    return None
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/"RHV_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/"RHV_RUN_REPORT.json").read_text())
    wp=json.loads((d/"RHV_WORLDS.json").read_text()); mem=json.loads((d/"RHV_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","approvals","audits","precision","null_rate"):
                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 i,x in enumerate(sm["sweep"]): ok(f"{label} sweep {x['q']}",report["measures"][label]["sweep"][i]==x)
        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={}; sweep_rec=[]
            for e in mem[label][a]:
                if e["kind"]=="promotion": promo[e["value"]["world"]]=e["value"]["arms"][a]
                if e["kind"]=="sweep": sweep_rec.append(e["value"]["sweep"])
            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)
            ok(f"{label} {a} sweep records",sweep_rec==[w["sweep"] for w in ws])
    H=report["hypotheses"]
    comp={"H1_a_typical_reviewer_is_weak":all(S[s]["TYPICAL"]["null"]>=0.25*REAL*WORLDS and S[s]["TYPICAL"]["null"]>S[s]["STANDING_FRESH"]["null"] for s in S),
          "H2_approving_everything_is_theatre":all(S[s]["THEATRE"]["null"]==S[s]["TRUST"]["null"] and S[s]["THEATRE"]["approvals"]==CANDIDATES*WORLDS for s in S),
          "H3_the_crossing_is_about_90_percent":all((crossing(S[s]) or {}).get("q") is not None and 0.85<=(crossing(S[s]) or {})["q"]<=0.98 for s in S),
          "H4_the_break_even_is_specificity":all((crossing(S[s]) or {}).get("q") is not None and abs((crossing(S[s]) or {})["q"]-(1-S[s]["STANDING_FRESH"]["null"]/(REAL*WORLDS)))<=0.03 for s in S),
          "H5_one_axis_is_not_enough":all(S[s]["SAFE_ONLY"]["null"]<=S[s]["STANDING_FRESH"]["null"] and S[s]["SAFE_ONLY"]["true"]<S[s]["STANDING_FRESH"]["true"] and S[s]["WEAK"]["null"]>S[s]["STANDING_FRESH"]["null"] for s in S)}
    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("H6 blocked",H["H6_external_review"]["verdict"]=="BLOCKED")
    for s in report["memory"]:
        for a in report["memory"][s]:
            p=report["memory"][s][a]["probe"]
            ok(f"probe {s}:{a}",bool(p["chain_and_signatures"] and p["replay_refused"] and p["tamper_detected"] and p["authority_from_memory_refused"] and p["authority_flag_false_everywhere"]))
    core=all(H[k]["ok"] for k in H if k!="H6_external_review"); ok("verdict",report["verdict"]==("REVIEW_VALUE_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())
