#!/usr/bin/env python3
# SPDX-FileCopyrightText: 2026 Science Against Authoritarianism Contributors
# SPDX-License-Identifier: GPL-3.0-or-later
"""Tier-1 Mechanism Simulator: Correlated Institutional Capture & Veto-Player Redundancy.

Models a core structural mechanism connecting concentrated wealth/patronage to
authoritarian consolidation (Tsebelis 2002 veto players; Winters 2011 wealth
defense; Hellman, Jones & Kaufmann 2003 state capture; Cooley, Heathershaw &
Sharman 2018 reputation/financial enablers):

  Suppose a democracy has k institutional guardrails (judiciary, independent
  media, universities/science, anti-corruption/AML, legislature), each with
  standalone probability r_i of resisting capture under pressure.

  1. Independent institutions (funding/ownership correlation rho = 0):
     Joint probability that at least one veto pillar holds is
       R_ind = 1 - prod(1 - r_i).
     With k = 5 independent pillars at r = 0.50, R_ind = 1 - 0.5^5 = 0.96875.

  2. Correlated wealth/patronage capture (rho in (0, 1]):
     When a shared wealth, corporate, media, or offshore patronage shock couples
     institutional vulnerabilities via a one-factor Gaussian latent model
       Z_i = sqrt(rho) * F + sqrt(1 - rho) * e_i,
     where institution i holds iff Z_i > Phi^{-1}(1 - r_i), joint survival
     R(rho) degrades monotonically toward the comonotonic worst-case bound
       R_comonotonic = max_i(r_i).
     Five apparent guardrails coupled at rho -> 1 behave like ONE guardrail.

  3. Transparency / beneficial-ownership lever:
     Public beneficial ownership and funding disclosure reduce effective
     cross-pillar coupling rho_eff = rho * (1 - transparency_reduction),
     restoring independent veto-player redundancy.

EPISTEMIC BOUNDARY (T1 mechanism / T4 stylized model — NOT a country forecast):
  This simulator validates the mathematical redundancy-collapse mechanism under
  correlated capture. It does NOT predict whether any real country will fall.
  Pure stdlib, deterministic with fixed seeds.
"""
from __future__ import annotations

import math
import random
from typing import Sequence


def _norm_cdf(x: float) -> float:
    return 0.5 * (1.0 + math.erf(x / math.sqrt(2.0)))


def _norm_ppf(p: float) -> float:
    """Inverse standard normal CDF via bisection (exact to ~1e-12, pure stdlib)."""
    if not (0.0 < p < 1.0):
        raise ValueError(f"probability p must lie in (0, 1), got {p}")
    lo, hi = -10.0, 10.0
    for _ in range(80):
        mid = 0.5 * (lo + hi)
        if _norm_cdf(mid) < p:
            lo = mid
        else:
            hi = mid
    return 0.5 * (lo + hi)


def independent_resilience(pillar_strengths: Sequence[float]) -> float:
    """Exact analytical Tsebelis redundancy bound when pillars are independent (rho = 0)."""
    if not pillar_strengths:
        raise ValueError("pillar_strengths must be non-empty")
    fail_all = 1.0
    for r in pillar_strengths:
        if not (0.0 <= r <= 1.0):
            raise ValueError(f"pillar strength must be in [0, 1], got {r}")
        fail_all *= (1.0 - r)
    return 1.0 - fail_all


def comonotonic_resilience(pillar_strengths: Sequence[float]) -> float:
    """Exact analytical lower bound when all pillars share one shock (rho = 1)."""
    if not pillar_strengths:
        raise ValueError("pillar_strengths must be non-empty")
    for r in pillar_strengths:
        if not (0.0 <= r <= 1.0):
            raise ValueError(f"pillar strength must be in [0, 1], got {r}")
    return max(pillar_strengths)


def simulate_correlated_capture(
    pillar_strengths: Sequence[float],
    rho: float,
    *,
    trials: int = 10000,
    seed: int = 42,
) -> dict[str, float]:
    """Monte Carlo survival under one-factor Gaussian correlated capture shock.

    Returns exact analytical bounds plus simulated joint survival probability
    (fraction of trials where >= 1 institutional pillar resists capture) and
    mean number of surviving pillars.
    """
    if not pillar_strengths:
        raise ValueError("pillar_strengths must be non-empty")
    if not (0.0 <= rho <= 1.0):
        raise ValueError(f"rho must lie in [0, 1], got {rho}")
    if trials <= 0:
        raise ValueError(f"trials must be positive, got {trials}")

    # Thresholds c_i such that P(Z_i > c_i) = r_i
    thresholds: list[float | None] = []
    for r in pillar_strengths:
        if not (0.0 <= r <= 1.0):
            raise ValueError(f"pillar strength must be in [0, 1], got {r}")
        if r == 0.0:
            thresholds.append(math.inf)
        elif r == 1.0:
            thresholds.append(-math.inf)
        else:
            thresholds.append(_norm_ppf(1.0 - r))

    s_common = math.sqrt(rho)
    s_idio = math.sqrt(1.0 - rho)
    rng = random.Random(seed)

    survived_any = 0
    total_holding = 0
    for _ in range(trials):
        common = rng.gauss(0.0, 1.0) if rho > 0.0 else 0.0
        holding = 0
        for c_i in thresholds:
            if c_i == -math.inf:
                holding += 1
            elif c_i == math.inf:
                continue
            else:
                idio = rng.gauss(0.0, 1.0) if rho < 1.0 else 0.0
                z_i = s_common * common + s_idio * idio
                if z_i > c_i:
                    holding += 1
        if holding > 0:
            survived_any += 1
        total_holding += holding

    return {
        "rho": rho,
        "joint_survival": survived_any / trials,
        "mean_pillars_holding": total_holding / trials,
        "independent_bound": independent_resilience(pillar_strengths),
        "comonotonic_bound": comonotonic_resilience(pillar_strengths),
    }


def effective_rho(base_rho: float, transparency: float) -> float:
    """Stylized transparency lever: disclosure decouples shared covert patronage."""
    if not (0.0 <= base_rho <= 1.0) or not (0.0 <= transparency <= 1.0):
        raise ValueError("base_rho and transparency must lie in [0, 1]")
    return base_rho * (1.0 - transparency)


def sweep_correlation(
    pillar_strengths: Sequence[float] = (0.5, 0.5, 0.5, 0.5, 0.5),
    rhos: Sequence[float] = (0.0, 0.25, 0.50, 0.75, 0.95, 1.0),
    *,
    trials: int = 8000,
    seed: int = 42,
) -> list[dict[str, float]]:
    """Run the mechanism sweep across increasing cross-pillar capture correlation."""
    return [
        simulate_correlated_capture(pillar_strengths, rho, trials=trials, seed=seed + i)
        for i, rho in enumerate(rhos)
    ]


def main() -> int:
    pillars = (0.5, 0.5, 0.5, 0.5, 0.5)
    print("Correlated Institutional Capture — 5 veto pillars (each standalone r=0.50)")
    print("  [stylized mechanism only — not a country prediction]")
    for row in sweep_correlation(pillars, trials=5000, seed=42):
        print(
            f"  rho={row['rho']:.2f}  joint_survival={row['joint_survival']:.4f}  "
            f"(ind_bound={row['independent_bound']:.4f}, comonotonic={row['comonotonic_bound']:.4f})"
        )
    return 0


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