#!/usr/bin/env python3
"""PGL (E464-G) 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, then **re-derives every campaign from the revealed salts**: the
transient block sequences, the discovery ledger's promotions, every fresh 1,024-trial audit, every
certificate decision and every hypothesis. It also re-checks the ten enforcement rows for the expected
verdict, the typed refusal reason and the effect count, and re-verifies the audit memory chain.

Usage: python3 verify_pgl_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 = 4 * M
K_MAX = 16
ALPHA = 0.05
A_EFF = ALPHA / M
MATERIAL_BAR = 0.05
HELDOUT_TRIALS = 1024
CERTS_PER_CAMPAIGN = 8
EFFECTS = [0.10] * 4 + [0.35] * 3 + [0.03] * 6 + [0.0] * 27
TRANSIENT = list(range(4, 7))
TRANSIENT_BLOCKS = 4
CAMPAIGNS = 400
TENANT = "cain42-pgl"

EXPECT = {
    "valid_certificate": (True, None),
    "no_certificate": (False, "NO_CERTIFICATE"),
    "forged_certificate": (False, "CERTIFICATE_SIGNATURE_INVALID"),
    "replayed_certificate": (False, "CERTIFICATE_REPLAYED"),
    "expired_certificate": (False, "CERTIFICATE_EXPIRED"),
    "stale_ledger": (False, "LEDGER_STALE"),
    "wrong_candidate": (False, "CANDIDATE_MISMATCH"),
    "fresh_audit_failed": (False, "HELDOUT_BELOW_BAR"),
    "revoked_principal": (False, "PRINCIPAL_REVOKED"),
    "wrong_tenant": (False, "TENANT_MISMATCH"),
}


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"pgl|{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(p):
    cum, acc = [], 0.0
    for v in pmf(BLOCK, p):
        acc += v
        cum.append(acc)
    cum[-1] = 1.0
    return lambda r: bisect.bisect_left(cum, r.random())


_S = {round(p, 6): sampler(p) for p in (P0, P0 + 0.35, P0 + 0.10, P0 + 0.03)}


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


def fresh_audit(salt, campaign, candidate, trials=HELDOUT_TRIALS):
    p = P0 + (0.0 if candidate in TRANSIENT else EFFECTS[candidate])
    r = random.Random(seed(salt, campaign, candidate, "audit"))
    return sum(1 for _ in range(trials) if r.random() < p) / trials - P0


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


def kind(i):
    if i < 4:
        return "material"
    if i in TRANSIENT:
        return "transient"
    if 7 <= i < 13:
        return "weak"
    return "null"


def ledger(seqs, cut):
    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 len(promo) >= CERTS_PER_CAMPAIGN:
                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:
                break
            used += 1
            if give(i):
                promo.append(i)
                done.add(i)
                if len(promo) >= CERTS_PER_CAMPAIGN:
                    return promo, used
        if used >= BUDGET:
            break
    while used < BUDGET and alive and len(promo) < CERTS_PER_CAMPAIGN:
        moved = False
        for i in list(alive):
            if used >= BUDGET:
                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 len(promo) >= CERTS_PER_CAMPAIGN:
                    return promo, used
        if not moved:
            break
    return promo, used


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


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)
    b = {"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)}
    prom_all, cert_all, held = [], [], []
    blocks = []
    for c in range(CAMPAIGNS):
        seqs = [block_sequence(salt, c, i) for i in range(M)]
        p, u = ledger(seqs, cut)
        blocks.append(u)
        cs = []
        for i in p:
            a = fresh_audit(salt, c, i)
            if a >= MATERIAL_BAR:
                cs.append((i, a))
        prom_all.append(p)
        cert_all.append(cs)
        held += [a for _, a in cs]
    counts = ("material", "transient", "weak", "null")
    promoted = {k: sum(1 for p in prom_all for i in p if kind(i) == k) for k in counts}
    certified = {k: sum(1 for cs in cert_all for i, _ in cs if kind(i) == k) for k in counts}
    total_prom = sum(len(p) for p in prom_all)
    return {
        "campaigns": CAMPAIGNS,
        "promotions_mean": mean([len(p) for p in prom_all]),
        "promotions_total": total_prom,
        "promoted": promoted, "certified": certified,
        "certified_total": sum(len(c) for c in cert_all),
        "certificates_mean": mean([len(c) for c in cert_all]),
        "heldout_mean_certified": mean(held),
        "blocks_used_mean": mean(blocks),
        "refused": {k: promoted[k] - certified[k] for k in counts},
        "phantom_mean": promoted["transient"] / CAMPAIGNS,
        "phantom_share": (promoted["transient"] / total_prom) if total_prom else 0.0,
        "certified_material_mean": certified["material"] / CAMPAIGNS,
        "boundary": b,
    }


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 / "PGL_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 / "PGL_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") == "PROMOTION_GATE_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 f in ("campaigns", "promotions_total", "certified_total"):
            ck(rec[f] == got[f], f"{s}/{f}")
        for f in ("promotions_mean", "certificates_mean", "heldout_mean_certified",
                  "blocks_used_mean", "phantom_mean", "phantom_share", "certified_material_mean"):
            ck(close(rec[f], got[f]), f"{s}/{f}")
        for grp in ("promoted", "certified", "refused"):
            for k, v in rec[grp].items():
                ck(v == got[grp][k], f"{s}/{grp}/{k}")
        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_transients_are_attractive"]["verdict"]
           == ("SUPPORTED" if got["promoted"]["transient"] / CAMPAIGNS >= 2.5 else "NOT_SUPPORTED"), f"{s}/H1")
        ck(h["H2_gate_refuses_transients"]["verdict"]
           == ("SUPPORTED" if (got["refused"]["transient"] >= 0.95 * got["promoted"]["transient"]
                               and got["promoted"]["transient"] > 0) else "NOT_SUPPORTED"), f"{s}/H2")
        ck(h["H3_gate_refuses_null_luck"]["verdict"]
           == ("SUPPORTED" if got["refused"]["null"] >= 0.90 * max(1, got["promoted"]["null"]) else "NOT_SUPPORTED"),
           f"{s}/H3")
        ck(h["H4_gate_keeps_real_discoveries"]["verdict"]
           == ("SUPPORTED" if got["certified_material_mean"] >= 2.5 else "NOT_SUPPORTED"), f"{s}/H4")
        ck(h["H5_certified_effect"]["verdict"]
           == ("SUPPORTED" if got["heldout_mean_certified"] >= 0.08 else "NOT_SUPPORTED"), f"{s}/H5")
        # enforcement rows
        a = got["audit"]
        rows = {c["condition"]: c for c in a["conditions"]}
        ck(set(rows) == set(EXPECT), f"{s}/condition set")
        for name, (applied, reason) in EXPECT.items():
            c = rows.get(name, {})
            ck(c.get("applied") is applied, f"{s}/{name}/applied")
            if reason is not None:
                ck(c.get("reason") == reason, f"{s}/{name}/reason={c.get('reason')}")
        ck(rows["valid_certificate"]["effects"] == 1, f"{s}/valid effects")
        ck(rows["replayed_certificate"].get("first_applied") is True
           and rows["replayed_certificate"]["effects"] == 1, f"{s}/replay")
        others = [c for n, c in rows.items() if n not in ("valid_certificate", "replayed_certificate")]
        ck(all((not c["applied"]) and c["effects"] == 0 for c in others), f"{s}/refusal effects")
        # governance
        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")
        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"PGL 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())
