#!/usr/bin/env python3
# SPDX-FileCopyrightText: 2026 Science Against Authoritarianism Contributors
# SPDX-License-Identifier: GPL-3.0-or-later
"""Cooperation Barriers & Institutional Remedies — 10th Tier-1 validated mechanism simulator.

Models a repeated N-agent public-goods dilemma explicitly coupling the five empirically
documented failure modes and institutional solutions from the cooperation literature:

  1. Conditional cooperation & baseline free-riding decay (Fischbacher et al. 2001)
  2. Antisocial punishment in weak-rule-of-law settings (Herrmann, Thöni & Gächter 2008, Science)
  3. Baseline endowment inequality breaking collective action unless paired with
     proportional fairness rules (Hauser, Hilbe, Chatterjee & Nowak 2019, Nature)
  4. Pluralistic ignorance / false social reality suppressing latent conditional
     cooperators until verified common knowledge is revealed (Andre et al. 2024,
     Nature Climate Change; Sparkman et al. 2022)
  5. Legitimate, transparent institutional sanctioning + positive-reward reciprocity
     (Gürerk, Irlenbusch & Rockenbach 2006, Science; Baldassarri & Grossman 2011, PNAS;
     Rand et al. 2009, Science; Ostrom 2010, AER)

Scope boundary: stylized mechanism demonstration (Tier 1 of the mathematical model,
Tier 4 of modeling assumptions, Tier 6 for real-world population prediction).
Pure stdlib, deterministic given seed.
"""
from __future__ import annotations

import math
import random
from dataclasses import dataclass
from typing import Any


@dataclass(frozen=True)
class CooperationDilemmaResult:
    rounds: list[dict[str, float]]
    initial_cooperation: float
    final_cooperation: float
    mean_cooperation: float
    final_welfare_index: float
    regime: str
    dominant_barrier: str


def _clip01(x: float) -> float:
    return max(0.0, min(1.0, float(x)))


def simulate_cooperation_dilemma(
    *,
    n_agents: int = 80,
    n_rounds: int = 30,
    initial_cooperator_share: float = 0.65,
    inequality: float = 0.20,
    misperception: float = 0.25,
    antisocial_punishment: float = 0.10,
    legitimate_institution: float = 0.50,
    positive_reciprocity: float = 0.45,
    proportional_fairness: bool = True,
    seed: int = 42,
) -> CooperationDilemmaResult:
    """Run a deterministic N-agent repeated public-goods dilemma under barriers & remedies.

    Each agent i has:
      - an endowment e_i > 0 drawn around 1.0 with dispersion controlled by `inequality`
      - a conditional-cooperation threshold tau_i in [0.15, 0.85]
      - a cooperation state c_i in {0, 1}

    At each round t:
      - Agents observe a perceived peer cooperation share `p_perceived = p_true * (1 - 0.65 * misperception)`.
      - Endowment asymmetry creates a fairness penalty proportional to `inequality * (1 - fairness_offset)`,
        where `fairness_offset = 0.70 * legitimate_institution` when `proportional_fairness` is enabled
        (Hauser et al. 2019: transparent proportional burden-sharing mitigates inequality breakdown).
      - Unchecked antisocial punishment (`antisocial_punishment * (1 - 0.85 * legitimate_institution)`)
        directly penalizes cooperators and drives them to defect (Herrmann et al. 2008).
      - Legitimate transparent rules (`legitimate_institution`) deter free-riding and suppress
        retaliatory antisocial punishment, while `positive_reciprocity` lowers the cooperation
        threshold via social/material rewards (Gürerk et al. 2006; Rand et al. 2009).
    """
    if n_agents < 4:
        raise ValueError("n_agents must be >= 4")
    if n_rounds < 1:
        raise ValueError("n_rounds must be >= 1")

    ineq = _clip01(inequality)
    misp = _clip01(misperception)
    anti = _clip01(antisocial_punishment)
    inst = _clip01(legitimate_institution)
    recip = _clip01(positive_reciprocity)
    init_share = _clip01(initial_cooperator_share)

    rng = random.Random(seed)
    # Agent thresholds (heterogeneous conditional cooperators) & endowments
    thresholds = [0.22 + 0.56 * rng.random() for _ in range(n_agents)]
    # Log-normal-like spread around 1.0 controlled by `inequality`
    endowments = [math.exp(ineq * 1.4 * (rng.random() - 0.5)) for _ in range(n_agents)]
    mean_endow = sum(endowments) / n_agents
    endowments = [e / mean_endow for e in endowments]

    n_init = int(round(init_share * n_agents))
    coop = [1 if i < n_init else 0 for i in range(n_agents)]
    rng.shuffle(coop)

    rounds_out: list[dict[str, float]] = []
    for t in range(n_rounds):
        true_share = sum(coop) / n_agents
        # Pluralistic ignorance: perceived peer cooperation underestimates true willingness
        perceived_share = _clip01(true_share * (1.0 - 0.65 * misp))

        # Effective antisocial retaliation shrinks sharply under legitimate rule of law
        eff_antisocial = anti * (1.0 - 0.85 * inst)
        # Effective inequality drag shrinks under transparent proportional burden-sharing
        fairness_mitigation = (0.72 * inst + 0.18 * recip) if proportional_fairness else 0.0
        eff_ineq_drag = ineq * max(0.0, 1.0 - min(0.90, fairness_mitigation))

        # Group welfare index: public good multiplier (1.8x) minus antisocial-punishment & conflict waste
        contrib_weighted = sum(endowments[i] * coop[i] for i in range(n_agents)) / n_agents
        welfare = max(0.0, 1.0 + 0.80 * contrib_weighted - 0.35 * eff_antisocial - 0.20 * eff_ineq_drag)

        rounds_out.append({
            "round": float(t),
            "cooperation_share": round(true_share, 4),
            "perceived_share": round(perceived_share, 4),
            "welfare_index": round(welfare, 4),
        })

        # Next-round strategic update (conditional cooperation + institutional incentives)
        next_coop: list[int] = []
        # Institutional deterrence + positive reciprocity boost perceived cooperation payoff
        inst_boost = 0.42 * inst + 0.34 * recip
        barrier_drag = 0.48 * eff_antisocial + 0.44 * eff_ineq_drag + 0.14 * (1.0 - inst)

        for i in range(n_agents):
            # Poorer agents experience extra fairness friction when inequality is high and unmitigated
            asymmetry_gap = abs(endowments[i] - 1.0) * eff_ineq_drag * 0.25
            effective_signal = perceived_share + inst_boost - barrier_drag - asymmetry_gap
            # Smooth stochastic best-response around agent's conditional threshold
            margin = effective_signal - thresholds[i]
            prob = 1.0 / (1.0 + math.exp(-7.0 * margin))
            next_coop.append(1 if rng.random() < prob else 0)
        coop = next_coop

    final_share = rounds_out[-1]["cooperation_share"]
    mean_share = sum(r["cooperation_share"] for r in rounds_out) / len(rounds_out)
    final_welfare = rounds_out[-1]["welfare_index"]

    if final_share >= 0.78:
        regime = "SUSTAINED_COOPERATION"
    elif final_share <= 0.25:
        regime = "DEFECTION_COLLAPSE"
    else:
        regime = "FRAGILE_MIXED"

    # Identify dominant active barrier diagnostically
    barriers = {
        "antisocial_punishment": anti * (1.0 - 0.85 * inst),
        "inequality_asymmetry": ineq * (1.0 - (0.72 * inst if proportional_fairness else 0.0)),
        "pluralistic_ignorance": misp * 0.65,
        "weak_legitimate_rules": (1.0 - inst) * 0.50,
    }
    dominant = max(barriers.items(), key=lambda kv: kv[1])[0]

    return CooperationDilemmaResult(
        rounds=rounds_out,
        initial_cooperation=rounds_out[0]["cooperation_share"],
        final_cooperation=final_share,
        mean_cooperation=round(mean_share, 4),
        final_welfare_index=final_welfare,
        regime=regime,
        dominant_barrier=dominant,
    )


def run_benchmark_scenarios(seed: int = 42) -> dict[str, dict[str, Any]]:
    """Run the 5 canonical cooperation-barrier & remedy scenarios for CLI/tests."""
    scenarios = {
        "free_rider_baseline": dict(inequality=0.2, misperception=0.2, antisocial_punishment=0.1, legitimate_institution=0.05, positive_reciprocity=0.05, proportional_fairness=False),
        "antisocial_punishment_trap": dict(inequality=0.3, misperception=0.2, antisocial_punishment=0.85, legitimate_institution=0.10, positive_reciprocity=0.15, proportional_fairness=False),
        "unequal_dilemma_no_fairness": dict(inequality=0.90, misperception=0.2, antisocial_punishment=0.10, legitimate_institution=0.30, positive_reciprocity=0.25, proportional_fairness=False),
        "pluralistic_ignorance_drag": dict(inequality=0.20, misperception=0.85, antisocial_punishment=0.10, legitimate_institution=0.35, positive_reciprocity=0.35, proportional_fairness=True),
        "legitimate_polycentric_remedy": dict(inequality=0.65, misperception=0.10, antisocial_punishment=0.30, legitimate_institution=0.85, positive_reciprocity=0.80, proportional_fairness=True),
    }
    out: dict[str, dict[str, Any]] = {}
    for name, params in scenarios.items():
        r = simulate_cooperation_dilemma(seed=seed, **params)
        out[name] = {
            "initial_cooperation": r.initial_cooperation,
            "final_cooperation": r.final_cooperation,
            "mean_cooperation": r.mean_cooperation,
            "final_welfare_index": r.final_welfare_index,
            "regime": r.regime,
            "dominant_barrier": r.dominant_barrier,
        }
    return out


def main() -> int:
    print("Pharos Simulator #10 — Cooperation Barriers & Institutional Remedies (Tier-1 mechanism)")
    for name, info in run_benchmark_scenarios().items():
        print(
            f"  {name:<30} init={info['initial_cooperation']:.2f} -> final={info['final_cooperation']:.2f} "
            f"welfare={info['final_welfare_index']:.2f}  [{info['regime']}]  top_barrier={info['dominant_barrier']}"
        )
    return 0


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