#!/usr/bin/env python3
"""EBQ standalone auditor — re-derives every queue order and metric from the salts."""
from __future__ import annotations
import hashlib, json, sys
from pathlib import Path
from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PublicKey

AGENTS=("A0","A1","A2","A3","A4","A5"); PER=40; CAP=200; Q=4; LIAR="A0"
ARMS=("FIFO","SHORTEST","DECLARED","VERIFIED","DRR","WFQ","ORACLE_FAIR"); TENANT,SEED="cain42-ebq","ebq"
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 cost(a,i): return 1+(i%4)
def tv(salt,a,i): return 1+int(unit(salt,"v",a,i)*10)
def dv(salt,a,i): return 10 if a==LIAR else tv(salt,a,i)
def items(salt): return [{"agent":a,"index":i,"cost":cost(a,i),"true":tv(salt,a,i),"declared":dv(salt,a,i)} for a in AGENTS for i in range(PER)]
def order(salt,arm):
    xs=items(salt); by={a:[x for x in xs if x["agent"]==a] for a in AGENTS}; cur={a:0 for a in AGENTS}
    k=lambda x:(x["agent"],x["index"])
    if arm=="FIFO":
        return [by[a][i] for i in range(PER) for a in AGENTS]
    if arm=="SHORTEST": return sorted(xs,key=lambda x:(x["cost"],k(x)))
    if arm=="DECLARED": return sorted(xs,key=lambda x:(-x["declared"],k(x)))
    if arm=="VERIFIED": return sorted(xs,key=lambda x:(-x["true"],k(x)))
    if arm=="DRR":
        out=[]; defi={a:Q for a in AGENTS}; guard=0
        while len(out)<len(xs):
            prog=False
            for a in AGENTS:
                if cur[a]>=PER: continue
                n=by[a][cur[a]]
                if n["cost"]<=defi[a]:
                    out.append(n); cur[a]+=1; defi[a]-=n["cost"]; prog=True
            if not prog:
                defi={a:Q for a in AGENTS}; guard+=1
                if guard>len(xs):
                    live=[a for a in AGENTS if cur[a]<PER]
                    a=min(live,key=lambda z:(by[z][cur[z]]["cost"],AGENTS.index(z)))
                    out.append(by[a][cur[a]]); cur[a]+=1; defi[a]=0; guard=0
        return out
    if arm in ("WFQ","ORACLE_FAIR"):
        out=[]; served={a:0 for a in AGENTS}
        while len(out)<len(xs):
            live=[a for a in AGENTS if cur[a]<PER]
            a=min(live,key=lambda z:(served[z],AGENTS.index(z)))
            n=by[a][cur[a]]; out.append(n); cur[a]+=1; served[a]+=n["cost"]
        return out
    raise ValueError(arm)
def run(salt,arm):
    done=[]; spent=0
    for x in order(salt,arm):
        if spent+x["cost"]<=CAP: done.append(x); spent+=x["cost"]
    per={a:{"units":0,"count":0,"value":0,"c4d":0,"c4t":0} for a in AGENTS}
    for x in items(salt):
        if x["cost"]==4: per[x["agent"]]["c4t"]+=1
    for x in done:
        p=per[x["agent"]]; p["units"]+=x["cost"]; p["count"]+=1; p["value"]+=x["true"]
        if x["cost"]==4: p["c4d"]+=1
    units=[per[a]["units"] for a in AGENTS]; c4d=sum(per[a]["c4d"] for a in AGENTS); c4t=sum(per[a]["c4t"] for a in AGENTS)
    jain=round(sum(units)**2/(len(units)*sum(u*u for u in units)),6) if sum(units) else 0.0
    return {"value":sum(x["true"] for x in done),"spent":spent,"processed":len(done),
            "a0_share":round(per[LIAR]["units"]/max(1,spent),6),"min_units":min(units),
            "fair_share":round(CAP/len(AGENTS),6),"cost4_frac":round(c4d/c4t,6),"jain":jain}
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/"EBQ_RUN_REPORT.json").read_text()); mem=json.loads((root/"EBQ_MEMORY.json").read_text())
    salts=json.loads((root/"SALTS.json").read_text()); pre=json.loads((root/"EBQ_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={s:{arm:run(salts[s],arm) for arm in ARMS} for s in ("salt1","salt2")}
    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 arm's order, spend and metric re-derives",mm==0,f"{mm} mismatches")
    def ms(s): return derived[s]
    h1=all(ms(s)["DECLARED"]["a0_share"]>=0.40 and ms(s)["DECLARED"]["value"]/ms(s)["VERIFIED"]["value"]<=0.95 for s in derived)
    h2=all(ms(s)["SHORTEST"]["cost4_frac"]<=0.10 and ms(s)["WFQ"]["cost4_frac"]>=0.25 for s in derived)
    h3=all(min(ms(s)["DRR"]["min_units"],ms(s)["WFQ"]["min_units"])>=0.60*ms(s)["WFQ"]["fair_share"] and max(ms(s)["DRR"]["a0_share"],ms(s)["WFQ"]["a0_share"])<=0.20 for s in derived)
    h4=all(ms(s)["FIFO"]["value"]/ms(s)["VERIFIED"]["value"]<=0.85 and ms(s)["FIFO"]["value"]/ms(s)["SHORTEST"]["value"]<=0.85 for s in derived)
    computed={"H1_declared_value_is_captured":"SUPPORTED" if h1 else "NOT_SUPPORTED","H2_shortest_starves_expensive_work":"SUPPORTED" if h2 else "NOT_SUPPORTED",
              "H3_fair_queueing_bounds_starvation_and_capture":"SUPPORTED" if h3 else "NOT_SUPPORTED","H4_fairness_costs_value":"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 ("queue","scheduler","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]))
    # the memory's dequeue log must match the recomputed DECLARED processing order
    cross=0
    for s in ("salt1","salt2"):
        done=[]; spent=0
        for x in order(salts[s],"DECLARED"):
            if spent+x["cost"]<=CAP: done.append(x); spent+=x["cost"]
        logged=[e["value"] for e in mem["entries"][s] if e["kind"]=="dequeue"]
        if len(logged)!=len(done): cross+=1
        else:
            for e,x in zip(logged,done):
                if any(e[k]!=x[k] for k in ("agent","index","cost","declared","true")): cross+=1
    check("memory dequeue log matches the recomputed queue",cross==0,f"{cross} mismatches")
    okp=all(a["probes"][s]["chain_and_signatures"] and a["probes"][s]["replay_refused"] and a["probes"][s]["tamper_detected"]
            and a["probes"][s]["declared_vs_verified_mismatches"]==a["probes"][s]["liar_misdeclared"] and a["probes"][s]["liar_misdeclared"]>0
            and a["probes"][s]["honest_declarations_clean"]
            and a["probes"][s]["authority_from_memory_refused"] and a["probes"][s]["authority_flag_false_everywhere"] for s in ("salt1","salt2"))
    check("H5 integrity and declaration check",okp)
    check("reported hypotheses match",{k:v.get("verdict") for k,v in a["hypotheses"].items()}=={**computed,"H5_queue_integrity_and_declaration_check":"SUPPORTED" if okp else "NOT_SUPPORTED","H6_external_review":"BLOCKED"})
    check("verdict follows",a["verdict"]==("EXPERIMENT_QUEUE_GOVERNANCE_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","EBQ_MANIFEST.json","MERKLE_ROOT.txt","EBQ_SIGNED_BODY.json","EBQ_VERIFICATION_RESULTS.json","EBQ_TAMPER_RESULTS.json","EBQ_PUBLIC_CHECK.json","PUBLICATION.json","EBQ_OMEGA_SEAL.json","EBQ_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())
