#!/usr/bin/env python3
# SPDX-FileCopyrightText: 2026 Science Against Authoritarianism Contributors
# SPDX-License-Identifier: GPL-3.0-or-later
"""Coupled 4-Layer Society & 2D Tipping Phase Diagram — 11th Tier-1 mechanism simulator.

Couples four interdependent governance layers grounded in Pharos's empirical findings:
  1. M_t — Media & Shared-Truth Integrity (Year-0 early-warning layer; SAA-047, SAA-083, SAA-089)
  2. V_t — Judicial & Electoral Veto Firewall (Year-1 institutional layer; SAA-045, SAA-087, SAA-088)
  3. O_t — Beneficial Ownership & Financial Sunlight (anti-kleptocracy layer; SAA-041, SAA-046, SAA-085)
  4. C_t — Living Commons & Conditional Civic Cooperation (bistable Hill threshold; SAA-013, SAA-066, SAA-068)

Provides:
  - Deterministic 4-layer coupled trajectory simulation (`simulate_coupled_society`)
  - 2D bifurcation phase-diagram grid sweeper (`sweep_phase_diagram`, 15x15 default)
  - One-At-a-Time (OAT) global sensitivity elasticities (`oat_sensitivity`)
  - Four stylized Stage-10 regime-archetype benchmarks (`benchmark_archetypes`)
  - Derived JSON artifact export (`--write-derived`) for interactive portal heatmaps

EPISTEMIC BOUNDARY (T1 mechanism / T4 stylized model — NOT a country forecast):
  Demonstrates coupled feedback loops, Year-0 media precedence, and nonlinear tipping
  boundaries under explicit assumptions. Pure stdlib, deterministic, zero country predictions.
"""
from __future__ import annotations

import argparse
import json
import os
from dataclasses import dataclass
from typing import Any

from pharos import io_utils
from pharos import metadata

_HERE = os.path.dirname(os.path.abspath(__file__))
_ROOT = os.path.normpath(os.path.join(_HERE, "..", "..", ".."))
OUT_JSON = os.path.join(_ROOT, "data", "derived", "coupled_society_phase.json")
REVIEW_REL = "docs/sims/INVERSION_REVIEW_COUPLED_SOCIETY_JSON.json"
REVIEW_DATE = "2026-12-02"

DEFAULT_PARAMS: dict[str, float] = {
    "capture_pressure": 0.42,
    "media_independence": 0.62,
    "veto_firewall": 0.60,
    "ownership_sunlight": 0.55,
    "spyware_surveillance": 0.28,
    "inequality_drag": 0.38,
}

PARAM_LABELS: dict[str, str] = {
    "capture_pressure": "Executive & Oligarchic Capture Pressure",
    "media_independence": "Media & Academic Independence",
    "veto_firewall": "Judicial & Electoral Veto Firewall",
    "ownership_sunlight": "Beneficial Ownership Sunlight",
    "spyware_surveillance": "Digital Spyware & Chilling Pressure",
    "inequality_drag": "Extreme Wealth Inequality Drag",
}


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


def _hill(x: float, theta: float = 0.46, k: int = 4) -> float:
    xc = _clamp01(x)
    xk = xc ** k
    tk = theta ** k
    return xk / (xk + tk) if (xk + tk) > 0.0 else 0.0


@dataclass(frozen=True)
class CoupledSocietyResult:
    trajectory: list[dict[str, float]]
    final_media: float
    final_veto: float
    final_sunlight: float
    final_cooperation: float
    final_health: float
    min_pillar_final: float
    media_dropped_before_veto: bool
    regime: str


def simulate_coupled_society(
    *,
    capture_pressure: float = DEFAULT_PARAMS["capture_pressure"],
    media_independence: float = DEFAULT_PARAMS["media_independence"],
    veto_firewall: float = DEFAULT_PARAMS["veto_firewall"],
    ownership_sunlight: float = DEFAULT_PARAMS["ownership_sunlight"],
    spyware_surveillance: float = DEFAULT_PARAMS["spyware_surveillance"],
    inequality_drag: float = DEFAULT_PARAMS["inequality_drag"],
    initial_state: tuple[float, float, float, float] = (0.68, 0.68, 0.62, 0.65),
    steps: int = 36,
) -> CoupledSocietyResult:
    """Simulate deterministic 4-layer coupled institutional-information-opacity-commons dynamics."""
    for name, val in (
        ("capture_pressure", capture_pressure),
        ("media_independence", media_independence),
        ("veto_firewall", veto_firewall),
        ("ownership_sunlight", ownership_sunlight),
        ("spyware_surveillance", spyware_surveillance),
        ("inequality_drag", inequality_drag),
    ):
        if not (0.0 <= val <= 1.0):
            raise ValueError(f"{name} must lie in [0, 1], got {val}")
    if steps < 1:
        raise ValueError(f"steps must be >= 1, got {steps}")

    m, v, o, c = (_clamp01(x) for x in initial_state)
    traj: list[dict[str, float]] = []
    m_half_step: int | None = None
    v_half_step: int | None = None
    m0, v0 = m, v

    for t in range(steps + 1):
        health = 0.25 * (m + v + o + c)
        traj.append({
            "step": float(t),
            "media": round(m, 4),
            "veto": round(v, 4),
            "sunlight": round(o, 4),
            "cooperation": round(c, 4),
            "health": round(health, 4),
        })
        if m_half_step is None and (m0 - m) >= 0.10:
            m_half_step = t
        if v_half_step is None and (v0 - v) >= 0.10:
            v_half_step = t
        if t == steps:
            break

        # Effective covert patronage is damped by beneficial-ownership sunlight O_t
        p_cov = capture_pressure * (1.0 - 0.58 * o)

        # Layer 1: Media & Shared-Truth Integrity (fastest dynamics — Year-0 indicator)
        m_star = _clamp01(
            0.34
            + 0.42 * media_independence
            + 0.16 * v
            + 0.12 * o
            + 0.08 * c
            - 0.30 * p_cov
            - 0.28 * spyware_surveillance
        )

        # Layer 2: Judicial & Electoral Veto Firewall (Year-1 institutional lag)
        v_star = _clamp01(
            0.28
            + 0.44 * veto_firewall
            + 0.20 * m
            + 0.14 * o
            + 0.10 * c
            - 0.34 * p_cov
            - 0.14 * inequality_drag
        )

        # Layer 3: Beneficial Ownership & Financial Sunlight
        o_star = _clamp01(
            0.26
            + 0.46 * ownership_sunlight
            + 0.18 * v
            + 0.16 * m
            - 0.32 * capture_pressure * (1.0 - 0.45 * v)
            - 0.12 * inequality_drag
        )

        # Layer 4: Living Commons & Conditional Cooperation (bistable Hill threshold)
        legitimacy = 0.40 * v + 0.35 * m + 0.25 * o
        reciprocity = _hill(0.50 * c + 0.50 * legitimacy, theta=0.52, k=5)
        c_star = _clamp01(
            0.22
            + 0.48 * reciprocity
            + 0.24 * legitimacy
            - 0.22 * inequality_drag
            - 0.18 * spyware_surveillance * (1.0 - 0.35 * m)
        )

        m = _clamp01(m + 0.32 * (m_star - m))
        v = _clamp01(v + 0.20 * (v_star - v))
        o = _clamp01(o + 0.18 * (o_star - o))
        c = _clamp01(c + 0.22 * (c_star - c))

    final_health = 0.25 * (m + v + o + c)
    min_pillar = min(m, v, o, c)
    if final_health >= 0.65 and min(m, v, c) >= 0.55:
        regime = "RESILIENT_OPEN"
    elif final_health >= 0.42:
        regime = "CONTESTED_HYBRID"
    else:
        regime = "CAPTURED_AUTOCRACY"

    media_led = (
        m_half_step is not None
        and (v_half_step is None or m_half_step <= v_half_step)
    )

    return CoupledSocietyResult(
        trajectory=traj,
        final_media=round(m, 4),
        final_veto=round(v, 4),
        final_sunlight=round(o, 4),
        final_cooperation=round(c, 4),
        final_health=round(final_health, 4),
        min_pillar_final=round(min_pillar, 4),
        media_dropped_before_veto=media_led,
        regime=regime,
    )


def sweep_phase_diagram(
    x_param: str,
    y_param: str,
    *,
    base_params: dict[str, float] | None = None,
    grid_size: int = 15,
    x_range: tuple[float, float] = (0.05, 0.95),
    y_range: tuple[float, float] = (0.05, 0.95),
    steps: int = 36,
) -> dict[str, Any]:
    """Evaluate a deterministic 2D grid mapping tipping boundaries across (x_param, y_param)."""
    if x_param not in DEFAULT_PARAMS or y_param not in DEFAULT_PARAMS:
        raise ValueError(f"Unknown parameter in sweep: ({x_param}, {y_param})")
    if grid_size < 3:
        raise ValueError(f"grid_size must be >= 3, got {grid_size}")

    base = dict(DEFAULT_PARAMS)
    if base_params:
        base.update(base_params)

    xs = [
        round(x_range[0] + (x_range[1] - x_range[0]) * i / (grid_size - 1), 3)
        for i in range(grid_size)
    ]
    ys = [
        round(y_range[0] + (y_range[1] - y_range[0]) * j / (grid_size - 1), 3)
        for j in range(grid_size)
    ]

    health_grid: list[list[float]] = []
    regime_grid: list[list[str]] = []
    counts = {"RESILIENT_OPEN": 0, "CONTESTED_HYBRID": 0, "CAPTURED_AUTOCRACY": 0}

    for yv in ys:
        h_row: list[float] = []
        r_row: list[str] = []
        for xv in xs:
            kw = dict(base)
            kw[x_param] = xv
            kw[y_param] = yv
            res = simulate_coupled_society(**kw, steps=steps)
            h_row.append(res.final_health)
            r_row.append(res.regime)
            counts[res.regime] += 1
        health_grid.append(h_row)
        regime_grid.append(r_row)

    total_cells = grid_size * grid_size
    return {
        "x_param": x_param,
        "x_label": PARAM_LABELS[x_param],
        "y_param": y_param,
        "y_label": PARAM_LABELS[y_param],
        "fixed_params": {k: v for k, v in base.items() if k not in (x_param, y_param)},
        "grid_size": grid_size,
        "x_values": xs,
        "y_values": ys,
        "health_grid": health_grid,
        "regime_grid": regime_grid,
        "regime_counts": counts,
        "resilient_share_pct": round(100.0 * counts["RESILIENT_OPEN"] / total_cells, 1),
        "captured_share_pct": round(100.0 * counts["CAPTURED_AUTOCRACY"] / total_cells, 1),
    }


def oat_sensitivity(
    *,
    baseline: dict[str, float] | None = None,
    delta: float = 0.15,
    steps: int = 36,
) -> list[dict[str, Any]]:
    """One-At-a-Time (OAT) global sensitivity analysis around a contested baseline."""
    base = {
        "capture_pressure": 0.55,
        "media_independence": 0.55,
        "veto_firewall": 0.55,
        "ownership_sunlight": 0.50,
        "spyware_surveillance": 0.35,
        "inequality_drag": 0.45,
    }
    if baseline:
        base.update(baseline)

    base_res = simulate_coupled_society(**base, steps=steps)
    rows: list[dict[str, Any]] = []
    abs_total = 0.0

    for key in DEFAULT_PARAMS:
        hi_kw = dict(base)
        lo_kw = dict(base)
        hi_kw[key] = _clamp01(base[key] + delta)
        lo_kw[key] = _clamp01(base[key] - delta)
        r_hi = simulate_coupled_society(**hi_kw, steps=steps)
        r_lo = simulate_coupled_society(**lo_kw, steps=steps)
        signed_swing = r_hi.final_health - r_lo.final_health
        abs_total += abs(signed_swing)
        rows.append({
            "parameter": key,
            "label": PARAM_LABELS[key],
            "baseline_value": base[key],
            "health_at_minus": r_lo.final_health,
            "health_at_baseline": base_res.final_health,
            "health_at_plus": r_hi.final_health,
            "signed_delta_health": round(signed_swing, 4),
            "abs_swing": round(abs(signed_swing), 4),
            "direction": "PROTECTIVE" if signed_swing > 0 else "EROSIVE",
        })

    for r in rows:
        r["sensitivity_share_pct"] = (
            round(100.0 * r["abs_swing"] / abs_total, 1) if abs_total > 1e-12 else 0.0
        )
    rows.sort(key=lambda r: r["abs_swing"], reverse=True)
    return rows


def benchmark_archetypes(*, steps: int = 36) -> list[dict[str, Any]]:
    """Run four stylized Stage-10 structural archetypes verifying nonlinear feedback properties."""
    specs = (
        (
            "open_high_sunlight",
            "Resilient Open Democracy (High Firewall + Sunlight)",
            {"capture_pressure": 0.25, "media_independence": 0.85, "veto_firewall": 0.85, "ownership_sunlight": 0.80, "spyware_surveillance": 0.12, "inequality_drag": 0.25},
            (0.78, 0.80, 0.75, 0.75),
            "RESILIENT_OPEN",
        ),
        (
            "captured_media_tipping",
            "Media-First Capture Cascade (Year-0 Press Erosion -> Veto Collapse)",
            {"capture_pressure": 0.82, "media_independence": 0.18, "veto_firewall": 0.35, "ownership_sunlight": 0.20, "spyware_surveillance": 0.78, "inequality_drag": 0.62},
            (0.68, 0.68, 0.60, 0.64),
            "CAPTURED_AUTOCRACY",
        ),
        (
            "oligarchic_opacity_trap",
            "Oligarchic Opacity & Inequality Trap (Shell Secrecy Lock-In)",
            {"capture_pressure": 0.72, "media_independence": 0.42, "veto_firewall": 0.45, "ownership_sunlight": 0.15, "spyware_surveillance": 0.42, "inequality_drag": 0.82},
            (0.58, 0.60, 0.45, 0.55),
            "CAPTURED_AUTOCRACY",
        ),
        (
            "polycentric_uturn_recovery",
            "Post-Backsliding Democratic U-Turn (Media + Veto + Sunlight Reform)",
            {"capture_pressure": 0.28, "media_independence": 0.84, "veto_firewall": 0.82, "ownership_sunlight": 0.78, "spyware_surveillance": 0.15, "inequality_drag": 0.30},
            (0.32, 0.35, 0.30, 0.38),
            "RESILIENT_OPEN",
        ),
    )
    out: list[dict[str, Any]] = []
    for aid, label, params, init_state, expected_regime in specs:
        res = simulate_coupled_society(**params, initial_state=init_state, steps=steps)
        out.append({
            "id": aid,
            "label": label,
            "params": params,
            "initial_state": {
                "media": init_state[0],
                "veto": init_state[1],
                "sunlight": init_state[2],
                "cooperation": init_state[3],
            },
            "expected_regime": expected_regime,
            "observed_regime": res.regime,
            "matches_expected": res.regime == expected_regime,
            "final_media": res.final_media,
            "final_veto": res.final_veto,
            "final_sunlight": res.final_sunlight,
            "final_cooperation": res.final_cooperation,
            "final_health": res.final_health,
            "media_dropped_before_veto": res.media_dropped_before_veto,
            "trajectory": res.trajectory,
        })
    return out


def build_derived_payload() -> dict[str, Any]:
    """Generate deterministic 2D phase-diagram grids, OAT sensitivity, and archetype trajectories."""
    sweep_firewall_sunlight = sweep_phase_diagram(
        "veto_firewall",
        "ownership_sunlight",
        base_params={
            "capture_pressure": 0.52,
            "media_independence": 0.62,
            "spyware_surveillance": 0.28,
            "inequality_drag": 0.38,
        },
        grid_size=15,
    )
    sweep_media_spyware = sweep_phase_diagram(
        "media_independence",
        "spyware_surveillance",
        base_params={
            "capture_pressure": 0.48,
            "veto_firewall": 0.62,
            "ownership_sunlight": 0.58,
            "inequality_drag": 0.35,
        },
        grid_size=15,
    )
    sens = oat_sensitivity()
    archetypes = benchmark_archetypes()
    return {
        "schema_version": "pharos-coupled-society-v2",
        "simulator": "sim_coupled_society",
        "epistemic_tier": "Tier-1 validated mechanism / Tier-4 stylized coupled model (NOT a country forecast)",
        "default_params": DEFAULT_PARAMS,
        "phase_diagrams": {
            "firewall_vs_sunlight": sweep_firewall_sunlight,
            "media_vs_spyware": sweep_media_spyware,
        },
        "oat_sensitivity": sens,
        "archetypes": archetypes,
        "ethical_note": "Pure stylized institutional mechanism simulator — zero real-country predictions and zero sub-national records (THREAT_MODEL.md).",
    }


def write_derived_artifact() -> dict[str, Any]:
    payload = build_derived_payload()
    io_utils.atomic_write_text(OUT_JSON, json.dumps(payload, indent=2) + "\n")

    rev = {
        "review_id": "IR-PHAROS-COUPLED-SOCIETY-JSON-20261202",
        "reviewed_date": REVIEW_DATE,
        "approved_artifact": "data/derived/coupled_society_phase.json",
        "schema_sha256": metadata.artifact_schema_sha256(OUT_JSON),
        "inversion_assessment": (
            "Pure stylized mathematical 4-layer phase diagram sweeps, OAT parameter sensitivities, and synthetic "
            "archetype trajectories; contains zero real-country forecasts and zero sub-national records."
        ),
    }
    io_utils.atomic_write_text(os.path.join(_ROOT, REVIEW_REL), json.dumps(rev, indent=2) + "\n")

    metadata.write_sidecar(
        OUT_JSON,
        output_type="analysis",
        sensitivity_tier="low",
        access_tier="public",
        inversion_red_team_date=REVIEW_DATE,
        description="Coupled 4-Layer Society simulator v2: 15x15 tipping phase diagrams, OAT global sensitivity & stylized archetype validation.",
        inversion_review_id="IR-PHAROS-COUPLED-SOCIETY-JSON-20261202",
        inversion_review_record=REVIEW_REL,
        license_scope="Original Pharos stylized mathematical simulation output: CC0-1.0.",
        upstream_sources=[{
            "provider": "Science Against Authoritarianism Contributors (Pharos Project)",
            "dataset": "Deterministic 4-Layer Coupled Institutional-Information-Opacity-Commons Equations (src/pharos/sims/sim_coupled_society.py)",
            "citation": "Science Against Authoritarianism Contributors (2026), Tier-1 Mechanism Simulator #11.",
            "terms_url": "https://pharos-observatory.pages.dev",
        }],
        reuse_note="Stylized Tier-1/Tier-4 mechanism phase portraits only — never interpret as a real-country prediction.",
    )
    return payload


def main(argv: list[str] | None = None) -> int:
    ap = argparse.ArgumentParser(description="Coupled 4-Layer Institutional-Information-Opacity-Commons Simulator")
    ap.add_argument("--write-derived", action="store_true", help="write data/derived/coupled_society_phase.json + sidecar")
    args = ap.parse_args(argv)

    if args.write_derived:
        payload = write_derived_artifact()
        fs = payload["phase_diagrams"]["firewall_vs_sunlight"]
        ms = payload["phase_diagrams"]["media_vs_spyware"]
        print(
            f"sim_coupled_society derived written: firewall×sunlight ({fs['resilient_share_pct']}% open / "
            f"{fs['captured_share_pct']}% captured), media×spyware ({ms['resilient_share_pct']}% open / "
            f"{ms['captured_share_pct']}% captured), top lever={payload['oat_sensitivity'][0]['parameter']}"
        )
        return 0

    for row in benchmark_archetypes():
        print(
            f"  {row['id']:28s} -> {row['observed_regime']:18s} "
            f"(H={row['final_health']:.3f}, M={row['final_media']:.2f}, V={row['final_veto']:.2f}, "
            f"O={row['final_sunlight']:.2f}, C={row['final_cooperation']:.2f}, M_led={row['media_dropped_before_veto']})"
        )
    return 0


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