#!/usr/bin/env python3
"""RCP standalone auditor — re-derives the run passport from the revealed salts.

Rebuilds the candidate rates, the ten honest roots and their four runs, every attacker claim set under
all three receipt strengths and six root counts, every vote and run count, every cost ratio, every
aggregate, every hypothesis and the verdict; then verifies the signed manifest, file hashes and Merkle
root, the salt commitments, and every Ed25519 signature and SHA-256 link of the exported memory.
Imports no CAIN code.

Usage: python3 verify_rcp_offline.py <bundle-dir>
"""
from __future__ import annotations

import bisect
import hashlib
import json
import statistics
import sys
from pathlib import Path

from cryptography.hazmat.primitives import serialization
from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PrivateKey, Ed25519PublicKey

CANDIDATES = 12
TRIALS = 40
H_ROOTS = 10
HONEST_RUNS = 4
TRUTH = 0
DECOY = 3
P_TRUTH = 0.62
P_DECOY = 0.45
P_OTHER_LO = 0.30
P_OTHER_HI = 0.46
LUCKY_DRAWS = 2048
WORLDS = 40
CAP = 384
R_LIST = (1, 8, 16, 32, 64, 128)
REGIMES = ("ID_ONLY", "UNBOUND", "BOUND")
HONEST_RUNS_TOTAL = H_ROOTS * HONEST_RUNS
TENANT, SEED = "cain42-rcp", "rcp"


def sha(b):
    return hashlib.sha256(b).hexdigest()


def canon(o):
    return json.dumps(o, sort_keys=True, separators=(",", ":"), ensure_ascii=False).encode()


def unit(salt, key):
    h = hashlib.sha256(f"{salt}|{key}".encode()).digest()
    return int.from_bytes(h[:8], "big") / 2 ** 64


def p_of(salt):
    p = {c: P_OTHER_LO + (P_OTHER_HI - P_OTHER_LO) * unit(salt, f"p|{c}") for c in range(CANDIDATES)}
    p[TRUTH] = P_TRUTH
    p[DECOY] = P_DECOY
    return p


def cdf(n, p):
    out, cum, pmf = [], 0.0, (1.0 - p) ** n
    for k in range(n + 1):
        cum += pmf
        out.append(cum)
        if k < n:
            pmf = pmf * (n - k) / (k + 1) * p / (1.0 - p)
    out[-1] = 1.0
    return out


def draw(u, table):
    return bisect.bisect_left(table, u)


def tables(salt):
    p = p_of(salt)
    return {c: cdf(TRIALS, p[c]) for c in range(CANDIDATES)}


def honest_sample(salt, world, root, cand, k, tab):
    return draw(unit(salt, f"h|{world}|{root}|{cand}|{k}"), tab[cand])


def lucky_sample(salt, world, root, tab):
    best, best_k = -1, 0
    for k in range(LUCKY_DRAWS):
        s = draw(unit(salt, f"lky|{world}|{root}|{k}"), tab[DECOY])
        if s > best:
            best, best_k = s, k
    return best, best_k


def luckies(salt, world, tab):
    return [lucky_sample(salt, world, j, tab)[0] for j in range(HONEST_RUNS)]


def claims_for(salt, world, regime, roots, tab, luck):
    out = []
    for r in range(H_ROOTS):
        for c in range(CANDIDATES):
            for k in range(HONEST_RUNS):
                out.append({"agent": f"H{r}-{c}-{k}", "root": f"root{r}", "candidate": c,
                            "trials": TRIALS, "successes": honest_sample(salt, world, r, c, k, tab),
                            "experiment": f"h|{world}|{r}|{c}|{k}", "sybil": False})
    if regime == "ID_ONLY":
        for j in range(CAP):
            out.append({"agent": f"S0-{j}", "root": "syb0", "candidate": DECOY, "trials": TRIALS,
                        "successes": luck[0], "experiment": f"declared|{world}|0|{j}", "sybil": True})
    else:
        for r in range(roots):
            for j in range(HONEST_RUNS):
                exp = f"run|{world}|{j}" if regime == "UNBOUND" else f"bound|{world}|{r}|{j}"
                out.append({"agent": f"S{r}-{j}", "root": f"syb{r}", "candidate": DECOY, "trials": TRIALS,
                            "successes": luck[j], "experiment": exp, "sybil": True})
    return out


def attacker_runs(regime, roots):
    if regime == "ID_ONLY":
        return 1
    if regime == "UNBOUND":
        return HONEST_RUNS
    return HONEST_RUNS * roots


# ---------------------------------------------------------------- policy (mirrored)

def score(claims, cap):
    per = {}
    for x in claims:
        a = per.setdefault((x["candidate"], x["root"]), {"s": 0, "t": 0, "exp": set()})
        a["s"] += x["successes"]; a["t"] += x["trials"]; a["exp"].add(x["experiment"])
    acc = {c: [0.0, 0.0] for c in range(CANDIDATES)}
    for (c, root), a in per.items():
        if not a["t"]:
            continue
        w = float(min(len(a["exp"]), cap))
        acc[c][0] += w * (a["s"] / a["t"]); acc[c][1] += w
    return {c: (v / w if w else -1.0) for c, (v, w) in acc.items()}


def select(scores):
    return max(range(CANDIDATES), key=lambda c: (scores[c], -c))


def evaluate(claims, cap):
    return select(score(claims, cap))


def votes(claims, cap):
    per = {}
    for x in claims:
        if x["candidate"] != DECOY:
            continue
        per.setdefault(x["root"], set()).add(x["experiment"])
    return {r: min(len(e), cap) for r, e in per.items()}


def simulate(salt, regime, roots):
    tab = tables(salt)
    luck = {w: luckies(salt, w, tab) for w in range(WORLDS)}
    per_world = [claims_for(salt, w, regime, roots, tab, luck[w]) for w in range(WORLDS)]
    cap_yes = honest_truth = 0
    vs, rs, cs, rows = [], [], [], []
    for i, cl in enumerate(per_world):
        honest = [x for x in cl if not x["sybil"]]
        dec = evaluate(cl, CAP)
        cap_yes += int(dec == DECOY)
        honest_truth += int(evaluate(honest, CAP) == TRUTH)
        v = sum(val for r, val in votes(cl, CAP).items() if r.startswith("syb"))
        runs = attacker_runs(regime, roots)
        vs.append(v); rs.append(runs); cs.append(runs / HONEST_RUNS_TOTAL)
        rows.append({"world": i, "votes": v, "capture": dec == DECOY,
                     "truth_without_attacker": evaluate(honest, CAP) == TRUTH})
    return ({"capture_rate": cap_yes / WORLDS, "honest_truth_rate": honest_truth / WORLDS,
             "attacker_votes": statistics.mean(vs), "attacker_runs": statistics.mean(rs),
             "cost_ratio": statistics.mean(cs)}, rows)


def hypotheses(m):
    H = {}

    def both(fn):
        return all(fn(s) for s in m)

    H["H1_an_unbound_receipt_is_a_passport"] = {
        "verdict": "SUPPORTED" if both(lambda s: m[s]["ID_ONLY_R1"]["capture_rate"] >= 0.80
                                       and m[s]["ID_ONLY_R1"]["attacker_runs"] == 1
                                       and m[s]["UNBOUND_R32"]["capture_rate"] >= 0.50
                                       and m[s]["BOUND_R32"]["attacker_runs"] >= 20 * m[s]["UNBOUND_R32"]["attacker_runs"]) else "NOT_SUPPORTED"}
    H["H2_the_passport_divides_the_price_by_roots"] = {
        "verdict": "SUPPORTED" if both(lambda s: all(abs(m[s][f"BOUND_R{R}"]["attacker_runs"] /
                                                         max(1.0, m[s][f"UNBOUND_R{R}"]["attacker_runs"]) - R) <= 0.01 * R
                                                     for R in R_LIST if R >= 8)
                                       and len({m[s][f"UNBOUND_R{R}"]["attacker_runs"] for R in R_LIST}) == 1) else "NOT_SUPPORTED"}
    H["H3_votes_scale_with_roots_only_unbound"] = {
        "verdict": "SUPPORTED" if both(lambda s: all(abs(m[s][f"UNBOUND_R{R}"]["attacker_votes"] - 4 * R) <= 1
                                                     and abs(m[s][f"BOUND_R{R}"]["attacker_votes"] - 4 * R) <= 1
                                                     for R in R_LIST)) else "NOT_SUPPORTED"}
    H["H4_honest_control"] = {
        "verdict": "SUPPORTED" if both(lambda s: all(m[s][f"{rg}_R{R}"]["honest_truth_rate"] == 1.0
                                                     for rg in REGIMES for R in R_LIST)) else "NOT_SUPPORTED"}
    H["H5_integrity_and_no_authority"] = {
        "verdict": "SUPPORTED" if both(lambda s: all(m[s][rg]["probe"]["chain_and_signatures"]
                                                     and m[s][rg]["probe"]["replay_refused"]
                                                     and m[s][rg]["probe"]["tamper_detected"]
                                                     and m[s][rg]["probe"]["authority_from_memory_refused"]
                                                     and m[s][rg]["probe"]["authority_flag_false_everywhere"]
                                                     for rg in REGIMES)) else "NOT_SUPPORTED"}
    H["H6_limit_binding_prices_capture_it_does_not_prevent_it"] = {
        "verdict": "LIMIT_CONFIRMED" if both(lambda s: m[s]["BOUND_R128"]["capture_rate"] >= 0.50) else "NOT_CONFIRMED"}
    H["H7_external_review"] = {"verdict": "BLOCKED"}
    core = ("H1_an_unbound_receipt_is_a_passport", "H2_the_passport_divides_the_price_by_roots",
            "H3_votes_scale_with_roots_only_unbound", "H4_honest_control",
            "H5_integrity_and_no_authority", "H6_limit_binding_prices_capture_it_does_not_prevent_it")
    ok = all(H[k]["verdict"] in ("SUPPORTED", "LIMIT_CONFIRMED") for k in core)
    return H, ("RUN_PASSPORT_SUPPORTED" if ok else "NOT_SUPPORTED")


# ---------------------------------------------------------------- memory

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]


def verify_entries(entries):
    prev, bad = "", 0
    for e in entries:
        body = canon({k: e[k] for k in ("seq", "tenant", "agent", "root", "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"] == _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"]), body)
            except Exception:
                ok = False
        bad += 0 if ok else 1
        prev = e["hash"]
    return bad


def jn(x):
    return json.loads(json.dumps(x, sort_keys=True))


def main():
    d = Path(sys.argv[1])
    rep = json.loads((d / "RCP_RUN_REPORT.json").read_text())
    sal = json.loads((d / "SALTS.json").read_text())
    pre = json.loads((d / "RCP_PREREGISTRATION.json").read_text())
    mem = json.loads((d / "RCP_MEMORY.json").read_text())
    rows_file = json.loads((d / "RCP_ROWS.json").read_text())
    man = json.loads((d / "MANIFEST.json").read_text())
    checks, fails = [], []

    def ck(n, ok):
        checks.append(n)
        if not ok:
            fails.append(n)

    body = canon({k: v for k, v in man.items() if k != "signature"})
    try:
        Ed25519PublicKey.from_public_bytes(bytes.fromhex(man["pubkey_ed25519"])).verify(
            bytes.fromhex(man["signature"]), body)
        ck("manifest signature", True)
    except Exception:
        ck("manifest signature", False)
    EX = {"MANIFEST.json", "RCP_MANIFEST.json", "MERKLE_ROOT.txt", "PUBLICATION.json", "RCP_OMEGA_SEAL.json",
          "RCP_PUBKEY.pem", "RCP_SIGNED_BODY.json", "RCP_VERIFICATION_RESULTS.json",
          "RCP_TAMPER_RESULTS.json", "RCP_PUBLIC_CHECK.json"}
    fs = sorted(p for p in d.rglob("*") if p.is_file() and p.name not in EX 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"])
    ck("engine withheld", man.get("engine_withheld") is True)
    ck("external review not claimed", man.get("external_review") == "NOT_OBTAINED")
    ck("salt commitment", {k: sha(v.encode()) for k, v in sal.items()} == pre["salts_commitment"])
    ck("status line", rep["status"] == "AGI: NOT ESTABLISHED · RSI: EXPERIMENTAL")
    ck("no model calls", rep["design"]["model_calls"] == 0)
    ck("regimes", tuple(rep["design"]["regimes"]) == REGIMES)
    ck("roots swept", tuple(rep["design"]["roots_swept"]) == R_LIST)

    total = 0
    for salt in mem:
        for rg in REGIMES:
            entries = mem[salt][rg]
            ck(f"memory chain {salt}:{rg}", verify_entries(entries) == 0)
            ck(f"memory seq {salt}:{rg}", [e["seq"] for e in entries] == list(range(1, len(entries) + 1)))
            ck(f"entry count {salt}:{rg}", len(entries) == rep["memory_entries"][salt][rg])
            total += len(entries)
    ck("memory entries total", total == sum(rep["memory_entries"][s][rg] for s in mem for rg in REGIMES))

    for s in sal:
        for rg in REGIMES:
            for R in R_LIST:
                key = f"{rg}_R{R}"
                out, rws = simulate(sal[s], rg, R)
                rm = rep["measurements"][s][key]
                ck(f"agg {s}:{key}", jn({k: rm[k] for k in out}) == jn(out))
                ck(f"rows {s}:{key}", jn(rows_file[s][key]) == jn(rws))

    H, verdict = hypotheses(rep["measurements"])
    for k, v in H.items():
        ck(f"hypothesis {k}", rep["hypotheses"][k]["verdict"] == v["verdict"])
    ck("verdict", rep["verdict"] == verdict)
    ck("no engine source", not any(x.suffix == ".py" and x.name != "verify_rcp_offline.py"
                                   for x in d.rglob("*") if x.is_file()))

    bad = [n for n in checks if n in fails]
    print(f"{len(checks) - len(bad)}/{len(checks)} checks passed")
    for n in bad[:20]:
        print("FAIL", n)
    return 0 if not bad else 1


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