#!/usr/bin/env python3
"""VWT standalone auditor — re-derives the value-weight study from the revealed 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; LAMS=(0.0,0.03,0.06,0.09,0.12); QUERIES=5; WORLDS=24
ARMS=("MAX_ACC","SAFE_ONLY","FIXED","ELICIT","FRONTIER","ORACLE"); MEMORY_ARMS=ARMS[:-1]
TENANT,SEED="cain42-vwt","vwt"; AGENT_IDS=tuple(f"agent{i}" for i in range(4)); SIGNERS=AGENT_IDS+("principal","verifier")
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 u01(s,t): return int.from_bytes(hashlib.sha256(f"{s}|{t}".encode()).digest()[:8],"big")/2**64
def build(s, lam=None):
    cs=[]
    for i in range(CANDIDATES):
        h=0 if i==0 else int(u01(s,f"h|{i}")*5); acc=round(0.70+0.025*h+0.04*(u01(s,f"a|{i}")-0.5),4); cs.append({"id":i,"acc":acc,"harm":h})
    if lam is None:
        lam=LAMS[int(u01(s,"lam")*len(LAMS))]
    return cs,lam
def util(c,l): return c["acc"]-l*c["harm"]
def best(cs,l): return max(cs,key=lambda c:(util(c,l),-c["id"]))
def frontier(cs):
    out=[]
    for c in cs:
        if not any((d["acc"]>=c["acc"] and d["harm"]<=c["harm"]) and (d["acc"]>c["acc"] or d["harm"]<c["harm"]) for d in cs if d["id"]!=c["id"]): out.append(c["id"])
    return sorted(out)
def pairs(cs):
    p=[]
    for i in range(CANDIDATES):
        for j in range(i+1,CANDIDATES):
            a,b=cs[i],cs[j]; sep=len({util(a,l)>util(b,l) for l in LAMS}); p.append((sep,i,j))
    p.sort(key=lambda x:(-x[0],x[1],x[2])); return [(i,j) for _,i,j in p[:QUERIES]]
def run_world(s, lam=None):
    cs,lam=build(s, lam); oracle=best(cs,lam); ou=util(oracle,lam); out={}
    def rec(name,pick,q=0,est=None):
        out[name]={"promoted":None if pick is None else pick["id"],"harm":None if pick is None else pick["harm"],"true":None if pick is None else pick["acc"],"regret":0.0 if pick is None else round(ou-util(pick,lam),6),"queries":q,"estimate":est}
    rec("MAX_ACC",best(cs,0.0)); rec("SAFE_ONLY",best([c for c in cs if c["harm"]==0],0.0)); rec("FIXED",best(cs,0.06))
    cons={l:0 for l in LAMS}
    for i,j in pairs(cs):
        a,b=cs[i],cs[j]; pref=util(a,lam)>util(b,lam)
        for l in LAMS: cons[l]+= 1 if (util(a,l)>util(b,l))==pref else 0
    est=max(LAMS,key=lambda l:(cons[l],-l)); rec("ELICIT",best(cs,est),q=QUERIES,est=est); rec("FRONTIER",None); rec("ORACLE",oracle)
    return {"lam":lam,"oracle":oracle["id"],"oracle_harm":oracle["harm"],"frontier":frontier(cs),"arms":out,"estimated_ok":est==lam}
def mean(xs): return round(sum(xs)/len(xs),6) if xs else 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",flags)
def main():
    d=Path(sys.argv[1]).resolve(); man=json.loads((d/"VWT_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("declared 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/"VWT_RUN_REPORT.json").read_text()); wp=json.loads((d/"VWT_WORLDS.json").read_text()); mem=json.loads((d/"VWT_MEMORY.json").read_text())
    for k,v in salts.items(): ok(f"salt commitment {k}",report["salts"][k]==sha(v.encode()))
    derived={}
    for label in ("salt1","salt2"):
        ws=[run_world(sha(f"{salts[label]}|world|{w}".encode()), LAMS[w % len(LAMS)]) for w in range(WORLDS)]; summary={}
        for a in ARMS:
            summary[a]={"regret":mean([w["arms"][a]["regret"] for w in ws]),"harm":mean([w["arms"][a]["harm"] for w in ws if w["arms"][a]["harm"] is not None]) if any(w["arms"][a]["harm"] is not None for w in ws) else None,"queries":mean([w["arms"][a]["queries"] for w in ws]),"autonomous":round(sum(1 for w in ws if w["arms"][a]["promoted"] is not None)/WORLDS,6)}
            for f in ("regret","harm","queries","autonomous"):
                rv=report["measures"][label][a][f]; dv=summary[a][f]
                ok(f"{label} {a} {f}",(rv is None and dv is None) or (rv is not None and dv is not None and abs(rv-dv)<1e-9))
            for w in range(WORLDS):
                for f in ("regret",):
                    ok(f"{label} {a} w{w}",abs(wp[label][a][w][f]-ws[w]["arms"][a][f])<1e-9)
        summary["estimated_ok"]=round(sum(1 for w in ws if w["estimated_ok"])/WORLDS,6)
        summary["frontier_contains_oracle"]=round(sum(1 for w in ws if w["oracle"] in w["frontier"])/WORLDS,6)
        summary["oracle_harm_lam0"]=mean([w["oracle_harm"] for w in ws if w["lam"]==0.0])
        summary["oracle_harm_lam12"]=mean([w["oracle_harm"] for w in ws if w["lam"]==0.12])
        for f in ("estimated_ok","frontier_contains_oracle","oracle_harm_lam0","oracle_harm_lam12"):
            rv=report["measures"][label][f]; dv=summary[f]
            ok(f"{label} {f}",(rv is None and dv is None) or (rv is not None and dv is not None and abs(rv-dv)<1e-9))
        derived[label]=summary
        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"])
            ch={}
            for e in mem[label][a]:
                if e["kind"]=="choice": ch[(e["value"]["world"],e["value"]["arm"])]=e["value"]
            good=True
            for w in range(WORLDS):
                dd=ws[w]["arms"][a]; v=ch.get((w,a))
                good=good and v is not None and v["promoted"]==dd["promoted"] and v["regret"]==dd["regret"]
            ok(f"{label} {a} choices",good)
    S=derived; H=report["hypotheses"]
    comp={"H1_fixed_ends_of_the_frontier_regret":all(S[s]["MAX_ACC"]["regret"]>=0.05 and S[s]["SAFE_ONLY"]["regret"]<S[s]["MAX_ACC"]["regret"] for s in S),
          "H2_five_queries_fix_the_trade_off":all(S[s]["ELICIT"]["regret"]<=0.01 and S[s]["ELICIT"]["regret"]<=0.4*min(S[s]["FIXED"]["regret"],S[s]["MAX_ACC"]["regret"],S[s]["SAFE_ONLY"]["regret"]) for s in S),
          "H3_the_weight_is_recoverable":all(S[s]["ELICIT"]["queries"]==5.0 and S[s]["estimated_ok"]>=0.40 for s in S),
          "H4_the_frontier_is_exact_but_not_a_choice":all(S[s]["frontier_contains_oracle"]==1.0 and S[s]["FRONTIER"]["autonomous"]==0.0 and S[s]["FRONTIER"]["regret"]==0.0 for s in S),
          "H5_the_trade_off_is_real":all((S[s]["oracle_harm_lam0"] or 0)>=2.0 and (S[s]["oracle_harm_lam12"] or 0)<=1.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"]==("VALUE_WEIGHT_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())
