#!/usr/bin/env python3
"""PRI standalone auditor — re-derives the priority/backdating 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

EVENTS=12; DELTAS=(2,4,6,8,10,12,14,16,18,20,22,24); WORLDS=12
ARMS=("TIMESTAMP","ARRIVAL","ANCHOR","ANCHOR_REQUIRED","ORACLE"); MEMORY_ARMS=ARMS[:-1]
TENANT,SEED="cain42-pri","pri"; SIGNERS=("honest","backdater","anchor","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 build(s):
    base=1000+int(sha(s.encode())[:4],16)%500; claims=[]
    for i in range(EVENTS):
        t=base+i*30; d=DELTAS[i]
        claims.append({"id":f"h{i}","event":i,"agent":"honest","declared":t,"anchor":t,"seq":1,"anchored":True,"truth":True})
        claims.append({"id":f"b{i}","event":i,"agent":"backdater","declared":t-d,"anchor":t+1,"seq":0,"anchored":True,"truth":False})
    return claims
def choose(pool,policy):
    if policy=="TIMESTAMP": return min(pool,key=lambda c:(c["declared"],c["seq"]))
    if policy=="ARRIVAL": return min(pool,key=lambda c:(c["seq"],c["declared"]))
    return min([c for c in pool if c["anchored"]],key=lambda c:(c["anchor"],c["seq"]))
def run_world(s):
    claims=build(s); out={}
    for arm in ARMS:
        wrong=0; anchors=0; order=[]
        for e in range(EVENTS):
            pool=[c for c in claims if c["event"]==e]
            if arm=="ANCHOR_REQUIRED": pool=[c for c in pool if c["agent"]!="backdater"]
            if arm=="ANCHOR_REQUIRED": pool=[c for c in pool if c["anchored"]]
            c=choose(pool, "ANCHOR" if arm=="ANCHOR_REQUIRED" else arm)
            anchors+=sum(1 for x in pool if x["anchored"]); wrong+= 0 if c["truth"] else 1; order.append(c["id"])
        out[arm]={"wrong":wrong,"correct":EVENTS-wrong,"anchors":anchors,"order":order}
    dis=all(min([c for c in claims if c["event"]==e],key=lambda c:(c["declared"],c["seq"]))["agent"]!=min([c for c in claims if c["event"]==e],key=lambda c:(c["anchor"],c["seq"]))["agent"] for e in range(EVENTS))
    return {"arms":out,"dis":dis}
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/"PRI_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/"PRI_RUN_REPORT.json").read_text()); wp=json.loads((d/"PRI_WORLDS.json").read_text()); mem=json.loads((d/"PRI_MEMORY.json").read_text())
    for k,v in salts.items(): ok(f"salt {k}",report["salts"][k]==sha(v.encode()))
    derived={}
    for label in ("salt1","salt2"):
        ws=[run_world(sha(f"{salts[label]}|world|{w}".encode())) for w in range(WORLDS)]; summary={}
        for a in ARMS:
            summary[a]={"wrong":sum(w["arms"][a]["wrong"] for w in ws),"correct":sum(w["arms"][a]["correct"] for w in ws),
                        "anchors":sum(w["arms"][a]["anchors"] for w in ws),"wrong_rate":round(sum(w["arms"][a]["wrong"] for w in ws)/(len(ws)*EVENTS),6)}
            for f in ("wrong","correct","anchors","wrong_rate"):
                ok(f"{label} {a} {f}",report["measures"][label][a][f]==summary[a][f])
            for w in range(WORLDS):
                ok(f"{label} {a} w{w} order",wp[label][a][w]["order"]==ws[w]["arms"][a]["order"])
        summary["declared_order_disagrees"]=round(sum(1 for w in ws if w["dis"])/WORLDS,6)
        ok(f"{label} clocks",report["measures"][label]["declared_order_disagrees"]==summary["declared_order_disagrees"])
        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"])
            pr={}
            for e in mem[label][a]:
                if e["kind"]=="priority": pr[e["value"]["world"]]=e["value"]["orders"]
            good=True
            for w in range(WORLDS):
                good=good and pr.get(w,{}).get(a)==ws[w]["arms"][a]["order"]
            ok(f"{label} {a} priorities",good)
    S=derived; H=report["hypotheses"]
    comp={"H1_a_declared_time_is_captured":all(S[s]["TIMESTAMP"]["wrong_rate"]==1.0 and S[s]["ARRIVAL"]["wrong_rate"]==1.0 for s in S),
          "H2_an_anchor_resolves_priority":all(S[s]["ANCHOR"]["wrong"]==0 and S[s]["ANCHOR"]["wrong_rate"]==0.0 for s in S),
          "H3_requiring_an_anchor_is_cheaper":all(S[s]["ANCHOR_REQUIRED"]["wrong"]==0 and S[s]["ANCHOR_REQUIRED"]["wrong_rate"]==0.0 and S[s]["ANCHOR_REQUIRED"]["anchors"]<S[s]["ANCHOR"]["anchors"] for s in S),
          "H4_the_two_clocks_disagree":all(S[s]["declared_order_disagrees"]==1.0 for s in S),
          "H5_integrity_and_no_authority":H["H5_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("H6 blocked",H["H6_external_review"]["verdict"]=="BLOCKED")
    core=all(H[k]["ok"] for k in H if k!="H6_external_review"); ok("verdict",report["verdict"]==("PRIORITY_ANCHOR_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())
