#!/usr/bin/env python3
"""PVR standalone auditor — re-derives every world, q group, 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,WORLDS=60,60,9; QS=(1.0,0.8,0.5)
ARMS=("NEVER","BUDGET_Q1","BUDGET_Q","STOP_Q1","STOP_Q","ALWAYS","ORACLE_Q"); TENANT,SEED="cain42-pvr","pvr"
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 q_of(w): return QS[w%len(QS)]
def claim(salt,c):
    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)
    return {"candidate":c,"p":p,"severity":sev,"cost":cost,"defective":unit(salt,"d",c)<p}
def claims(salt): return [claim(salt,c) for c in range(CLAIMS)]
def detects(salt,q,c): return unit(salt,"q",c)<q
def order(salt,world,arm):
    xs=claims(salt); q=q_of(world)
    if arm=="NEVER": return []
    if arm=="ALWAYS": return [(x["candidate"],True) for x in xs]
    if arm in ("BUDGET_Q1","BUDGET_Q","STOP_Q1","STOP_Q"):
        qq=1.0 if arm.endswith("Q1") else q
        ranked=sorted(xs,key=lambda x:(-(qq*x["p"]*x["severity"]/max(1,x["cost"])),-(qq*x["p"]*x["severity"]),x["candidate"]))
        if arm.startswith("STOP"): return [(x["candidate"],qq*x["p"]*x["severity"]>x["cost"]) for x in ranked]
        return [(x["candidate"],True) for x in ranked]
    if arm=="ORACLE_Q":
        return [(x["candidate"],True) for x in sorted([x for x in xs if x["defective"] and q*x["severity"]>x["cost"]],key=lambda x:(x["cost"],-x["severity"],x["candidate"]))]
    raise ValueError(arm)
def run(salt,world,arm):
    base=f"{salt}-{world}"; xs={x["candidate"]:x for x in claims(base)}; q=q_of(world); spent=0; ver=set()
    for c,ok in order(base,world,arm):
        if not ok: continue
        x=xs[c]
        if spent+x["cost"]<=BUDGET: ver.add(c); spent+=x["cost"]
    loss=0; missed=0
    for c,x in xs.items():
        if not x["defective"]: continue
        if not (c in ver and detects(base,q,c)): loss+=x["severity"]; missed+=1
    return {"loss":loss,"spend":spent,"total":loss+spent,"verified":len(ver),"missed_defects":missed,
            "defective_total":sum(1 for x in xs.values() if x["defective"])}
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/"PVR_RUN_REPORT.json").read_text()); mem=json.loads((root/"PVR_MEMORY.json").read_text())
    salts=json.loads((root/"SALTS.json").read_text()); pre=json.loads((root/"PVR_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 q in QS:
            ws=[w for w in range(WORLDS) if q_of(w)==q]
            derived[s][str(q)]={arm:{k:mean([run(f"{salts[s]}-{w}",w,arm)[k] for w in ws]) for k in ("loss","spend","total","verified","missed_defects","defective_total")} for arm in ARMS}
    mm=0
    for s in derived:
        for q in QS:
            for arm in ARMS:
                exp=derived[s][str(q)][arm]; rep=a["measurements"][s][str(q)][arm]
                if any(rep.get(k)!=v for k,v in exp.items()): mm+=1
    check("every world, q group and policy re-derives",mm==0,f"{mm} mismatches")
    h1=all(all(derived[s][str(q)]["BUDGET_Q1"]["total"]==derived[s][str(q)]["BUDGET_Q"]["total"] for q in QS) for s in derived)
    h2=all(all(min(derived[s][str(q)][x]["total"] for x in ("BUDGET_Q1","BUDGET_Q","STOP_Q1","STOP_Q"))/derived[s][str(q)]["NEVER"]["total"]<=0.70 for q in (1.0,0.8)) for s in derived)
    h3=all(min(derived[s]["0.5"][x]["total"] for x in ("BUDGET_Q1","BUDGET_Q","STOP_Q1","STOP_Q"))/derived[s]["0.5"]["NEVER"]["total"]<=0.80 for s in derived)
    h4=all(derived[s]["0.5"]["STOP_Q"]["total"]<derived[s]["0.5"]["STOP_Q1"]["total"] for s in derived)
    computed={"H1_q_cancels_in_the_ranking":"SUPPORTED" if h1 else "NOT_SUPPORTED","H2_ranking_wins_when_the_verifier_is_accurate":"SUPPORTED" if h2 else "NOT_SUPPORTED",
              "H3_ranking_still_wins_at_q_0_5":"SUPPORTED" if h3 else "NOT_SUPPORTED","H4_q_aware_threshold_helps_at_low_q":"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]["q_values_recorded"]==[0.5,0.8,1.0]
            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"]=="world":
                if e["value"]["q"]!=q_of(e["value"]["world"]): cross+=1
            elif e["kind"]=="claim":
                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 ("p","severity","cost","defective")): cross+=1
    check("memory worlds and claims match the recomputation",cross==0,f"{cross} mismatches")
    check("H5 integrity and q record",okp)
    check("reported hypotheses match",{k:v.get("verdict") for k,v in a["hypotheses"].items()}=={**computed,"H5_integrity_and_q_record":"SUPPORTED" if okp else "NOT_SUPPORTED","H6_external_review":"BLOCKED"})
    check("verdict follows",a["verdict"]==("PARTIAL_VERIFICATION_VALUE_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","PVR_MANIFEST.json","MERKLE_ROOT.txt","PVR_SIGNED_BODY.json","PVR_VERIFICATION_RESULTS.json","PVR_TAMPER_RESULTS.json","PVR_PUBLIC_CHECK.json","PUBLICATION.json","PVR_OMEGA_SEAL.json","PVR_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())
