#!/usr/bin/env python3
"""ABP (E461) standalone auditor. Imports no CAIN code; runs from a clean copy of the bundle.

Verifies the signed manifest, every declared file hash and the Merkle root, the salt commitments, the exact
type-I error of every published sequential boundary, and then **re-derives the entire campaign from the
revealed salts**: all forty candidates' block results, all eight arms, every promotion, every false
promotion, every held-out effect, both generations policies, all hypotheses and the verdict. It also
re-verifies the audit campaign's governed-memory chain and every governance probe.

Usage: python3 verify_abp_offline.py [bundle_dir]
"""
from __future__ import annotations

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

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

STATUS = "AGI: NOT ESTABLISHED · RSI: EXPERIMENTAL"
P0 = 0.5
BLOCK = 64
M = 40
GENUINE = 1
DELTA = 0.07
BUDGET_BLOCKS = 4 * M
K_MAX = 16
ALPHA = 0.05
A_EFF = ALPHA / M
GENERATIONS = 3
GEN_BLOCKS = 4
HELDOUT_TRIALS = 1024
CAMPAIGNS = 600
AGENTS = ["atlas", "borealis", "cetus", "draco"]
SHARD = M // len(AGENTS)
TENANT = "cain42-abp"
PART1 = ["oracle", "ungoverned", "fixed_bonf", "seq_halving", "peek"]
PART2 = ["oracle", "refresh_5", "ledger"]


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


def pubhex(agent):
    k = Ed25519PrivateKey.from_private_bytes(hashlib.sha256(f"abp|{agent}".encode()).digest())
    return k.public_key().public_bytes(serialization.Encoding.Raw,
                                       serialization.PublicFormat.Raw).hex()


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


def pmf(n, p):
    return [math.comb(n, k) * (p ** k) * ((1 - p) ** (n - k)) for k in range(n + 1)]


_PMF0 = pmf(BLOCK, P0)


def crossing_prob(cutoffs, p=P0, block=BLOCK):
    pm = _PMF0 if (p == P0 and block == BLOCK) else pmf(block, p)
    dp = [1.0]
    total = 0.0
    for k, cut in enumerate(cutoffs, 1):
        ndp = [0.0] * (k * block + 1)
        for s, pr in enumerate(dp):
            if pr == 0.0:
                continue
            for b in range(block + 1):
                if pm[b]:
                    ndp[s + b] += pr * pm[b]
        cont = [0.0] * cut
        for s, pr in enumerate(ndp):
            if s >= cut:
                total += pr
            else:
                cont[s] = pr
        dp = cont
        if not any(dp):
            break
    return total


def cutoffs_for(c, K, block=BLOCK, p0=P0):
    sd = math.sqrt(block * p0 * (1 - p0))
    return [math.ceil(k * block * p0 + c * sd * math.sqrt(k)) for k in range(1, K + 1)]


def sampler(n, p):
    cum, acc = [], 0.0
    for v in pmf(n, p):
        acc += v
        cum.append(acc)
    cum[-1] = 1.0
    return lambda r: bisect.bisect_left(cum, r.random())


_B0 = sampler(BLOCK, P0)
_B1 = sampler(BLOCK, P0 + DELTA)


def seed(salt, campaign, candidate, tag):
    return int(sha(f"{salt}|{campaign}|{candidate}|{tag}".encode())[:16], 16)


def block_sequence(salt, campaign, candidate, n=K_MAX + 2 * GENERATIONS):
    draw = _B1 if candidate < GENUINE else _B0
    r = random.Random(seed(salt, campaign, candidate, "blocks"))
    return [draw(r) for _ in range(n)]


def heldout_effect(salt, campaign, candidate):
    p = P0 + (DELTA if candidate < GENUINE else 0.0)
    r = random.Random(seed(salt, campaign, candidate, "heldout"))
    hits = sum(1 for _ in range(HELDOUT_TRIALS) if r.random() < p)
    return hits / HELDOUT_TRIALS - P0


def zstat(s, looks):
    n = looks * BLOCK
    return (s - n * P0) / math.sqrt(n * P0 * (1 - P0))


def agent_of(c):
    return AGENTS[c // SHARD]


def allocate(seqs, cut):
    looks = {i: 0 for i in range(M)}
    s = {i: 0 for i in range(M)}
    used = 0

    def give(i):
        if looks[i] >= K_MAX:
            return False
        looks[i] += 1
        s[i] += seqs[i][looks[i] - 1]
        return s[i] >= cut[looks[i] - 1]

    alive = list(range(M))
    for i in alive:
        used += 1
        if give(i):
            return i, used
    target = M // 2
    for _ in range(6):
        alive = [i for i in alive if zstat(s[i], looks[i]) >= 0]
        if not alive:
            return None, used
        alive = sorted(alive, key=lambda i: -zstat(s[i], looks[i]))[:max(5, target)]
        target = max(5, target // 2)
        for i in list(alive):
            if used >= BUDGET_BLOCKS:
                break
            used += 1
            if give(i):
                return i, used
        if used >= BUDGET_BLOCKS:
            break
    while used < BUDGET_BLOCKS and alive:
        moved = False
        for i in list(alive):
            if used >= BUDGET_BLOCKS:
                break
            if looks[i] >= K_MAX:
                continue
            moved = True
            used += 1
            if give(i):
                return i, used
        if not moved:
            break
    return None, used


def arm_fixed(seqs, cut):
    best = None
    for i in range(M):
        s = sum(seqs[i][:4])
        if s >= cut[3]:
            z = zstat(s, 4)
            if best is None or z > best[1]:
                best = (i, z)
    return best[0] if best else None


def arm_ungoverned(seqs):
    return max(range(M), key=lambda i: sum(seqs[i][:4]))


def arm_local_best(seqs):
    return [max(range(a * SHARD, (a + 1) * SHARD), key=lambda i: sum(seqs[i][:4])) for a in range(len(AGENTS))]


def arm_peek(seqs, zf):
    for k in range(1, 5):
        for i in range(M):
            if zstat(sum(seqs[i][:k]), k) >= zf:
                return i
    return None


def arm_refresh(seqs, cut4):
    for g in range(GENERATIONS):
        for k in range(1, GEN_BLOCKS + 1):
            for i in range(M):
                if sum(seqs[i][4 * g:4 * g + k]) >= cut4[k - 1]:
                    return i
    return None


def arm_ledger(seqs, cutg):
    for g in range(GENERATIONS):
        for i in range(M):
            if sum(seqs[i][:4 * (g + 1)]) >= cutg[4 * (g + 1) - 1]:
                return i
    return None


def mean(xs):
    return statistics.mean(xs) if xs else 0.0


def recompute(salt):
    # the published boundary constants are re-derived exactly as the engine derives them
    from_engine = {}
    for key, K in (("fixed4", 4), ("adaptive16", K_MAX), ("gen12", GENERATIONS * GEN_BLOCKS)):
        lo, hi = 0.0, 8.0
        for _ in range(44):
            mid = (lo + hi) / 2
            if crossing_prob(cutoffs_for(mid, K), P0) > A_EFF:
                lo = mid
            else:
                hi = mid
        from_engine[key] = {"c": hi, "K": K, "cutoffs": cutoffs_for(hi, K),
                            "alpha_achieved": crossing_prob(cutoffs_for(hi, K), P0),
                            "alpha_tighter": crossing_prob(cutoffs_for(max(0.0, hi - 1e-3), K), P0)}
    cut4 = from_engine["fixed4"]["cutoffs"]
    cut16 = from_engine["adaptive16"]["cutoffs"]
    cutg = from_engine["gen12"]["cutoffs"]
    zf = 3.0235
    rows1 = {a: [] for a in PART1}
    rows2 = {a: [] for a in PART2}
    held1 = {a: [] for a in PART1}
    held2 = {a: [] for a in PART2}
    blocks = []
    any_false = 0
    for c in range(CAMPAIGNS):
        seqs = [block_sequence(salt, c, i) for i in range(M)]
        pick, used = allocate(seqs, cut16)
        blocks.append(used)
        lb = arm_local_best(seqs)
        if any(p >= GENUINE for p in lb):
            any_false += 1
        p1 = {"oracle": 0, "ungoverned": arm_ungoverned(seqs), "fixed_bonf": arm_fixed(seqs, cut4),
              "seq_halving": pick, "peek": arm_peek(seqs, zf)}
        for a in PART1:
            rows1[a].append(p1[a])
            held1[a].append(heldout_effect(salt, c, p1[a]) if p1[a] is not None else None)
        p2 = {"oracle": 0, "refresh_5": arm_refresh(seqs, cut4), "ledger": arm_ledger(seqs, cutg)}
        for a in PART2:
            rows2[a].append(p2[a])
            held2[a].append(heldout_effect(salt, c, p2[a]) if p2[a] is not None else None)

    def pack(rows, arms, held):
        out = {}
        for a in arms:
            picks = rows[a]
            idx = [k for k, p in enumerate(picks) if p is not None]
            eff = [held[a][k] for k in idx]
            out[a] = {"campaigns": len(picks), "promotions": len(idx),
                      "promotion_rate": len(idx) / len(picks),
                      "power": sum(1 for k in idx if picks[k] < GENUINE) / len(picks),
                      "false_promotion_rate": sum(1 for k in idx if picks[k] >= GENUINE) / len(picks),
                      "false_share_of_promotions": (sum(1 for k in idx if picks[k] >= GENUINE) / len(idx)) if idx else 0.0,
                      "mean_heldout_effect_promoted": mean(eff)}
        return out

    return {"part1": pack(rows1, PART1, held1), "part2": pack(rows2, PART2, held2),
            "local_best": {"any_false_rate": any_false / CAMPAIGNS},
            "boundaries": from_engine,
            "adaptive_blocks_used_mean": mean(blocks), "adaptive_blocks_used_max": max(blocks)}


def close(a, b, tol=2e-9):
    return abs(float(a) - float(b)) <= tol


def main():
    bdir = Path(sys.argv[1] if len(sys.argv) > 1 else ".")
    fails = []

    def ck(cond, what):
        if not cond:
            fails.append(what)

    man = json.loads((bdir / "ABP_MANIFEST.json").read_text())
    pub = man["pubkey_ed25519"]
    body = {k: v for k, v in man.items() if k != "signature"}
    try:
        Ed25519PublicKey.from_public_bytes(bytes.fromhex(pub)).verify(
            bytes.fromhex(man["signature"]), canon(body))
    except Exception:
        fails.append("manifest signature")
    ck(man.get("status") == STATUS, "status line")
    ck(man.get("engine_withheld") is True, "engine withheld flag")
    for name, h in man["files"].items():
        p = bdir / name
        ck(p.exists() and sha(p.read_bytes()) == h, f"file hash {name}")
    leaves = sorted(sha((bdir / n).read_bytes()) for n in man["files"])
    while len(leaves) > 1:
        if len(leaves) % 2:
            leaves.append(leaves[-1])
        leaves = [sha((leaves[i] + leaves[i + 1]).encode()) for i in range(0, len(leaves), 2)]
    ck(leaves and leaves[0] == man["merkle_root"], "merkle root")
    ck((bdir / "MERKLE_ROOT.txt").read_text().strip() == man["merkle_root"], "MERKLE_ROOT.txt")

    salts = json.loads((bdir / "SALTS.json").read_text())
    rep = json.loads((bdir / "ABP_RUN_REPORT.json").read_text())
    ck({k: sha(v.encode()) for k, v in salts.items()} == rep["salt_commitment"], "salt commitment")
    ck(rep.get("verdict") == "GOVERNED_ALPHA_LEDGER_SUPPORTED", "verdict")
    ck(rep["design"]["model_calls"] == 0, "no model calls")

    for s in ("salt1", "salt2"):
        rec = recompute(salts[s])
        got = rep["scenarios"][s]
        for part in ("part1", "part2"):
            for arm, d in rec[part].items():
                g = got[part][arm]
                for f in ("campaigns", "promotions"):
                    ck(d[f] == g[f], f"{s}/{part}/{arm}/{f}")
                for f in ("promotion_rate", "power", "false_promotion_rate",
                          "false_share_of_promotions", "mean_heldout_effect_promoted"):
                    ck(close(d[f], g[f]), f"{s}/{part}/{arm}/{f}")
        ck(close(rec["local_best"]["any_false_rate"], got["local_best"]["any_false_rate"]),
           f"{s}/local_best")
        ck(close(rec["adaptive_blocks_used_mean"], got["adaptive_blocks_used_mean"]), f"{s}/blocks_mean")
        ck(rec["adaptive_blocks_used_max"] == got["adaptive_blocks_used_max"], f"{s}/blocks_max")
        for key in ("fixed4", "adaptive16", "gen12"):
            rb, gb = rec["boundaries"][key], got["boundaries"][key]
            ck(rb["cutoffs"] == gb["cutoffs"], f"{s}/{key}/cutoffs")
            ck(close(rb["alpha_achieved"], gb["alpha_achieved"], 1e-12), f"{s}/{key}/alpha")
            ck(gb["alpha_achieved"] <= A_EFF + 1e-12, f"{s}/{key}/alpha<=target")
            ck(gb["alpha_tighter"] > A_EFF, f"{s}/{key}/boundary_not_loose")
        # hypotheses recomputed from the recomputed numbers
        h = rep["hypotheses"]
        ck(h["H1_ungoverned_promotes_noise"]["verdict"]
           == ("SUPPORTED" if got["part1"]["ungoverned"]["false_promotion_rate"] >= 0.30 else "NOT_SUPPORTED"),
           f"{s}/H1")
        ck(("SUPPORTED" if (got["part1"]["fixed_bonf"]["false_promotion_rate"] <= 0.06) else "NOT_SUPPORTED")
           == h["H2_fixed_boundary_controls_error"]["verdict"], f"{s}/H2")
        h3 = (got["part1"]["seq_halving"]["false_promotion_rate"] <= 0.06
              and got["part1"]["seq_halving"]["power"] >= got["part1"]["fixed_bonf"]["power"] + 0.15)
        ck(h["H3_adaptive_allocation_wins"]["verdict"] == ("SUPPORTED" if h3 else "NOT_SUPPORTED"), f"{s}/H3")
        h4 = (got["part1"]["peek"]["false_promotion_rate"] >= 1.5 * ALPHA
              and got["part1"]["peek"]["false_promotion_rate"]
              >= 2 * got["part1"]["seq_halving"]["false_promotion_rate"])
        ck(h["H4_optional_stopping_inflates"]["verdict"] == ("SUPPORTED" if h4 else "NOT_SUPPORTED"), f"{s}/H4")
        h5 = (got["part2"]["ledger"]["false_promotion_rate"] <= 0.06
              and got["part2"]["refresh_5"]["false_promotion_rate"]
              >= 2 * got["part2"]["ledger"]["false_promotion_rate"])
        ck(h["H5_ledger_beats_refresh"]["verdict"] == ("SUPPORTED" if h5 else "NOT_SUPPORTED"), f"{s}/H5")
        h6 = (got["part1"]["seq_halving"]["mean_heldout_effect_promoted"] >= 0.05
              and got["part1"]["seq_halving"]["false_promotion_rate"]
              <= 0.25 * got["part1"]["ungoverned"]["false_promotion_rate"])
        ck(h["H6_heldout_effect"]["verdict"] == ("SUPPORTED" if h6 else "NOT_SUPPORTED"), f"{s}/H6")
        a = got["audit"]
        ck(a["chain_valid"] and a["replay_refused"] and a["tenant_probe"]["foreign_visible_to_us"] == 0
           and a["tamper_detected"] and all(not p["granted"] for p in a["authority_probes"]),
           f"{s}/H7 governance")
        # re-verify the audit memory chain from the exported rows
        prev, bad = "", []
        for e in a["raw"]:
            payload = {k: e[k] for k in ("seq", "tenant", "agent", "kind", "key", "value", "prev",
                                         "created_at", "nonce", "grants_authority", "executable")}
            b = canon(payload)
            ok = (e["prev"] == prev and e["tenant"] == TENANT
                  and sha(e["prev"].encode() + b + bytes.fromhex(e["sig"])) == e["hash"])
            if ok:
                try:
                    Ed25519PublicKey.from_public_bytes(bytes.fromhex(pubhex(e["agent"]))).verify(
                        bytes.fromhex(e["sig"]), b)
                except Exception:
                    ok = False
            if not ok:
                bad.append(e["seq"])
            prev = e["hash"]
        ck(not bad, f"{s}/audit chain")
        ck(all(e["grants_authority"] is False and e["executable"] is False for e in a["raw"]),
           f"{s}/audit no authority")

    print(f"ABP auditor: {'PASS' if not fails else 'FAIL'} ({len(fails)} failures)")
    for f in fails[:20]:
        print("  FAIL:", f)
    return 0 if not fails else 1


if __name__ == "__main__":
    sys.exit(main())
