#!/usr/bin/env python3
"""DPL (E463-D) 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 the published boundary, and then **re-derives every campaign from the revealed salts**: all
forty candidates' block results, all four arms, every promotion, every held-out effect, every hypothesis and
the verdict. Re-verifies the audit campaign's governed-memory chain and every governance probe.

Usage: python3 verify_dpl_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
BUDGET_BLOCKS = 4 * M
K_MAX = 16
ALPHA = 0.05
A_EFF = ALPHA / M
HELDOUT_TRIALS = 1024
MATERIAL_BAR = 0.06
EFFECTS = [0.10] * 4 + [0.03] * 6 + [0.0] * 30
CAMPAIGNS = 900
AGENTS = ["atlas", "borealis", "cetus", "draco"]
SHARD = M // len(AGENTS)
TENANT = "cain42-dpl"
ARMS = ["oracle", "first", "all", "pilot"]


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


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


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


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())


_S = {}
for _p in set(round(P0 + e, 6) for e in EFFECTS):
    _S[_p] = sampler(BLOCK, _p)


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 + 4):
    draw = _S[round(P0 + EFFECTS[candidate], 6)]
    r = random.Random(seed(salt, campaign, candidate, "blocks"))
    return [draw(r) for _ in range(n)]


def heldout_effect(salt, campaign, candidate):
    p = P0 + EFFECTS[candidate]
    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 sequential(seqs, cut, stop_at_first):
    looks = {i: 0 for i in range(M)}
    tot = {i: 0 for i in range(M)}
    used, promo, done = 0, [], set()

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

    alive = list(range(M))
    for i in alive:
        used += 1
        if give(i):
            promo.append(i)
            done.add(i)
            if stop_at_first:
                return promo, used
    target = M // 2
    for _ in range(6):
        alive = [i for i in alive if i not in done and zstat(tot[i], looks[i]) >= 0]
        if not alive:
            break
        alive = sorted(alive, key=lambda i: -zstat(tot[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):
                promo.append(i)
                done.add(i)
                if stop_at_first:
                    return promo, used
        if used >= BUDGET_BLOCKS:
            break
        if stop_at_first and promo:
            return promo, used
    while used < BUDGET_BLOCKS and alive:
        moved = False
        for i in list(alive):
            if used >= BUDGET_BLOCKS:
                break
            if i in done or looks[i] >= K_MAX:
                continue
            moved = True
            used += 1
            if give(i):
                promo.append(i)
                done.add(i)
                if stop_at_first:
                    return promo, used
        if stop_at_first and promo:
            return promo, used
        if not moved:
            break
    return promo, used


def pilot(seqs, cut):
    tot = {i: seqs[i][0] for i in range(M)}
    looks = {i: 1 for i in range(M)}
    used, promo, done = M, [], set()
    for i in range(M):
        if tot[i] >= cut[0]:
            promo.append(i)
            done.add(i)
    alive = sorted([i for i in range(M) if i not in done],
                   key=lambda i: -zstat(tot[i], 1))[:8]
    while used < BUDGET_BLOCKS and alive:
        moved = False
        for i in list(alive):
            if used >= BUDGET_BLOCKS:
                break
            if i in done or looks[i] >= K_MAX:
                continue
            moved = True
            used += 1
            looks[i] += 1
            tot[i] += seqs[i][looks[i] - 1]
            if tot[i] >= cut[looks[i] - 1]:
                promo.append(i)
                done.add(i)
        if not moved:
            break
    return promo, used


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


def pack(promos, useds, helds):
    n = len(promos)
    mat = [sum(1 for i in p if EFFECTS[i] >= MATERIAL_BAR) for p in promos]
    nul = [sum(1 for i in p if EFFECTS[i] == 0.0) for p in promos]
    weak = [sum(1 for i in p if 0.0 < EFFECTS[i] < MATERIAL_BAR) for p in promos]
    return {
        "campaigns": n,
        "mean_material": mean(mat), "mean_null": mean(nul), "mean_weak": mean(weak),
        "material_total": sum(mat), "null_total": sum(nul), "weak_total": sum(weak),
        "campaigns_with_any_material": sum(1 for x in mat if x >= 1) / n,
        "campaigns_with_two_material": sum(1 for x in mat if x >= 2) / n,
        "campaigns_with_any_null": sum(1 for x in nul if x >= 1) / n,
        "null_promotion_rate": sum(1 for x in nul if x >= 1) / n,
        "mean_promotions": mean([len(p) for p in promos]),
        "blocks_used_mean": mean(useds), "blocks_used_max": max(useds),
        "mean_heldout_effect": mean([e for es in helds for e in es]),
        "material_per_100_blocks": 100 * sum(mat) / max(1e-9, sum(useds)),
    }


def recompute(salt):
    lo, hi = 0.0, 8.0
    for _ in range(44):
        mid = (lo + hi) / 2
        if crossing_prob(cutoffs_for(mid, K_MAX), P0) > A_EFF:
            lo = mid
        else:
            hi = mid
    cut = cutoffs_for(hi, K_MAX)
    boundary = {"c": hi, "K": K_MAX, "cutoffs": cut,
                "alpha_achieved": crossing_prob(cut, P0),
                "alpha_tighter": crossing_prob(cutoffs_for(max(0.0, hi - 1e-3), K_MAX), P0)}
    promos = {a: [] for a in ARMS}
    useds = {a: [] for a in ARMS}
    helds = {a: [] for a in ARMS}
    for c in range(CAMPAIGNS):
        seqs = [block_sequence(salt, c, i) for i in range(M)]
        picks = {"oracle": (list(range(4)), 0),
                 "first": sequential(seqs, cut, True),
                 "all": sequential(seqs, cut, False),
                 "pilot": pilot(seqs, cut)}
        for a, (p, u) in picks.items():
            promos[a].append(p)
            useds[a].append(u)
            helds[a].append([heldout_effect(salt, c, i) for i in p])
    out = {a: pack(promos[a], useds[a], helds[a]) for a in ARMS}
    out["boundary"] = boundary
    return out


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 / "DPL_MANIFEST.json").read_text())
    body = {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"]), 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 / "DPL_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") == "DISCOVERY_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 arm in ARMS:
            for f, v in rec[arm].items():
                ck(close(v, got[arm][f]), f"{s}/{arm}/{f}")
        ck(rec["boundary"]["cutoffs"] == got["boundary"]["cutoffs"], f"{s}/cutoffs")
        ck(close(rec["boundary"]["alpha_achieved"], got["boundary"]["alpha_achieved"], 1e-12),
           f"{s}/alpha")
        ck(got["boundary"]["alpha_achieved"] <= A_EFF + 1e-12, f"{s}/alpha<=target")
        ck(got["boundary"]["alpha_tighter"] > A_EFF, f"{s}/boundary_not_loose")
        h = rep["hypotheses"]
        ck(h["H1_single_winner_wastes_budget"]["verdict"]
           == ("SUPPORTED" if got["first"]["blocks_used_mean"] <= 0.65 * BUDGET_BLOCKS else "NOT_SUPPORTED"),
           f"{s}/H1")
        ck(h["H2_discovery_engine_finds_more"]["verdict"]
           == ("SUPPORTED" if got["all"]["mean_material"] >= 1.8 * got["first"]["mean_material"] else "NOT_SUPPORTED"),
           f"{s}/H2")
        ck(h["H3_error_still_controlled"]["verdict"]
           == ("SUPPORTED" if got["all"]["null_promotion_rate"] <= 0.06 else "NOT_SUPPORTED"), f"{s}/H3")
        ck(h["H4_multiple_per_campaign"]["verdict"]
           == ("SUPPORTED" if got["all"]["campaigns_with_two_material"] >= 0.90 else "NOT_SUPPORTED"),
           f"{s}/H4")
        ck(h["H5_near_oracle"]["verdict"]
           == ("SUPPORTED" if got["all"]["mean_material"] >= 0.75 * got["oracle"]["mean_material"] else "NOT_SUPPORTED"),
           f"{s}/H5")
        ck(h["H6_refinement_adds_nothing"]["verdict"]
           == ("SUPPORTED" if got["pilot"]["mean_material"] <= got["all"]["mean_material"] + 0.10 else "NOT_SUPPORTED"),
           f"{s}/H6")
        ck(h["H7_heldout_effect"]["verdict"]
           == ("SUPPORTED" if got["all"]["mean_heldout_effect"] >= 0.05 else "NOT_SUPPORTED"), f"{s}/H7")
        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 a["material_promoted"] >= 2 and all(not p["granted"] for p in a["authority_probes"]),
           f"{s}/H8 governance")
        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"DPL 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())
