#!/usr/bin/env python3
# SPDX-FileCopyrightText: 2026 Science Against Authoritarianism Contributors
# SPDX-License-Identifier: GPL-3.0-or-later
"""Tier-1 Mechanism Simulator: Ostrom Commons, Fairness, Positive Reciprocity & Nature Regeneration.

Models a coupled social-ecological mechanism grounded in:
  - Elinor Ostrom (1990) local self-governance of shared commons (SAA-013);
  - Blackman et al. (2017, PNAS) & Dawson et al. (2021) equitable community
    forest/ecosystem stewardship (SAA-057);
  - Rand et al. (2009, Science) positive reward sustaining public cooperation
    without destructive retaliation (SAA-059);
  - Otto et al. (2020, PNAS) / Lenton et al. (2022) positive social tipping
    dynamics (SAA-058).

Mechanism:
  A community shares a renewable living ecosystem (forest, watershed, fishery)
  with health N_t in [0, 1] and cooperating-steward share C_t in [0, 1].
    - Sustainable cooperators harvest at e_coop = 0.07.
    - Unrestrained extractors harvest at e_def = 0.34 - 0.14 * fairness.
    - Ecosystem health evolves via logistic regeneration (r = 0.36):
        N_{t+1} = clamp(N_t + r * N_t * (1 - N_t) - E_t * N_t, 0, 1)
      where E_t = C_t * e_coop + (1 - C_t) * e_def.
    - Cooperation evolves via replicator dynamics driven by fairness (f),
      positive cooperation rewards/compassion norms (b), and ecosystem vitality:
        delta_u = 0.65 * f + 0.55 * b + 0.35 * N_t - 0.68
        C_{t+1} = clamp(C_t + 0.45 * C_t * (1 - C_t) * delta_u, 0, 1)
    - Shared wellbeing W_t = 0.45 * N_t + 0.35 * C_t + 0.20 * f.

Analytical equilibria:
  - Unfair / low-cooperation regime (f, b small): delta_u < 0 -> C_t -> 0,
    driving N_t toward collapse (N* ≈ 1 - 0.34/0.36 ≈ 0.056 when f = 0).
  - Fair / positive-reciprocity regime (f, b high): delta_u > 0 -> C_t -> 1,
    driving N_t toward sustainable abundance (N* = 1 - 0.07/0.36 ≈ 0.806).

EPISTEMIC BOUNDARY (T1 mechanism / T4 stylized model — NOT a real-world forecast):
  Demonstrates the mathematical tipping bifurcation between extractive collapse
  and equitable commons regeneration. Pure stdlib, deterministic.
"""
from __future__ import annotations

from typing import Any

R_REGEN = 0.36
E_COOP = 0.07
E_DEF_BASE = 0.34
E_DEF_FAIR_REDUCTION = 0.14
REPLICATOR_SPEED = 0.45


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


def sustainable_carrying_equilibrium() -> float:
    """Analytical steady-state nature health when C -> 1 (all stewards harvest sustainably)."""
    return _clamp01(1.0 - E_COOP / R_REGEN)


def extractive_collapse_equilibrium(fairness: float = 0.0) -> float:
    """Analytical steady-state nature health when C -> 0 at a given fairness rule level."""
    if not (0.0 <= fairness <= 1.0):
        raise ValueError(f"fairness must lie in [0, 1], got {fairness}")
    e_def = E_DEF_BASE - E_DEF_FAIR_REDUCTION * fairness
    return _clamp01(1.0 - e_def / R_REGEN)


def simulate_commons_trajectory(
    *,
    fairness: float,
    encouragement: float,
    initial_coop: float = 0.40,
    initial_nature: float = 0.45,
    years: int = 30,
) -> dict[str, Any]:
    """Run deterministic coupled commons + cooperation + nature regeneration trajectory."""
    for name, val in (
        ("fairness", fairness),
        ("encouragement", encouragement),
        ("initial_coop", initial_coop),
        ("initial_nature", initial_nature),
    ):
        if not (0.0 <= val <= 1.0):
            raise ValueError(f"{name} must lie in [0, 1], got {val}")
    if years < 1:
        raise ValueError(f"years must be >= 1, got {years}")

    n_val = initial_nature
    c_val = initial_coop
    series: list[dict[str, float | int]] = []
    tipping_year: int | None = None

    for t in range(years + 1):
        wellbeing = _clamp01(0.45 * n_val + 0.35 * c_val + 0.20 * fairness)
        series.append({
            "year": t,
            "nature": round(n_val, 6),
            "cooperation": round(c_val, 6),
            "wellbeing": round(wellbeing, 6),
        })
        if tipping_year is None and c_val >= 0.70 and n_val >= 0.65:
            tipping_year = t
        if t == years:
            break

        e_def = E_DEF_BASE - E_DEF_FAIR_REDUCTION * fairness
        extraction = c_val * E_COOP + (1.0 - c_val) * e_def
        next_n = _clamp01(n_val + R_REGEN * n_val * (1.0 - n_val) - extraction * n_val)
        delta_u = 0.65 * fairness + 0.55 * encouragement + 0.35 * n_val - 0.68
        next_c = _clamp01(c_val + REPLICATOR_SPEED * c_val * (1.0 - c_val) * delta_u)
        n_val, c_val = next_n, next_c

    final = series[-1]
    if final["nature"] >= 0.65 and final["cooperation"] >= 0.70:
        regime = "THRIVING"
    elif final["nature"] <= 0.25 or final["cooperation"] <= 0.20:
        regime = "DEPLETED"
    else:
        regime = "FRAGILE"

    return {
        "fairness": fairness,
        "encouragement": encouragement,
        "initial_coop": initial_coop,
        "initial_nature": initial_nature,
        "years": years,
        "final_nature": final["nature"],
        "final_cooperation": final["cooperation"],
        "final_wellbeing": final["wellbeing"],
        "tipping_year": tipping_year,
        "regime": regime,
        "sustainable_equilibrium": round(sustainable_carrying_equilibrium(), 6),
        "series": series,
    }


def main() -> int:
    print("Commons, Fairness & Nature Stewardship Simulator (T1 mechanism / T4 stylized model)")
    for label, f, b in (
        ("Unfair / fear-based (tragedy)", 0.15, 0.15),
        ("Mixed / fragile transition", 0.45, 0.45),
        ("Fair local voice + positive cooperation", 0.75, 0.70),
    ):
        res = simulate_commons_trajectory(fairness=f, encouragement=b)
        print(
            f"  {label:<40} -> nature={res['final_nature']*100:5.1f}%  "
            f"coop={res['final_cooperation']*100:5.1f}%  "
            f"wellbeing={res['final_wellbeing']*100:5.1f}%  [{res['regime']}]"
        )
    return 0


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