#!/usr/bin/env python3
"""CEV standalone auditor — re-derives the colluding-evaluator 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

CANDIDATES, N_REAL = 40, 12
N_TRIALS, FOCAL, FOCAL_REAL, FOCAL_NULL = 24, 8, 3, 5
REAL_P, NULL_P, OMIT, BAR = 0.72, 0.50, 0.60, 0.65
CAMPAIGNS = 200
ARMS = ("honest1", "collude1", "quorum2of3", "collude2", "control", "oracle")
MEMORY_ARMS = ARMS[:5]
ROLES = {"honest1": ["honest"], "collude1": ["collude"], "quorum2of3": ["honest", "honest", "collude"],
         "collude2": ["honest", "collude", "collude"], "control": ["honest"]}
TENANT, SEED = "cain42-cev", "cev"
STATUS = "AGI: NOT ESTABLISHED · RSI: EXPERIMENTAL"

def canon(o): return json.dumps(o, sort_keys=True, separators=(",", ":"), ensure_ascii=False).encode()
def sha(b): return hashlib.sha256(b).hexdigest()
def _u(salt, campaign, tag):
    h = hashlib.sha256(f"{salt}|{campaign}|{tag}".encode()).digest()
    return int.from_bytes(h[:8], "big") / 2 ** 64

def roles(salt, campaign):
    order = sorted(range(CANDIDATES), key=lambda c: _u(salt, campaign, f"real|{c}"))
    real = set(order[:N_REAL])
    order2 = sorted(range(CANDIDATES), key=lambda c: _u(salt, campaign, f"focal|{c}"))
    fr = [c for c in order2 if c in real][:FOCAL_REAL]
    fn = [c for c in order2 if c not in real][:FOCAL_NULL]
    out = []
    for c in sorted(fr + fn):
        p = REAL_P if c in real else NULL_P
        s = sum(1 for t in range(N_TRIALS) if _u(salt, campaign, f"trial|{c}|{t}") < p)
        base = c * N_TRIALS
        executed = [base + i for i in range(N_TRIALS)]
        ok = [base + i for i in range(N_TRIALS) if _u(salt, campaign, f"trial|{c}|{i}") < p]
        if len(ok) == N_TRIALS: ok = ok[:-1]
        out.append({"candidate": c, "real": c in real, "successes": s, "n": N_TRIALS,
                    "executed": executed, "manifest": ok})
    return out

def majority(logs):
    if not logs: return None
    if len(logs) == 1: return logs[0]
    for x in logs:
        if sum(1 for y in logs if y == x) >= 2: return x
    return None

def run_campaign(salt, arm, i):
    p = roles(salt, i)
    if arm == "control":
        for c in p: c["manifest"] = list(c["executed"])
    logs = [[c["executed"] if r == "honest" else c["manifest"] for c in p] for r in ROLES.get(arm, [])]
    if arm == "oracle":
        est = {c["candidate"]: (REAL_P if c["real"] else NULL_P) for c in p}; det = ref = False
    else:
        lg = majority(logs)
        if lg is None:
            est, det, ref = {}, True, True
        else:
            est, det = {}, False
            for c, l in zip(p, lg):
                if sorted(l) != sorted(c["manifest"]):
                    det = True; continue
                est[c["candidate"]] = (c["successes"] / N_TRIALS) if arm == "control" else (1.0 if c["manifest"] else 0.0)
            ref = det
    best = None
    for c, v in est.items():
        if v > BAR and (best is None or v > est[best] or (v == est[best] and c < best)): best = c
    real = bool(best is not None and next(x for x in p if x["candidate"] == best)["real"])
    return {"arm": arm, "campaign": i, "declared": best is not None, "promoted": best, "real": real,
            "false_promotion": bool(best is not None and not real), "correct": bool(best is not None and real),
            "detected": bool(det), "refused": bool(ref), "estimates": {str(k): round(v, 6) for k, v in est.items()}}

def main():
    d = Path(sys.argv[1]); checks, fails = [], []
    def ck(n, ok):
        checks.append(n)
        if not ok: fails.append(n)
    man = json.loads((d / "MANIFEST.json").read_text())
    try:
        Ed25519PublicKey.from_public_bytes(bytes.fromhex(man["pubkey_ed25519"])).verify(
            bytes.fromhex(man["signature"]), canon({k: v for k, v in man.items() if k != "signature"})); ck("manifest signature", True)
    except Exception: ck("manifest signature", False)
    fs = sorted(p for p in d.rglob("*") if p.is_file() and p.name not in
                ("MANIFEST.json", "CEV_MANIFEST.json", "MERKLE_ROOT.txt", "PUBLICATION.json",
                 "CEV_OMEGA_SEAL.json", "CEV_PUBKEY.pem", "CEV_SIGNED_BODY.json") and "__pycache__" not in p.parts)
    hashed = {str(p.relative_to(d)): sha(p.read_bytes()) for p in fs}
    ck("file hashes", all(man["files"].get(k) == v for k, v in hashed.items()))
    ck("no unlisted file", set(man["files"]) == set(hashed))
    l = sorted(man["files"].values())
    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)]
    ck("merkle root", (l[0] if l else sha(b"")) == man["merkle_root"])
    pre = json.loads((d / "CEV_PREREGISTRATION.json").read_text())
    sal = json.loads((d / "SALTS.json").read_text())
    ck("salt commitment", {k: sha(v.encode()) for k, v in sal.items()} == pre["salts_commitment"])
    ck("status line", pre["status"] == STATUS)
    rep = json.loads((d / "CEV_RUN_REPORT.json").read_text())
    rows_file = json.loads((d / "CEV_ROWS.json").read_text())
    mem = json.loads((d / "CEV_MEMORY.json").read_text())
    sims = {s: {a: [run_campaign(sal[s], a, i) for i in range(CAMPAIGNS)] for a in ARMS} for s in sal}
    for s in sal:
        for a in ARMS:
            got, sim = rows_file[s][a], sims[s][a]
            ck(f"rows {s}:{a}", len(got) == len(sim))
            ck(f"values {s}:{a}", all(g.get(k) == r.get(k) for g, r in zip(got, sim)
                                      for k in ("declared", "promoted", "real", "false_promotion", "correct",
                                                "detected", "refused", "estimates")))
    def rate(s, a, k): return sum(1 for r in sims[s][a] if r[k]) / CAMPAIGNS
    H = rep["hypotheses"]
    ck("H1", all(rate(s, "collude1", "false_promotion") > 0.40 and rate(s, "collude1", "detected") == 0 for s in sal)
       and H["H1_one_colluder_defeats_binding"]["verdict"] == "SUPPORTED")
    ck("H2", all(rate(s, "quorum2of3", "detected") == 1.0 and rate(s, "quorum2of3", "refused") == 1.0
                 and rate(s, "quorum2of3", "declared") == 0 for s in sal)
       and H["H2_two_of_three_detects"]["verdict"] == "SUPPORTED")
    ck("H3", all(rate(s, "collude2", "false_promotion") > 0.40 and rate(s, "collude2", "detected") == 0 for s in sal)
       and H["H3_two_of_three_colluding_defeats_the_quorum"]["verdict"] == "SUPPORTED")
    ck("H4", all(rate(s, "honest1", "detected") == 1.0 and rate(s, "honest1", "refused") == 1.0
                 and sum(1 for r in sims[s]["control"] if r["detected"] or r["refused"]) == 0
                 and rate(s, "control", "false_promotion") <= 0.05 for s in sal)
       and H["H4_honest_control"]["verdict"] == "SUPPORTED")
    h5 = H["H5_integrity_and_process_separation"]["detail"]
    ck("H5", all(h5[f"{s}:{a}"]["chain_and_signatures"] and h5[f"{s}:{a}"]["replay_refused"]
                 and h5[f"{s}:{a}"]["tamper_detected"] and h5[f"{s}:{a}"]["authority_from_memory_refused"]
                 for s in sal for a in MEMORY_ARMS)
       and all(len(set(h5[f"{s}:pids"])) == 3 for s in sal)
       and H["H5_integrity_and_process_separation"]["verdict"] == "SUPPORTED")
    core = all(H[k]["verdict"] == "SUPPORTED" for k in
               ("H1_one_colluder_defeats_binding", "H2_two_of_three_detects",
                "H3_two_of_three_colluding_defeats_the_quorum", "H4_honest_control",
                "H5_integrity_and_process_separation"))
    ck("verdict", rep["verdict"] == ("EVALUATOR_QUORUM_REQUIRED" if core else "NOT_SUPPORTED"))
    ck("summary", all(rep["summary"][s][a]["false_promotion"] == round(rate(s, a, "false_promotion"), 4)
                      and rep["summary"][s][a]["detected"] == round(rate(s, a, "detected"), 4) for s in sal for a in ARMS))
    ck("no model calls", rep["design"]["model_calls"] == 0)
    def kp(a): return Ed25519PrivateKey.from_private_bytes(hashlib.sha256(f"{SEED}|{a}".encode()).digest())
    def nce(a, kind, key, value): return sha(canon({"agent": a, "kind": kind, "key": key, "value": value}))[:16]
    for s in mem:
        for a, entries in mem[s].items():
            prev, bad = "", 0
            for e in entries:
                b = 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() + b + bytes.fromhex(e["sig"])) == e["hash"]
                      and e["nonce"] == nce(e["agent"], e["kind"], e["key"], e["value"])
                      and e["grants_authority"] is False and e["executable"] is False)
                if ok:
                    try:
                        Ed25519PublicKey.from_public_bytes(kp(e["agent"]).public_key().public_bytes(
                            serialization.Encoding.Raw, serialization.PublicFormat.Raw)).verify(bytes.fromhex(e["sig"]), b)
                    except Exception: ok = False
                bad += 0 if ok else 1; prev = e["hash"]
            ck(f"memory chain {s}:{a}", bad == 0)
    ck("no engine source", not any(x.name.endswith(".py") and x.name != "verify_cev_offline.py" for x in d.rglob("*") if x.is_file()))
    print(f"{len(checks)-len(fails)}/{len(checks)} checks passed")
    for n in fails: print("FAIL", n)
    return 0 if not fails else 1

if __name__ == "__main__":
    raise SystemExit(main())
