#!/usr/bin/env python3
"""VBI standalone auditor — re-derives every world, budget and policy from the salts."""
from __future__ import annotations
import hashlib,json,sys
from pathlib import Path
from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PublicKey
CLAIMS,BUDGET,LIAR,LIAR_CLAIMS=60,60,"A0",10
ARMS=("NEVER","ALWAYS","RANDOM20","SEVERITY","VOI","VOI_DECLARED","ORACLE"); TENANT,SEED="cain42-vbi","vbi"; WORLDS=8
def canon(o): return json.dumps(o,sort_keys=True,separators=(",",":"),ensure_ascii=False).encode()
def sha(b): return hashlib.sha256(b).hexdigest()
def h(s): return hashlib.sha256(s.encode()).hexdigest()
def unit(salt,*p): return int(h("|".join((salt,*map(str,p))))[:8],16)/float(1<<32)
def claim(salt,c):
    owner=LIAR if c<LIAR_CLAIMS else f"A{1+(c%5)}"
    if owner==LIAR: p,sev,cost,decl=0.30,1,1,50
    else:
        p=round(0.02+0.38*unit(salt,"p",c),6); sev=1+int(unit(salt,"s",c)*50); cost=1+int(unit(salt,"c",c)*4); decl=sev
    return {"candidate":c,"owner":owner,"p":p,"severity":sev,"declared":decl,"cost":cost,"defective":unit(salt,"d",c)<p}
def claims(salt): return [claim(salt,c) for c in range(CLAIMS)]
def order(salt,arm):
    xs=claims(salt)
    if arm=="NEVER": return []
    if arm=="ALWAYS": return [x["candidate"] for x in xs]
    if arm=="RANDOM20":
        pick=sorted(xs,key=lambda x:(unit(salt,"r",x["candidate"]),x["candidate"])); return [x["candidate"] for x in pick[:int(0.2*CLAIMS)]]
    if arm=="SEVERITY": return [x["candidate"] for x in sorted(xs,key=lambda x:(-x["declared"],x["candidate"]))]
    if arm in ("VOI","VOI_DECLARED"):
        k="severity" if arm=="VOI" else "declared"
        return [x["candidate"] for x in sorted(xs,key=lambda x:(-(x["p"]*x[k]/max(1,x["cost"])),-(x["p"]*x[k]),x["candidate"]))]
    if arm=="ORACLE":
        return [x["candidate"] for x in sorted([x for x in xs if x["defective"] and x["severity"]>x["cost"]],key=lambda x:(x["cost"],-x["severity"],x["candidate"]))]
    raise ValueError(arm)
def run(salt,arm):
    xs={x["candidate"]:x for x in claims(salt)}; spent=0; ver=set()
    for c in order(salt,arm):
        x=xs[c]
        if spent+x["cost"]<=BUDGET: ver.add(c); spent+=x["cost"]
    defects=[c for c,x in xs.items() if x["defective"] and c not in ver]
    liar=[c for c in ver if xs[c]["owner"]==LIAR]
    return {"loss":sum(xs[c]["severity"] for c in defects),"spend":spent,"verified":len(ver),
            "accepted_defects":len(defects),"defective_total":sum(1 for x in xs.values() if x["defective"]),
            "liar_verified":len(liar),"liar_spend":sum(xs[c]["cost"] for c in liar)}
def mean(xs): return round(sum(xs)/len(xs),6)
def nonce(a,k,key,v): return sha(canon({"agent":a,"kind":k,"key":key,"value":v}))[:16]
def pub_of(a):
    from cryptography.hazmat.primitives import serialization
    from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PrivateKey
    k=Ed25519PrivateKey.from_private_bytes(hashlib.sha256(f"{SEED}|{a}".encode()).digest())
    return k.public_key().public_bytes(serialization.Encoding.Raw,serialization.PublicFormat.Raw).hex()
def vmem(es,pubs):
    prev,bad="",[]
    for e in es:
        e={**e,"grants_authority":False,"executable":False}
        body=canon({k:e[k] for k in ("seq","tenant","agent","kind","key","value","prev","nonce","created_at","grants_authority","executable")})
        ok=e["prev"]==prev and e["tenant"]==TENANT and sha(e["prev"].encode()+body+bytes.fromhex(e["sig"]))==e["hash"] and e["nonce"]==nonce(e["agent"],e["kind"],e["key"],e["value"])
        if ok:
            try: Ed25519PublicKey.from_public_bytes(bytes.fromhex(pubs[e["agent"]])).verify(bytes.fromhex(e["sig"]),body)
            except Exception: ok=False
        if not ok: bad.append(e["seq"])
        prev=e["hash"]
    return bad
def merkle(fs):
    l=sorted(sha(p.read_bytes()) for p in fs)
    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)]
    return l[0] if l else sha(b"")
def main():
    root=Path(sys.argv[1] if len(sys.argv)>1 else ".").resolve(); ck,fail=[],[]
    def check(n,ok,d=""):
        ck.append({"check":n,"ok":bool(ok),"detail":d})
        if not ok: fail.append(n)
    a=json.loads((root/"VBI_RUN_REPORT.json").read_text()); mem=json.loads((root/"VBI_MEMORY.json").read_text())
    salts=json.loads((root/"SALTS.json").read_text()); pre=json.loads((root/"VBI_PREREGISTRATION.json").read_text()); man=json.loads((root/"MANIFEST.json").read_text())
    for k in ("salt1","salt2"): check(f"salt commitment {k}",sha(salts[k].encode())==pre["salts_commitment"][k])
    derived={}
    for s in ("salt1","salt2"):
        derived[s]={}
        for arm in ARMS:
            rs=[run(f"{salts[s]}-{w}",arm) for w in range(WORLDS)]
            derived[s][arm]={k:mean([r[k] for r in rs]) for k in ("loss","spend","verified","accepted_defects","defective_total","liar_verified","liar_spend")}
    mm=0
    for s in derived:
        for arm in ARMS:
            exp=derived[s][arm]; rep=a["measurements"][s][arm]
            if any(rep.get(k)!=v for k,v in exp.items()): mm+=1
    check("every world, budget and policy re-derives",mm==0,f"{mm} mismatches")
    def L(s,a_): return derived[s][a_]["loss"]
    h1=all(L(s,"VOI")/L(s,"NEVER")<=0.40 for s in derived)
    h2=all(L(s,"VOI")/L(s,"ALWAYS")<=0.70 for s in derived)
    h3=all(L(s,"VOI_DECLARED")/L(s,"VOI")>=1.10 and derived[s]["VOI_DECLARED"]["liar_spend"]>=0.10*BUDGET for s in derived)
    h4=all(all(L(s,"VOI")<L(s,o) for o in ("ALWAYS","SEVERITY","RANDOM20","VOI_DECLARED")) for s in derived)
    computed={"H1_voi_beats_never":"SUPPORTED" if h1 else "NOT_SUPPORTED","H2_voi_beats_verifying_everything":"SUPPORTED" if h2 else "NOT_SUPPORTED",
              "H3_declared_severity_is_captured":"SUPPORTED" if h3 else "NOT_SUPPORTED","H4_voi_is_the_best_non_oracle_arm":"SUPPORTED" if h4 else "NOT_SUPPORTED"}
    check("H1-H4 recomputed (a negative hypothesis is a valid result)",True,json.dumps(computed))
    pubs={x:pub_of(x) for x in ("colony","verifier","auditor")}
    check("published memory keys derive from the seed",pubs==mem["keys"])
    bad=[]
    for k,es in mem["entries"].items(): bad+=[(k,b) for b in vmem(es,pubs)]
    check("every governed-memory entry verifies",not bad,str(bad[:5]))
    okp=all(a["probes"][s]["chain_and_signatures"] and a["probes"][s]["replay_refused"] and a["probes"][s]["tamper_detected"]
            and a["probes"][s]["liar_claims"]==LIAR_CLAIMS*WORLDS and a["probes"][s]["liar_misdeclared"]==LIAR_CLAIMS*WORLDS
            and a["probes"][s]["authority_from_memory_refused"] and a["probes"][s]["authority_flag_false_everywhere"] for s in ("salt1","salt2"))
    cross=0
    for s in ("salt1","salt2"):
        for e in mem["entries"][s]:
            if e["kind"]!="claim": continue
            w=int(e["key"].split(":")[0]); c=int(e["key"].split(":")[1])
            exp=claim(f"{salts[s]}-{w}",c)
            if any(e["value"].get(k)!=exp[k] for k in ("owner","p","severity","declared","cost","defective")): cross+=1
    check("memory claims match the recomputed world",cross==0,f"{cross} mismatches")
    check("H5 integrity and declaration record",okp)
    check("reported hypotheses match",{k:v.get("verdict") for k,v in a["hypotheses"].items()}=={**computed,"H5_integrity_and_declaration_record":"SUPPORTED" if okp else "NOT_SUPPORTED","H6_external_review":"BLOCKED"})
    check("verdict follows",a["verdict"]==("VALUE_OF_INFORMATION_GATE_SUPPORTED" if all([h1,h2,h3,h4,okp]) else "NOT_SUPPORTED"))
    fs=sorted(p for p in root.rglob("*") if p.is_file() and "__pycache__" not in p.parts and p.name not in
              ("MANIFEST.json","VBI_MANIFEST.json","MERKLE_ROOT.txt","VBI_SIGNED_BODY.json","VBI_VERIFICATION_RESULTS.json","VBI_TAMPER_RESULTS.json","VBI_PUBLIC_CHECK.json","PUBLICATION.json","VBI_OMEGA_SEAL.json","VBI_PUBKEY.pem"))
    body={k:man[k] for k in ("schema","evolution","status","name","created_at","verifier","pubkey_ed25519","files","merkle_root","engine_withheld","external_review")}
    try:
        Ed25519PublicKey.from_public_bytes(bytes.fromhex(man["pubkey_ed25519"])).verify(bytes.fromhex(man["signature"]),canon(body)); check("manifest signature",True)
    except Exception: check("manifest signature",False)
    check("file hashes match",all(man["files"].get(str(p.relative_to(root)))==sha(p.read_bytes()) for p in fs))
    check("manifest lists exactly the bundle files",sorted(man["files"])==sorted(str(p.relative_to(root)) for p in fs))
    check("merkle root recomputes",man["merkle_root"]==merkle(fs))
    check("engine source withheld",man.get("engine_withheld") is True and not any(p.suffix==".py" and "verify" not in p.name for p in fs))
    check("no model calls",a.get("model_calls")==0); check("status line",a.get("status")=="AGI: NOT ESTABLISHED · RSI: EXPERIMENTAL")
    check("external review not claimed",man.get("external_review")=="NOT_OBTAINED")
    print(json.dumps({"checks":len(ck),"passed":sum(1 for c in ck if c["ok"]),"failed":fail,"verdict":a["verdict"]},indent=1))
    return 0 if not fail else 1
if __name__=="__main__": sys.exit(main())
