#!/usr/bin/env python3
"""
Quantitative Econometric & Lifecycle Analysis of the Path of Exile 1 Economy (3.12-3.30).

Reads processed datasets from data/processed/:
  - economy_panel.csv
  - player_factors.csv
  - league_events.csv

Outputs clean CSV summary/regression tables to outputs/tables/ and
publication-quality PNG figures to outputs/figures/.
"""

from __future__ import annotations

import itertools
import warnings
from pathlib import Path

import matplotlib
matplotlib.use("Agg")
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import seaborn as sns
import statsmodels.api as sm
import statsmodels.formula.api as smf
from scipy import stats
from sklearn.ensemble import RandomForestRegressor
from sklearn.inspection import permutation_importance
from sklearn.metrics import r2_score
from sklearn.model_selection import GroupKFold, KFold

warnings.filterwarnings("ignore", category=FutureWarning)

ROOT = Path("/Users/alotofblahaj/.gemini/antigravity/scratch/poe1-economy-quant")
DATA_DIR = ROOT / "data" / "processed"
TABLE_DIR = ROOT / "outputs" / "tables"
FIG_DIR = ROOT / "outputs" / "figures"

TABLE_DIR.mkdir(parents=True, exist_ok=True)
FIG_DIR.mkdir(parents=True, exist_ok=True)

# Clean publication styling
plt.rcParams.update({
    "figure.dpi": 180,
    "savefig.dpi": 220,
    "font.family": "DejaVu Sans",
    "axes.spines.top": False,
    "axes.spines.right": False,
    "axes.grid": True,
    "grid.alpha": 0.25,
    "grid.linestyle": "--",
    "axes.titlesize": 11,
    "axes.labelsize": 10,
    "xtick.labelsize": 8.5,
    "ytick.labelsize": 8.5,
    "legend.fontsize": 8.2,
})

PARITY_PAIRS = [
    ("House of Mirrors", "Mirror of Kalandra", 9, "HoM x9 / Mirror"),
    ("The Apothecary", "Mageblood", 5, "Apothecary x5 / Mageblood"),
    ("The Doctor", "Headhunter", 8, "Doctor x8 / Headhunter"),
    ("Seven Years Bad Luck", "Mirror Shard", 13, "SYBL x13 / Mirror Shard"),
]

KEY_CARDS = [
    "House of Mirrors",
    "The Apothecary",
    "The Doctor",
    "Seven Years Bad Luck",
    "The Fortunate",
    "Brother's Gift",
    "Divine Beauty",
    "The Sephirot",
    "The Immortal",
    "The Nurse",
]


def load_data() -> tuple[pd.DataFrame, pd.DataFrame, pd.DataFrame]:
    econ = pd.read_csv(DATA_DIR / "economy_panel.csv", dtype={"patch_version": str})
    pf = pd.read_csv(DATA_DIR / "player_factors.csv", dtype={"patch_version": str})
    ev = pd.read_csv(DATA_DIR / "league_events.csv", dtype={"patch_version": str})

    for df in (econ, pf):
        df["league_day"] = df["league_day"].astype(int)
    econ["chaos_value"] = pd.to_numeric(econ["chaos_value"], errors="coerce")
    econ["divine_value"] = pd.to_numeric(econ["divine_value"], errors="coerce")

    # Sort events chronologically by launch_date
    ev["patch_num"] = ev["patch_version"].apply(
        lambda s: int(s.split(".")[0]) * 100 + int(s.split(".")[1])
    )
    ev = ev.sort_values("patch_num").reset_index(drop=True)
    return econ, pf, ev


def build_wide_daily_panel(
    econ: pd.DataFrame, pf: pd.DataFrame, ev: pd.DataFrame
) -> pd.DataFrame:
    """Build a league-date panel with wide prices for currencies, cards, uniques,
    merged with player_factors and league_events."""
    chaos_wide = econ.pivot_table(
        index=["league_name", "patch_version", "date", "league_day"],
        columns="item_name",
        values="chaos_value",
        aggfunc="first",
    )
    chaos_wide.columns = [f"{c}__chaos" for c in chaos_wide.columns]

    div_wide = econ.pivot_table(
        index=["league_name", "patch_version", "date", "league_day"],
        columns="item_name",
        values="divine_value",
        aggfunc="first",
    )
    div_wide.columns = [f"{c}__div" for c in div_wide.columns]

    wide = pd.concat([chaos_wide, div_wide], axis=1).reset_index()

    # Merge player_factors (left join keeps Settlers days > 90 for full-econ checks)
    wide = wide.merge(
        pf[
            [
                "league_name",
                "patch_version",
                "date",
                "league_day",
                "peak_players",
                "avg_players",
                "day0_peak",
                "retention_rate",
                "log_players",
                "is_weekend",
            ]
        ],
        on=["league_name", "patch_version", "date", "league_day"],
        how="left",
    )

    # Merge league_events
    wide = wide.merge(
        ev[
            [
                "league_name",
                "patch_version",
                "patch_num",
                "launch_date",
                "end_date",
                "league_duration_days",
                "post_319_divine_swap",
                "currency_exchange_faustus",
                "magic_find_inflation",
                "poe2_ea_overlap",
            ]
        ],
        on=["league_name", "patch_version"],
        how="left",
    )

    # Exact daily PoE 2 Early Access indicator (Dec 6, 2024+)
    wide["poe2_ea_active"] = (wide["date"] >= "2024-12-06").astype(int)
    wide["log1p_day"] = np.log1p(wide["league_day"])
    wide["log1p_day_sq"] = wide["log1p_day"] ** 2
    wide["log_day0_peak"] = np.log(wide["day0_peak"])
    wide["has_player_data"] = wide["peak_players"].notna().astype(int)

    # Regime labels
    def assign_regime(row: pd.Series) -> str:
        if row["post_319_divine_swap"] == 0:
            return "pre_319"
        if row["magic_find_inflation"] == 1:
            return "post_319_mf_323"
        if row["currency_exchange_faustus"] == 1:
            return "faustus_325_plus"
        return "post_319_pre_faustus"

    wide["regime"] = wide.apply(assign_regime, axis=1)
    wide = wide.sort_values(["patch_num", "league_day"]).reset_index(drop=True)
    return wide


def compute_coverage_summary(
    econ: pd.DataFrame, pf: pd.DataFrame, ev: pd.DataFrame, wide: pd.DataFrame
) -> pd.DataFrame:
    rows = []
    econ_leagues = ev[ev["league_name"].isin(econ["league_name"].unique())].copy()
    for _, erow in econ_leagues.iterrows():
        lg = erow["league_name"]
        sub_e = econ[econ["league_name"] == lg]
        sub_w = wide[wide["league_name"] == lg]
        sub_p = pf[pf["league_name"] == lg]

        div_s = sub_w["Divine Orb__chaos"].dropna()
        exa_s = sub_w["Exalted Orb__chaos"].dropna()
        mir_c = sub_w["Mirror of Kalandra__chaos"].dropna()
        mir_d = sub_w["Mirror of Kalandra__div"].dropna()
        hom_d = sub_w["House of Mirrors__div"].dropna()

        rows.append({
            "patch_version": erow["patch_version"],
            "league_name": lg,
            "launch_date": erow["launch_date"],
            "end_date": erow["end_date"] if pd.notna(erow["end_date"]) else "ongoing",
            "econ_rows": len(sub_e),
            "econ_days": int(sub_w["date"].nunique()),
            "min_league_day": int(sub_w["league_day"].min()),
            "max_league_day": int(sub_w["league_day"].max()),
            "player_days": int(len(sub_p)),
            "matched_player_days": int(sub_w["has_player_data"].sum()),
            "day0_peak_players": int(sub_p["day0_peak"].iloc[0]) if len(sub_p) else np.nan,
            "day30_retention": round(
                float(sub_p.loc[sub_p["league_day"] == 30, "retention_rate"].iloc[0]), 4
            ) if (sub_p["league_day"] == 30).any() else np.nan,
            "divine_days": int(len(div_s)),
            "mirror_chaos_days": int(len(mir_c)),
            "mirror_divine_days": int(len(mir_d)),
            "hom_divine_days": int(len(hom_d)),
            "median_divine_chaos": round(float(div_s.median()), 2) if len(div_s) else np.nan,
            "median_exalt_chaos": round(float(exa_s.median()), 2) if len(exa_s) else np.nan,
            "median_mirror_chaos": round(float(mir_c.median()), 2) if len(mir_c) else np.nan,
            "median_mirror_divine": round(float(mir_d.median()), 2) if len(mir_d) else np.nan,
            "median_hom_divine": round(float(hom_d.median()), 2) if len(hom_d) else np.nan,
            "post_319_divine_swap": int(erow["post_319_divine_swap"]),
            "currency_exchange_faustus": int(erow["currency_exchange_faustus"]),
            "magic_find_inflation": int(erow["magic_find_inflation"]),
            "poe2_ea_overlap": int(erow["poe2_ea_overlap"]),
        })
    df = pd.DataFrame(rows)
    df.to_csv(TABLE_DIR / "01_coverage_summary.csv", index=False)
    return df


def compute_lifecycle_trajectories(wide: pd.DataFrame) -> tuple[pd.DataFrame, pd.DataFrame]:
    """Compute cross-league trajectories by league_day (0..90) and early vs late inflation."""
    sub90 = wide[wide["league_day"] <= 90].copy()

    # Define regime groupings
    regime_masks = {
        "all_post_319": sub90["post_319_divine_swap"] == 1,
        "pre_319": sub90["post_319_divine_swap"] == 0,
        "post_319_pre_faustus": (sub90["post_319_divine_swap"] == 1) & (sub90["currency_exchange_faustus"] == 0),
        "faustus_325_plus": sub90["currency_exchange_faustus"] == 1,
    }

    series_specs = [
        ("Divine Orb", "chaos", "Divine Orb__chaos"),
        ("Exalted Orb", "chaos", "Exalted Orb__chaos"),
        ("Mirror of Kalandra", "chaos", "Mirror of Kalandra__chaos"),
        ("Mirror of Kalandra", "divine", "Mirror of Kalandra__div"),
        ("Mageblood", "divine", "Mageblood__div"),
        ("Headhunter", "divine", "Headhunter__div"),
    ]
    for card in KEY_CARDS:
        series_specs.append((card, "chaos", f"{card}__chaos"))
        series_specs.append((card, "divine", f"{card}__div"))

    traj_rows = []
    for reg_name, mask in regime_masks.items():
        df_reg = sub90[mask]
        for item_name, unit, col in series_specs:
            if col not in df_reg.columns:
                continue
            valid = df_reg[["league_day", "league_name", col]].dropna()
            if valid.empty:
                continue
            grp = valid.groupby("league_day")[col]
            stats_df = grp.agg(
                n_leagues="count",
                median="median",
                q25=lambda s: float(np.percentile(s, 25)),
                q75=lambda s: float(np.percentile(s, 75)),
                mean="mean",
                min="min",
                max="max",
            ).reset_index()
            stats_df["iqr"] = stats_df["q75"] - stats_df["q25"]
            stats_df["regime"] = reg_name
            stats_df["item_name"] = item_name
            stats_df["unit"] = unit
            traj_rows.append(stats_df)

    traj_df = pd.concat(traj_rows, ignore_index=True)[
        [
            "regime", "item_name", "unit", "league_day",
            "n_leagues", "median", "q25", "q75", "iqr", "mean", "min", "max",
        ]
    ]
    traj_df.to_csv(TABLE_DIR / "02_lifecycle_trajectories.csv", index=False)

    # Early (days 1..7) vs Mid (days 22..35) vs Late (days 60..90) inflation per league
    infl_rows = []
    core_cols = [
        ("Divine Orb", "chaos", "Divine Orb__chaos"),
        ("Exalted Orb", "chaos", "Exalted Orb__chaos"),
        ("Mirror of Kalandra", "chaos", "Mirror of Kalandra__chaos"),
        ("Mirror of Kalandra", "divine", "Mirror of Kalandra__div"),
        ("House of Mirrors", "divine", "House of Mirrors__div"),
        ("House of Mirrors", "chaos", "House of Mirrors__chaos"),
        ("The Apothecary", "divine", "The Apothecary__div"),
        ("The Doctor", "divine", "The Doctor__div"),
        ("Seven Years Bad Luck", "divine", "Seven Years Bad Luck__div"),
        ("The Fortunate", "divine", "The Fortunate__div"),
        ("Brother's Gift", "divine", "Brother's Gift__div"),
        ("Mageblood", "divine", "Mageblood__div"),
        ("Headhunter", "divine", "Headhunter__div"),
    ]
    for (patch_ver, lg), g in wide.groupby(["patch_version", "league_name"], sort=False):
        for item_name, unit, col in core_cols:
            if col not in g.columns:
                continue
            s = g[["league_day", col]].dropna()
            if len(s) < 5:
                continue
            early = s[(s["league_day"] >= 1) & (s["league_day"] <= 7)][col]
            mid = s[(s["league_day"] >= 22) & (s["league_day"] <= 35)][col]
            late = s[(s["league_day"] >= 60) & (s["league_day"] <= 90)][col]
            # Exclude day 0/1 extreme single-day listing spike for peak tracking when day>=2 exists
            s_peak = s[s["league_day"] >= 2] if (s["league_day"] >= 2).any() else s
            peak_idx = s_peak[col].idxmax()

            e_med = float(early.median()) if len(early) else np.nan
            m_med = float(mid.median()) if len(mid) else np.nan
            l_med = float(late.median()) if len(late) else np.nan

            infl_rows.append({
                "patch_version": patch_ver,
                "league_name": lg,
                "item_name": item_name,
                "unit": unit,
                "n_days_total": int(len(s)),
                "early_d1_7_median": round(e_med, 4) if pd.notna(e_med) else np.nan,
                "mid_d22_35_median": round(m_med, 4) if pd.notna(m_med) else np.nan,
                "late_d60_90_median": round(l_med, 4) if pd.notna(l_med) else np.nan,
                "mid_to_early_ratio": round(m_med / e_med, 4) if (pd.notna(e_med) and pd.notna(m_med) and e_med > 0) else np.nan,
                "late_to_early_ratio": round(l_med / e_med, 4) if (pd.notna(e_med) and pd.notna(l_med) and e_med > 0) else np.nan,
                "pct_change_early_to_late": round((l_med / e_med - 1.0) * 100.0, 2) if (pd.notna(e_med) and pd.notna(l_med) and e_med > 0) else np.nan,
                "peak_day_d2plus": int(s_peak.loc[peak_idx, "league_day"]),
                "peak_value_d2plus": round(float(s_peak.loc[peak_idx, col]), 4),
            })

    infl_df = pd.DataFrame(infl_rows)
    infl_df.to_csv(TABLE_DIR / "02b_early_vs_late_inflation.csv", index=False)
    return traj_df, infl_df


def _extract_model_rows(
    fit,
    dep_var: str,
    sample_name: str,
    spec_name: str,
    se_type: str,
    keep_terms: list[str] | None = None,
    extra_r2: float | None = None,
) -> list[dict]:
    rows = []
    params = fit.params
    bse = fit.bse
    tvals = fit.tvalues
    pvals = fit.pvalues
    ci = fit.conf_int()
    r2_val = extra_r2 if extra_r2 is not None else float(fit.rsquared)
    for term in params.index:
        if term.startswith("C(league_name)"):
            continue
        if keep_terms is not None and term not in keep_terms:
            continue
        rows.append({
            "dep_var": dep_var,
            "sample": sample_name,
            "spec": spec_name,
            "se_type": se_type,
            "term": term,
            "coef": float(params[term]),
            "se": float(bse[term]),
            "t_stat": float(tvals[term]),
            "p_value": float(pvals[term]),
            "ci_low_95": float(ci.loc[term, 0]),
            "ci_high_95": float(ci.loc[term, 1]),
            "n_obs": int(fit.nobs),
            "r2": float(r2_val),
            "adj_r2": float(fit.rsquared_adj),
        })
    return rows


def run_panel_econometrics(wide: pd.DataFrame) -> pd.DataFrame:
    """Estimate League FE (log-levels, splines, interactions, first-differences) and
    Pooled Regime regressions with League-Clustered & Newey-West HAC standard errors."""
    reg_rows = []

    targets = [
        ("ln_divine_chaos", "Divine Orb__chaos", "post_319", wide["post_319_divine_swap"] == 1),
        ("ln_divine_chaos", "Divine Orb__chaos", "all_leagues", pd.Series(True, index=wide.index)),
        ("ln_exalt_chaos", "Exalted Orb__chaos", "pre_319", wide["post_319_divine_swap"] == 0),
        ("ln_mirror_divine", "Mirror of Kalandra__div", "post_319", wide["post_319_divine_swap"] == 1),
        ("ln_mirror_chaos", "Mirror of Kalandra__chaos", "all_leagues", pd.Series(True, index=wide.index)),
        ("ln_mirror_chaos", "Mirror of Kalandra__chaos", "post_319", wide["post_319_divine_swap"] == 1),
        ("ln_hom_divine", "House of Mirrors__div", "post_319", wide["post_319_divine_swap"] == 1),
        ("ln_apothecary_divine", "The Apothecary__div", "post_319", wide["post_319_divine_swap"] == 1),
        ("ln_doctor_divine", "The Doctor__div", "post_319", wide["post_319_divine_swap"] == 1),
        ("ln_sybl_divine", "Seven Years Bad Luck__div", "post_319", wide["post_319_divine_swap"] == 1),
    ]

    for dep_name, col, sample_name, base_mask in targets:
        df = wide.loc[
            base_mask & wide[col].notna() & (wide[col] > 0) & wide["log_players"].notna() & wide["retention_rate"].notna()
        ].copy()
        df["y"] = np.log(df[col])
        n_leagues = df["league_name"].nunique()
        if len(df) < 30 or n_leagues < 3:
            continue

        # Spec A1: League FE + quadratic log1p(league_day) + player factors
        formula_fe = "y ~ log_players + retention_rate + log1p_day + log1p_day_sq + is_weekend + C(league_name)"
        # Compute within-R2 by demeaning y by league
        y_dm = df["y"] - df.groupby("league_name")["y"].transform("mean")
        fit_fe_cl = smf.ols(formula_fe, data=df).fit(
            cov_type="cluster", cov_kwds={"groups": df["league_name"]}
        )
        # Within R2: 1 - RSS / TSS_within
        tss_within = float((y_dm ** 2).sum())
        r2_within = 1.0 - float((fit_fe_cl.resid ** 2).sum()) / tss_within if tss_within > 0 else np.nan
        reg_rows.extend(_extract_model_rows(
            fit_fe_cl, dep_name, sample_name, "FE_LogLevels_QuadDay", "Cluster_League",
            extra_r2=r2_within,
        ))
        # Also record Newey-West HAC (maxlags=7) on same FE model
        fit_fe_hac = smf.ols(formula_fe, data=df).fit(
            cov_type="HAC", cov_kwds={"maxlags": 7}
        )
        reg_rows.extend(_extract_model_rows(
            fit_fe_hac, dep_name, sample_name, "FE_LogLevels_QuadDay", "HAC_NW_lag7",
            extra_r2=r2_within,
        ))

        # Spec A1b & A1c: Single player-metric FE checks (since log_players = ln(day0_peak) + ln(retention_rate) within league)
        fit_lp = smf.ols("y ~ log_players + log1p_day + log1p_day_sq + is_weekend + C(league_name)", data=df).fit(
            cov_type="cluster", cov_kwds={"groups": df["league_name"]}
        )
        r2_w_lp = 1.0 - float((fit_lp.resid ** 2).sum()) / tss_within if tss_within > 0 else np.nan
        reg_rows.extend(_extract_model_rows(
            fit_lp, dep_name, sample_name, "FE_LogPlayers_Only", "Cluster_League",
            extra_r2=r2_w_lp,
        ))

        fit_ret = smf.ols("y ~ retention_rate + log1p_day + log1p_day_sq + is_weekend + C(league_name)", data=df).fit(
            cov_type="cluster", cov_kwds={"groups": df["league_name"]}
        )
        r2_w_ret = 1.0 - float((fit_ret.resid ** 2).sum()) / tss_within if tss_within > 0 else np.nan
        reg_rows.extend(_extract_model_rows(
            fit_ret, dep_name, sample_name, "FE_Retention_Only", "Cluster_League",
            extra_r2=r2_w_ret,
        ))

        # Spec A2: Nonlinear B-spline check on league_day (df=4, rank-full with intercept/FE)
        formula_sp = "y ~ log_players + retention_rate + bs(league_day, df=4) + is_weekend + C(league_name)"
        fit_sp = smf.ols(formula_sp, data=df).fit(
            cov_type="cluster", cov_kwds={"groups": df["league_name"]}
        )
        r2_within_sp = 1.0 - float((fit_sp.resid ** 2).sum()) / tss_within if tss_within > 0 else np.nan
        reg_rows.extend(_extract_model_rows(
            fit_sp, dep_name, sample_name, "FE_LogLevels_Spline4", "Cluster_League",
            keep_terms=["Intercept", "log_players", "retention_rate", "is_weekend"],
            extra_r2=r2_within_sp,
        ))

        # Spec B: League FE with Regime x Lifecycle/Retention Interactions
        if sample_name == "post_319" and df["currency_exchange_faustus"].nunique() > 1:
            df["faustus_x_logday"] = df["currency_exchange_faustus"] * df["log1p_day"]
            df["faustus_x_ret"] = df["currency_exchange_faustus"] * df["retention_rate"]
            df["mf_x_logday"] = df["magic_find_inflation"] * df["log1p_day"]
            df["mf_x_ret"] = df["magic_find_inflation"] * df["retention_rate"]
            if df["magic_find_inflation"].nunique() > 1:
                formula_int = (
                    "y ~ log_players + retention_rate + log1p_day + log1p_day_sq + is_weekend "
                    "+ faustus_x_logday + faustus_x_ret + mf_x_logday + mf_x_ret + C(league_name)"
                )
            else:
                formula_int = (
                    "y ~ log_players + retention_rate + log1p_day + log1p_day_sq + is_weekend "
                    "+ faustus_x_logday + faustus_x_ret + C(league_name)"
                )
            fit_int = smf.ols(formula_int, data=df).fit(
                cov_type="cluster", cov_kwds={"groups": df["league_name"]}
            )
            r2_within_int = 1.0 - float((fit_int.resid ** 2).sum()) / tss_within if tss_within > 0 else np.nan
            reg_rows.extend(_extract_model_rows(
                fit_int, dep_name, sample_name, "FE_RegimeInteractions", "Cluster_League",
                extra_r2=r2_within_int,
            ))

        # Spec C: Pooled Structural Regime Levels & Slopes
        # Note: On matched player_factors sample (league_day <= 90), currency_exchange_faustus == poe2_ea_overlap (3.25+)
        if sample_name in ("all_leagues", "post_319"):
            terms_pool = ["log_players", "retention_rate", "log1p_day", "log1p_day_sq", "is_weekend"]
            if sample_name == "all_leagues" and df["post_319_divine_swap"].nunique() > 1:
                terms_pool.append("post_319_divine_swap")
            if df["currency_exchange_faustus"].nunique() > 1:
                # Explicitly represent the 3.25+ joint Faustus & PoE2-EA era dummy
                df["regime_325_faustus_poe2"] = df["currency_exchange_faustus"]
                terms_pool.append("regime_325_faustus_poe2")
            if df["magic_find_inflation"].nunique() > 1:
                terms_pool.append("magic_find_inflation")
            formula_pool = "y ~ " + " + ".join(terms_pool)
            fit_pool_cl = smf.ols(formula_pool, data=df).fit(
                cov_type="cluster", cov_kwds={"groups": df["league_name"]}
            )
            fit_pool_hac = smf.ols(formula_pool, data=df).fit(
                cov_type="HAC", cov_kwds={"maxlags": 7}
            )
            reg_rows.extend(_extract_model_rows(
                fit_pool_cl, dep_name, sample_name, "Pooled_Regimes", "Cluster_League"
            ))
            reg_rows.extend(_extract_model_rows(
                fit_pool_hac, dep_name, sample_name, "Pooled_Regimes", "HAC_NW_lag7"
            ))

        # Spec D: First-Differences on consecutive daily observations (d_day == 1)
        df_s = df.sort_values(["patch_num", "league_day"]).copy()
        df_s["d_day"] = df_s.groupby("league_name")["league_day"].diff()
        df_s["dy"] = df_s.groupby("league_name")["y"].diff()
        df_s["d_log_players"] = df_s.groupby("league_name")["log_players"].diff()
        df_s["d_retention"] = df_s.groupby("league_name")["retention_rate"].diff()
        df_s["d_log1p_day"] = df_s.groupby("league_name")["log1p_day"].diff()
        df_fd = df_s[df_s["d_day"] == 1].dropna(
            subset=["dy", "d_log_players", "d_retention", "d_log1p_day"]
        ).copy()
        if len(df_fd) >= 30 and df_fd["league_name"].nunique() >= 3:
            formula_fd = "dy ~ d_log_players + d_retention + d_log1p_day + is_weekend"
            fit_fd_cl = smf.ols(formula_fd, data=df_fd).fit(
                cov_type="cluster", cov_kwds={"groups": df_fd["league_name"]}
            )
            fit_fd_hac = smf.ols(formula_fd, data=df_fd).fit(
                cov_type="HAC", cov_kwds={"maxlags": 5}
            )
            reg_rows.extend(_extract_model_rows(
                fit_fd_cl, f"d_{dep_name}", sample_name, "FD_ConsecutiveDays", "Cluster_League"
            ))
            reg_rows.extend(_extract_model_rows(
                fit_fd_hac, f"d_{dep_name}", sample_name, "FD_ConsecutiveDays", "HAC_NW_lag5"
            ))

    # Spec E: Full Economy Panel (no day-90 truncation) separating Faustus (3.25+) vs PoE2 EA active (date >= 2024-12-06)
    # Using Settlers days 1..318 + 3.19..3.30
    full_targets = [
        ("ln_divine_chaos", "Divine Orb__chaos"),
        ("ln_mirror_chaos", "Mirror of Kalandra__chaos"),
        ("ln_hom_divine", "House of Mirrors__div"),
        ("ln_apothecary_divine", "The Apothecary__div"),
    ]
    for dep_name, col in full_targets:
        df_full = wide[
            (wide["post_319_divine_swap"] == 1) & wide[col].notna() & (wide[col] > 0)
        ].copy()
        df_full["y"] = np.log(df_full[col])
        df_full["is_weekend_cal"] = pd.to_datetime(df_full["date"]).dt.day_of_week.isin([5, 6]).astype(int)
        # Pooled separating Faustus vs PoE2 EA active
        formula_sep = (
            "y ~ log1p_day + log1p_day_sq + is_weekend_cal "
            "+ currency_exchange_faustus + poe2_ea_active + magic_find_inflation"
        )
        fit_sep_hac = smf.ols(formula_sep, data=df_full).fit(
            cov_type="HAC", cov_kwds={"maxlags": 7}
        )
        fit_sep_cl = smf.ols(formula_sep, data=df_full).fit(
            cov_type="cluster", cov_kwds={"groups": df_full["league_name"]}
        )
        reg_rows.extend(_extract_model_rows(
            fit_sep_hac, dep_name, "full_post319_untruncated", "FullEcon_Faustus_vs_PoE2EA", "HAC_NW_lag7"
        ))
        reg_rows.extend(_extract_model_rows(
            fit_sep_cl, dep_name, "full_post319_untruncated", "FullEcon_Faustus_vs_PoE2EA", "Cluster_League"
        ))

        # Within-Settlers test of PoE2 EA active (Dec 6, 2024+)
        df_set = df_full[df_full["league_name"] == "Settlers"].copy()
        if df_set["poe2_ea_active"].nunique() > 1 and len(df_set) >= 30:
            fit_set = smf.ols(
                "y ~ log1p_day + log1p_day_sq + is_weekend_cal + poe2_ea_active", data=df_set
            ).fit(cov_type="HAC", cov_kwds={"maxlags": 7})
            reg_rows.extend(_extract_model_rows(
                fit_set, dep_name, "settlers_within_318d", "WithinSettlers_PoE2EA", "HAC_NW_lag7"
            ))

    reg_df = pd.DataFrame(reg_rows)
    reg_df.to_csv(TABLE_DIR / "03_panel_regressions.csv", index=False)
    return reg_df


def compute_parity_analysis(wide: pd.DataFrame) -> tuple[pd.DataFrame, pd.DataFrame, pd.DataFrame]:
    """Compute Card vs Underlying parity ratios across leagues/phases and panel regressions."""
    parity_rows = []
    parity_daily_frames = []
    reg_rows = []

    for card, und, stack_n, label in PARITY_PAIRS:
        c_col = f"{card}__chaos"
        u_col = f"{und}__chaos"
        if c_col not in wide.columns or u_col not in wide.columns:
            continue

        df = wide[wide[c_col].notna() & wide[u_col].notna() & (wide[u_col] > 0) & (wide[c_col] > 0)].copy()
        df["pair"] = label
        df["card_name"] = card
        df["underlying_name"] = und
        df["stack_size"] = stack_n
        df["parity_ratio"] = stack_n * df[c_col] / df[u_col]
        df["log_parity_ratio"] = np.log(df["parity_ratio"])

        # Flag extreme poe.watch variant/day0-1 artifacts (ratio > 5.0 or ratio < 0.05) for clean sensitivity check
        df["is_extreme_outlier"] = ((df["parity_ratio"] > 5.0) | (df["parity_ratio"] < 0.05)).astype(int)
        parity_daily_frames.append(df)

        for sample_tag, sub_df in [("raw", df), ("clean_no_extreme", df[df["is_extreme_outlier"] == 0])]:
            # Per league summary
            for (patch_ver, lg), g in sub_df.groupby(["patch_version", "league_name"], sort=False):
                early = g[(g["league_day"] >= 1) & (g["league_day"] <= 14)]["parity_ratio"]
                mid = g[(g["league_day"] >= 15) & (g["league_day"] <= 45)]["parity_ratio"]
                late = g[(g["league_day"] >= 46) & (g["league_day"] <= 90)]["parity_ratio"]
                r = g["parity_ratio"]
                parity_rows.append({
                    "pair": label,
                    "sample_filter": sample_tag,
                    "group_type": "league",
                    "group_name": f"{patch_ver}_{lg}",
                    "n_obs": int(len(r)),
                    "median": round(float(r.median()), 4),
                    "q25": round(float(np.percentile(r, 25)), 4),
                    "q75": round(float(np.percentile(r, 75)), 4),
                    "iqr": round(float(np.percentile(r, 75) - np.percentile(r, 25)), 4),
                    "mean": round(float(r.mean()), 4),
                    "std": round(float(r.std(ddof=1)), 4) if len(r) > 1 else np.nan,
                    "pct_above_1": round(float((r > 1.0).mean() * 100.0), 2),
                    "early_d1_14_median": round(float(early.median()), 4) if len(early) else np.nan,
                    "mid_d15_45_median": round(float(mid.median()), 4) if len(mid) else np.nan,
                    "late_d46_90_median": round(float(late.median()), 4) if len(late) else np.nan,
                })

            # Per regime summary
            for reg_name, g in sub_df.groupby("regime"):
                early = g[(g["league_day"] >= 1) & (g["league_day"] <= 14)]["parity_ratio"]
                mid = g[(g["league_day"] >= 15) & (g["league_day"] <= 45)]["parity_ratio"]
                late = g[(g["league_day"] >= 46) & (g["league_day"] <= 90)]["parity_ratio"]
                r = g["parity_ratio"]
                parity_rows.append({
                    "pair": label,
                    "sample_filter": sample_tag,
                    "group_type": "regime",
                    "group_name": reg_name,
                    "n_obs": int(len(r)),
                    "median": round(float(r.median()), 4),
                    "q25": round(float(np.percentile(r, 25)), 4),
                    "q75": round(float(np.percentile(r, 75)), 4),
                    "iqr": round(float(np.percentile(r, 75) - np.percentile(r, 25)), 4),
                    "mean": round(float(r.mean()), 4),
                    "std": round(float(r.std(ddof=1)), 4) if len(r) > 1 else np.nan,
                    "pct_above_1": round(float((r > 1.0).mean() * 100.0), 2),
                    "early_d1_14_median": round(float(early.median()), 4) if len(early) else np.nan,
                    "mid_d15_45_median": round(float(mid.median()), 4) if len(mid) else np.nan,
                    "late_d46_90_median": round(float(late.median()), 4) if len(late) else np.nan,
                })

        # Regressions on clean parity ratio (player-matched sample)
        df_reg = df[(df["is_extreme_outlier"] == 0) & df["log_players"].notna() & df["retention_rate"].notna()].copy()
        if len(df_reg) >= 30 and df_reg["league_name"].nunique() >= 3:
            # League FE
            y_dm = df_reg["log_parity_ratio"] - df_reg.groupby("league_name")["log_parity_ratio"].transform("mean")
            tss_w = float((y_dm ** 2).sum())
            fit_fe = smf.ols(
                "log_parity_ratio ~ log1p_day + retention_rate + log_players + is_weekend + C(league_name)",
                data=df_reg,
            ).fit(cov_type="cluster", cov_kwds={"groups": df_reg["league_name"]})
            r2_w = 1.0 - float((fit_fe.resid ** 2).sum()) / tss_w if tss_w > 0 else np.nan
            reg_rows.extend(_extract_model_rows(
                fit_fe, f"ln_parity_{label}", "clean_matched", "Parity_FE", "Cluster_League", extra_r2=r2_w
            ))

            # Pooled Regime model
            terms = ["log1p_day", "retention_rate", "log_players", "is_weekend"]
            if df_reg["post_319_divine_swap"].nunique() > 1:
                terms.append("post_319_divine_swap")
            if df_reg["currency_exchange_faustus"].nunique() > 1:
                df_reg["regime_325_faustus_poe2"] = df_reg["currency_exchange_faustus"]
                terms.append("regime_325_faustus_poe2")
            if df_reg["magic_find_inflation"].nunique() > 1:
                terms.append("magic_find_inflation")
            fit_pool = smf.ols("log_parity_ratio ~ " + " + ".join(terms), data=df_reg).fit(
                cov_type="cluster", cov_kwds={"groups": df_reg["league_name"]}
            )
            reg_rows.extend(_extract_model_rows(
                fit_pool, f"ln_parity_{label}", "clean_matched", "Parity_Pooled_Regimes", "Cluster_League"
            ))

    parity_df = pd.DataFrame(parity_rows)
    parity_df.to_csv(TABLE_DIR / "04_parity_ratios.csv", index=False)

    parity_reg_df = pd.DataFrame(reg_rows)
    parity_reg_df.to_csv(TABLE_DIR / "04b_parity_regressions.csv", index=False)

    parity_daily = pd.concat(parity_daily_frames, ignore_index=True)
    return parity_df, parity_reg_df, parity_daily


def compute_lead_lag_and_granger(wide: pd.DataFrame) -> tuple[pd.DataFrame, pd.DataFrame]:
    """Compute within-league consecutive-day return cross-correlations (lags -7..+7)
    and pooled within-league Granger causality F-tests (lags 1..3)."""
    df_p = wide[wide["post_319_divine_swap"] == 1].sort_values(["patch_num", "league_day"]).copy()

    pairs_ccf = [
        ("D/C", "Divine Orb__chaos", "Mirror/D", "Mirror of Kalandra__div"),
        ("D/C", "Divine Orb__chaos", "Mirror/C", "Mirror of Kalandra__chaos"),
        ("D/C", "Divine Orb__chaos", "HoM/D", "House of Mirrors__div"),
        ("D/C", "Divine Orb__chaos", "HoM/C", "House of Mirrors__chaos"),
        ("Mirror/D", "Mirror of Kalandra__div", "HoM/D", "House of Mirrors__div"),
        ("Mirror/C", "Mirror of Kalandra__chaos", "HoM/C", "House of Mirrors__chaos"),
        ("Mageblood/D", "Mageblood__div", "Apothecary/D", "The Apothecary__div"),
        ("Mageblood/C", "Mageblood__chaos", "Apothecary/C", "The Apothecary__chaos"),
        ("Headhunter/D", "Headhunter__div", "Doctor/D", "The Doctor__div"),
        ("Headhunter/C", "Headhunter__chaos", "Doctor/C", "The Doctor__chaos"),
        ("MirrorShard/D", "Mirror Shard__div", "SYBL/D", "Seven Years Bad Luck__div"),
        ("D/C", "Divine Orb__chaos", "Apothecary/D", "The Apothecary__div"),
        ("D/C", "Divine Orb__chaos", "Doctor/D", "The Doctor__div"),
    ]

    ccf_rows = []
    granger_rows = []

    for x_name, x_col, y_name, y_col in pairs_ccf:
        if x_col not in df_p.columns or y_col not in df_p.columns:
            continue

        # Build consecutive-day log returns within each league
        sub = df_p[["league_name", "patch_num", "league_day", x_col, y_col]].dropna().copy()
        sub = sub[(sub[x_col] > 0) & (sub[y_col] > 0)].sort_values(["patch_num", "league_day"])
        sub["d_day"] = sub.groupby("league_name")["league_day"].diff()
        sub["rx"] = np.log(sub[x_col]) - np.log(sub.groupby("league_name")[x_col].shift(1))
        sub["ry"] = np.log(sub[y_col]) - np.log(sub.groupby("league_name")[y_col].shift(1))
        sub = sub[sub["d_day"] == 1].copy()

        # Trim extreme >100% single-day poe.watch artifact spikes in returns (e.g. |r| > 1.0 = >171% 1-day jump)
        # Report raw & trimmed n_obs; CCF computed on consecutive returns without cross-league bleed
        sub_clean = sub[(sub["rx"].abs() <= 1.0) & (sub["ry"].abs() <= 1.0)].copy()
        if len(sub_clean) < 40:
            continue

        # Cross-correlation for lag k in -7..+7: corr(rx_{t-k}, ry_t)
        # Positive lag k > 0 means x_{t-k} leads y_t (X leads Y)
        for k in range(-7, 8):
            tmp = sub_clean.copy()
            tmp["rx_lag"] = tmp.groupby("league_name")["rx"].shift(k)
            tmp["day_diff_k"] = tmp["league_day"] - tmp.groupby("league_name")["league_day"].shift(k)
            valid = tmp[(tmp["day_diff_k"] == k) & tmp["rx_lag"].notna() & tmp["ry"].notna()]
            if len(valid) < 25:
                continue
            r_val, p_val = stats.pearsonr(valid["rx_lag"], valid["ry"])
            ccf_rows.append({
                "pair": f"{x_name} -> {y_name}",
                "x_series": x_name,
                "y_series": y_name,
                "lag_days": k,
                "n_obs": int(len(valid)),
                "pearson_r": round(float(r_val), 5),
                "p_value": float(p_val),
                "se_approx": round(float(1.0 / np.sqrt(len(valid))), 5),
            })

        # Pooled within-league Granger causality tests (lags p=1,2,3) in both directions
        for p_lag in (1, 2, 3):
            tmp = sub_clean.copy()
            lag_cols_x, lag_cols_y = [], []
            ok_mask = pd.Series(True, index=tmp.index)
            for l in range(1, p_lag + 1):
                cx = f"rx_l{l}"
                cy = f"ry_l{l}"
                tmp[cx] = tmp.groupby("league_name")["rx"].shift(l)
                tmp[cy] = tmp.groupby("league_name")["ry"].shift(l)
                dd = tmp["league_day"] - tmp.groupby("league_name")["league_day"].shift(l)
                ok_mask = ok_mask & (dd == l) & tmp[cx].notna() & tmp[cy].notna()
                lag_cols_x.append(cx)
                lag_cols_y.append(cy)
            g_df = tmp[ok_mask].copy()
            if len(g_df) < 40:
                continue

            # Direction 1: X Granger-causes Y
            res_r = smf.ols("ry ~ " + " + ".join(lag_cols_y), data=g_df).fit()
            res_u = smf.ols("ry ~ " + " + ".join(lag_cols_y + lag_cols_x), data=g_df).fit()
            f_stat, f_pval, df_diff = res_u.compare_f_test(res_r)
            granger_rows.append({
                "direction": f"{x_name} => {y_name}",
                "max_lag": p_lag,
                "n_obs": int(len(g_df)),
                "f_stat": round(float(f_stat), 4),
                "p_value": float(f_pval),
                "df_num": int(df_diff),
                "r2_restricted": round(float(res_r.rsquared), 5),
                "r2_unrestricted": round(float(res_u.rsquared), 5),
            })

            # Direction 2: Y Granger-causes X
            res_r2 = smf.ols("rx ~ " + " + ".join(lag_cols_x), data=g_df).fit()
            res_u2 = smf.ols("rx ~ " + " + ".join(lag_cols_x + lag_cols_y), data=g_df).fit()
            f_stat2, f_pval2, df_diff2 = res_u2.compare_f_test(res_r2)
            granger_rows.append({
                "direction": f"{y_name} => {x_name}",
                "max_lag": p_lag,
                "n_obs": int(len(g_df)),
                "f_stat": round(float(f_stat2), 4),
                "p_value": float(f_pval2),
                "df_num": int(df_diff2),
                "r2_restricted": round(float(res_r2.rsquared), 5),
                "r2_unrestricted": round(float(res_u2.rsquared), 5),
            })

    ccf_df = pd.DataFrame(ccf_rows)
    granger_df = pd.DataFrame(granger_rows)
    ccf_df.to_csv(TABLE_DIR / "05_lead_lag_ccf.csv", index=False)
    granger_df.to_csv(TABLE_DIR / "05b_granger_tests.csv", index=False)
    return ccf_df, granger_df


def compute_variance_decomposition(wide: pd.DataFrame) -> pd.DataFrame:
    """Exact 3-group Shapley/LMG R2 decomposition + GroupKFold RF permutation importance."""
    targets = [
        ("ln_divine_chaos_post319", "Divine Orb__chaos", wide["post_319_divine_swap"] == 1, False),
        ("ln_divine_chaos_all", "Divine Orb__chaos", pd.Series(True, index=wide.index), True),
        ("ln_mirror_divine_post319", "Mirror of Kalandra__div", wide["post_319_divine_swap"] == 1, False),
        ("ln_mirror_chaos_all", "Mirror of Kalandra__chaos", pd.Series(True, index=wide.index), True),
        ("ln_hom_divine_post319", "House of Mirrors__div", wide["post_319_divine_swap"] == 1, False),
        ("ln_apothecary_divine_post319", "The Apothecary__div", wide["post_319_divine_swap"] == 1, False),
        ("ln_doctor_divine_post319", "The Doctor__div", wide["post_319_divine_swap"] == 1, False),
        ("ln_sybl_divine_post319", "Seven Years Bad Luck__div", wide["post_319_divine_swap"] == 1, False),
    ]

    rows = []
    for t_name, col, mask, include_319 in targets:
        df = wide.loc[
            mask & wide[col].notna() & (wide[col] > 0)
            & wide["log_players"].notna() & wide["retention_rate"].notna() & wide["log_day0_peak"].notna()
        ].copy()
        df["y"] = np.log(df[col])
        if len(df) < 50 or df["league_name"].nunique() < 4:
            continue

        regime_cols = ["currency_exchange_faustus", "magic_find_inflation"]
        if include_319 and df["post_319_divine_swap"].nunique() > 1:
            regime_cols = ["post_319_divine_swap"] + regime_cols
        # Keep only varying columns
        regime_cols = [c for c in regime_cols if df[c].nunique() > 1]

        groups = {
            "Time_Lifecycle": ["log1p_day", "log1p_day_sq", "league_day", "is_weekend"],
            "Players_Retention": ["log_players", "retention_rate", "log_day0_peak"],
            "Structural_Regimes": regime_cols,
        }

        def r2_subset(group_keys: tuple[str, ...]) -> float:
            cols = []
            for gk in group_keys:
                cols.extend(groups[gk])
            if not cols:
                return 0.0
            X = sm.add_constant(df[cols], has_constant="add")
            fit = sm.OLS(df["y"], X).fit()
            return float(fit.rsquared)

        # Exact Shapley R2 across all 3! = 6 permutations
        group_names = list(groups.keys())
        cache_r2 = {}
        for r in range(len(group_names) + 1):
            for comb in itertools.combinations(group_names, r):
                cache_r2[tuple(sorted(comb))] = r2_subset(comb)

        shapley = {g: 0.0 for g in group_names}
        perms = list(itertools.permutations(group_names))
        for perm in perms:
            cur = []
            prev_r2 = 0.0
            for g in perm:
                cur.append(g)
                new_r2 = cache_r2[tuple(sorted(cur))]
                shapley[g] += (new_r2 - prev_r2) / len(perms)
                prev_r2 = new_r2

        full_r2 = cache_r2[tuple(sorted(group_names))]

        # Pooled 5-fold CV RandomForest OOF R2 + permutation importance (for cross-league + within-league level prediction)
        all_cols = groups["Time_Lifecycle"] + groups["Players_Retention"] + groups["Structural_Regimes"]
        X_all = df[all_cols].to_numpy()
        y_all = df["y"].to_numpy()
        kf = KFold(n_splits=5, shuffle=True, random_state=42)

        oof_preds = np.zeros_like(y_all)
        perm_imp_accum = np.zeros(len(all_cols))
        for tr_idx, te_idx in kf.split(X_all, y_all):
            rf = RandomForestRegressor(n_estimators=200, max_depth=8, min_samples_leaf=5, random_state=42, n_jobs=-1)
            rf.fit(X_all[tr_idx], y_all[tr_idx])
            oof_preds[te_idx] = rf.predict(X_all[te_idx])
            pi = permutation_importance(rf, X_all[te_idx], y_all[te_idx], n_repeats=10, random_state=42, scoring="r2")
            perm_imp_accum += pi.importances_mean / 5.0
        rf_pooled_oof_r2 = float(r2_score(y_all, oof_preds))

        # Also GroupKFold on league-demeaned y (pure within-league dynamics across unseen leagues)
        y_within = (df["y"] - df.groupby("league_name")["y"].transform("mean")).to_numpy()
        grp_labels = df["league_name"].to_numpy()
        n_splits_g = min(5, df["league_name"].nunique())
        gkf = GroupKFold(n_splits=n_splits_g)
        oof_within = np.zeros_like(y_within)
        within_cols = groups["Time_Lifecycle"] + ["retention_rate", "log_players"]
        X_w = df[within_cols].to_numpy()
        for tr_idx, te_idx in gkf.split(X_w, y_within, groups=grp_labels):
            rf_w = RandomForestRegressor(n_estimators=200, max_depth=6, min_samples_leaf=5, random_state=42, n_jobs=-1)
            rf_w.fit(X_w[tr_idx], y_within[tr_idx])
            oof_within[te_idx] = rf_w.predict(X_w[te_idx])
        rf_within_oof_r2 = float(r2_score(y_within, oof_within))

        perm_by_col = dict(zip(all_cols, perm_imp_accum))
        perm_by_group = {
            gk: float(sum(max(0.0, perm_by_col[c]) for c in cols))
            for gk, cols in groups.items()
        }
        perm_total = sum(perm_by_group.values()) or 1.0

        for gk in group_names:
            rows.append({
                "target": t_name,
                "n_obs": int(len(df)),
                "n_leagues": int(df["league_name"].nunique()),
                "full_ols_r2": round(full_r2, 5),
                "group": gk,
                "shapley_r2": round(shapley[gk], 5),
                "shapley_share_pct": round(100.0 * shapley[gk] / full_r2, 2) if full_r2 > 0 else 0.0,
                "solo_ols_r2": round(cache_r2[(gk,)], 5),
                "rf_pooled_oof_r2": round(rf_pooled_oof_r2, 5),
                "rf_within_group_oof_r2": round(rf_within_oof_r2, 5),
                "rf_perm_delta_r2": round(perm_by_group[gk], 5),
                "rf_perm_share_pct": round(100.0 * perm_by_group[gk] / perm_total, 2),
            })

    vdec_df = pd.DataFrame(rows)
    vdec_df.to_csv(TABLE_DIR / "06_variance_decomposition.csv", index=False)
    return vdec_df


def make_figures(
    wide: pd.DataFrame,
    traj_df: pd.DataFrame,
    infl_df: pd.DataFrame,
    reg_df: pd.DataFrame,
    parity_daily: pd.DataFrame,
    ccf_df: pd.DataFrame,
    vdec_df: pd.DataFrame,
    ev: pd.DataFrame,
) -> None:
    # ------------------------------------------------------------------
    # Figure 1: Cross-League Lifecycle Trajectories (2x2)
    # ------------------------------------------------------------------
    fig, axes = plt.subplots(2, 2, figsize=(13.5, 9.2))

    # Panel A: D/C by Regime vs Exalt/C pre-3.19
    ax = axes[0, 0]
    for reg, item, unit, label, color, ls in [
        ("post_319_pre_faustus", "Divine Orb", "chaos", "D/C: Post-3.19 Pre-Faustus (3.19-3.24)", "#d95f02", "-"),
        ("faustus_325_plus", "Divine Orb", "chaos", "D/C: Faustus Era (3.25-3.30)", "#1b9e77", "-"),
        ("pre_319", "Exalted Orb", "chaos", "Ex/C: Pre-3.19 Benchmark (3.12-3.18)", "#7570b3", "--"),
        ("pre_319", "Divine Orb", "chaos", "D/C: Pre-3.19 (3.12-3.18)", "#666666", ":"),
    ]:
        sub = traj_df[(traj_df["regime"] == reg) & (traj_df["item_name"] == item) & (traj_df["unit"] == unit)]
        sub = sub[sub["n_leagues"] >= 2] if reg != "pre_319" or item != "Divine Orb" else sub
        ax.plot(sub["league_day"], sub["median"], label=label, color=color, linestyle=ls, linewidth=2.0)
        if ls == "-":
            ax.fill_between(sub["league_day"], sub["q25"], sub["q75"], color=color, alpha=0.14)
    ax.set_title("(A) Reserve Currency in Chaos by League Day (Median & IQR)")
    ax.set_xlabel("League Day (0 = Launch)")
    ax.set_ylabel("Chaos Orb Value")
    ax.set_xlim(0, 90)
    ax.set_ylim(0, 495)
    ax.legend(loc="upper left", frameon=True, framealpha=0.92, fontsize=8.0)

    # Panel B: Mirror/D and House of Mirrors x9 / D (Post-3.19)
    ax = axes[0, 1]
    for item, mult, label, color in [
        ("Mirror of Kalandra", 1.0, "Mirror of Kalandra (D)", "#e7298a"),
        ("House of Mirrors", 9.0, "House of Mirrors x9 (D)", "#1f78b4"),
    ]:
        sub = traj_df[(traj_df["regime"] == "all_post_319") & (traj_df["item_name"] == item) & (traj_df["unit"] == "divine")]
        ax.plot(sub["league_day"], sub["median"] * mult, label=label, color=color, linewidth=2.0)
        ax.fill_between(sub["league_day"], sub["q25"] * mult, sub["q75"] * mult, color=color, alpha=0.14)
    ax.set_title("(B) Mirror & 9x House of Mirrors in Divine (Post-3.19)")
    ax.set_xlabel("League Day (0 = Launch)")
    ax.set_ylabel("Divine Orb Value")
    ax.set_xlim(0, 90)
    ax.legend(loc="upper left", frameon=True, framealpha=0.9)

    # Panel C: Mirror/C across regimes (log scale)
    ax = axes[1, 0]
    for reg, label, color in [
        ("pre_319", "Pre-3.19 (3.12-3.18)", "#7570b3"),
        ("post_319_pre_faustus", "Post-3.19 Pre-Faustus (3.19-3.24)", "#d95f02"),
        ("faustus_325_plus", "Faustus Era (3.25-3.30)", "#1b9e77"),
    ]:
        sub = traj_df[(traj_df["regime"] == reg) & (traj_df["item_name"] == "Mirror of Kalandra") & (traj_df["unit"] == "chaos")]
        sub = sub[sub["league_day"] >= 2]
        ax.plot(sub["league_day"], sub["median"], label=label, color=color, linewidth=2.0)
        ax.fill_between(sub["league_day"], sub["q25"], sub["q75"], color=color, alpha=0.14)
    ax.set_yscale("log")
    ax.set_title("(C) Mirror of Kalandra in Chaos (Log Scale, Days 2-90)")
    ax.set_xlabel("League Day")
    ax.set_ylabel("Chaos Value (log scale)")
    ax.set_xlim(2, 90)
    ax.legend(loc="lower right", frameon=True, framealpha=0.9)

    # Panel D: Normalized Divination Card Trajectories in Divine (Day 7 = 1.0, Post-3.19)
    ax = axes[1, 1]
    card_colors = {
        "House of Mirrors": "#e7298a",
        "The Apothecary": "#1b9e77",
        "The Doctor": "#d95f02",
        "Seven Years Bad Luck": "#7570b3",
        "Brother's Gift": "#e6ab02",
        "The Fortunate": "#666666",
    }
    for card, color in card_colors.items():
        sub = traj_df[(traj_df["regime"] == "all_post_319") & (traj_df["item_name"] == card) & (traj_df["unit"] == "divine")]
        sub = sub[sub["league_day"] >= 1].copy()
        d7 = sub.loc[sub["league_day"] == 7, "median"]
        if len(d7) and float(d7.iloc[0]) > 0:
            base = float(d7.iloc[0])
            ax.plot(sub["league_day"], sub["median"] / base, label=f"{card} (D7={base:.1f}D)", color=color, linewidth=1.9)
    ax.axhline(1.0, color="black", linestyle=":", linewidth=1.0, alpha=0.7)
    ax.set_title("(D) Divination Cards in Divine Normalized to Day 7 = 1.0 (Post-3.19)")
    ax.set_xlabel("League Day")
    ax.set_ylabel("Relative Price (Day 7 = 1.0)")
    ax.set_xlim(1, 90)
    ax.legend(loc="upper left", frameon=True, framealpha=0.9, fontsize=7.8)

    fig.suptitle("PoE 1 Cross-League Economy Lifecycle Trajectories (3.12-3.30)", fontsize=13.5, fontweight="bold", y=0.99)
    fig.tight_layout(rect=[0, 0, 1, 0.965])
    fig.savefig(FIG_DIR / "fig1_lifecycle_curves.png")
    plt.close(fig)

    # ------------------------------------------------------------------
    # Figure 2: Structural Regime Shifts & Early vs Late Inflation Across 19 Leagues
    # ------------------------------------------------------------------
    fig, axes = plt.subplots(2, 1, figsize=(13.5, 8.8), sharex=True)

    league_order = [
        f"{r.patch_version} {r.league_name}"
        for _, r in ev[ev["league_name"].isin(wide["league_name"].unique())].iterrows()
    ]
    wide_plot = wide[wide["league_day"] <= 90].copy()
    wide_plot["league_label"] = wide_plot["patch_version"] + " " + wide_plot["league_name"]

    # Panel A: Divine/C & Exalt/C medians + IQR
    ax = axes[0]
    div_stats = (
        wide_plot.groupby("league_label")["Divine Orb__chaos"]
        .agg(["median", lambda s: s.quantile(0.25), lambda s: s.quantile(0.75)])
        .reindex(league_order)
    )
    div_stats.columns = ["med", "q25", "q75"]
    exa_stats = (
        wide_plot.groupby("league_label")["Exalted Orb__chaos"]
        .agg(["median", lambda s: s.quantile(0.25), lambda s: s.quantile(0.75)])
        .reindex(league_order)
    )
    exa_stats.columns = ["med", "q25", "q75"]

    x = np.arange(len(league_order))
    ax.errorbar(
        x - 0.14, div_stats["med"],
        yerr=[div_stats["med"] - div_stats["q25"], div_stats["q75"] - div_stats["med"]],
        fmt="o", color="#1b9e77", capsize=3, markersize=6, label="Divine Orb (Chaos, Median & IQR)"
    )
    ax.errorbar(
        x + 0.14, exa_stats["med"],
        yerr=[exa_stats["med"] - exa_stats["q25"], exa_stats["q75"] - exa_stats["med"]],
        fmt="s", color="#7570b3", capsize=3, markersize=5.5, label="Exalted Orb (Chaos, Median & IQR)"
    )
    # Mark structural lines
    idx_319 = league_order.index("3.19 Kalandra")
    idx_323 = league_order.index("3.23 Affliction")
    idx_325 = league_order.index("3.25 Settlers")
    ax.axvline(idx_319 - 0.5, color="#d95f02", linestyle="--", linewidth=1.3, label="3.19 Divine/Exalt Swap")
    ax.axvspan(idx_323 - 0.4, idx_323 + 0.4, color="#e7298a", alpha=0.10, label="3.23 Affliction MF Spike")
    ax.axvline(idx_325 - 0.5, color="#1f78b4", linestyle="-.", linewidth=1.3, label="3.25+ Faustus & PoE2 EA Era")
    ax.set_title("(A) Divine Orb vs Exalted Orb Chaos Value Across 19 Challenge Leagues (Days 0-90)")
    ax.set_ylabel("Chaos Orb Value")
    ax.legend(loc="upper left", ncol=2, frameon=True, framealpha=0.9)

    # Panel B: Late-to-Early Inflation Ratio (Days 60-90 / Days 1-7)
    ax = axes[1]
    infl_sub = infl_df.copy()
    infl_sub["league_label"] = infl_sub["patch_version"] + " " + infl_sub["league_name"]
    d_infl = infl_sub[(infl_sub["item_name"] == "Divine Orb") & (infl_sub["unit"] == "chaos")].set_index("league_label")["late_to_early_ratio"].reindex(league_order)
    h_infl = infl_sub[(infl_sub["item_name"] == "House of Mirrors") & (infl_sub["unit"] == "divine")].set_index("league_label")["late_to_early_ratio"].reindex(league_order)
    m_infl = infl_sub[(infl_sub["item_name"] == "Mirror of Kalandra") & (infl_sub["unit"] == "chaos")].set_index("league_label")["late_to_early_ratio"].reindex(league_order)

    w = 0.26
    ax.bar(x - w, d_infl, width=w, color="#1b9e77", label="Divine Orb (C) Late/Early")
    ax.bar(x, h_infl, width=w, color="#e7298a", label="House of Mirrors (D) Late/Early")
    ax.bar(x + w, m_infl, width=w, color="#1f78b4", label="Mirror of Kalandra (C) Late/Early")
    ax.axhline(1.0, color="black", linestyle=":", linewidth=1.0)
    ax.axvline(idx_319 - 0.5, color="#d95f02", linestyle="--", linewidth=1.3)
    ax.axvline(idx_325 - 0.5, color="#1f78b4", linestyle="-.", linewidth=1.3)
    ax.set_title("(B) Late-League (Days 60-90) vs Early-League (Days 1-7) Inflation Multiple")
    ax.set_ylabel("Late / Early Median Ratio")
    ax.set_xticks(x)
    ax.set_xticklabels(league_order, rotation=35, ha="right")
    ax.legend(loc="upper left", frameon=True, framealpha=0.9)

    fig.suptitle("Structural Regime Shifts & Intra-League Inflation Across 19 Leagues (3.12-3.30)", fontsize=13.5, fontweight="bold", y=0.99)
    fig.tight_layout(rect=[0, 0, 1, 0.965])
    fig.savefig(FIG_DIR / "fig2_regime_boxplots_early_late.png")
    plt.close(fig)

    # ------------------------------------------------------------------
    # Figure 3: Player Retention Relationship & FE Coefficient Forest Plot
    # ------------------------------------------------------------------
    fig, axes = plt.subplots(1, 2, figsize=(13.5, 5.6))

    ax = axes[0]
    post_df = wide[(wide["post_319_divine_swap"] == 1) & wide["Divine Orb__chaos"].notna() & wide["retention_rate"].notna()].copy()
    post_df["ln_dc"] = np.log(post_df["Divine Orb__chaos"])
    reg_palette = {
        "post_319_pre_faustus": ("Pre-Faustus (3.19-3.22, 3.24)", "#d95f02"),
        "post_319_mf_323": ("Affliction MF (3.23)", "#e7298a"),
        "faustus_325_plus": ("Faustus Era (3.25-3.30)", "#1b9e77"),
    }
    for rkey, (rlabel, rcol) in reg_palette.items():
        sub = post_df[post_df["regime"] == rkey]
        if sub.empty:
            continue
        ax.scatter(sub["retention_rate"], sub["ln_dc"], alpha=0.45, s=16, color=rcol, label=rlabel)
        if len(sub) >= 10:
            z = np.polyfit(sub["retention_rate"], sub["ln_dc"], 1)
            xs = np.linspace(sub["retention_rate"].min(), sub["retention_rate"].max(), 50)
            ax.plot(xs, np.polyval(z, xs), color=rcol, linewidth=2.2)
    ax.set_title("(A) Log(D/C) vs Player Retention Rate by Regime (Post-3.19)")
    ax.set_xlabel("Player Retention Rate (Daily Peak / Day-0 Peak)")
    ax.set_ylabel("ln(Divine Orb Chaos Value)")
    ax.legend(loc="upper right", frameon=True, framealpha=0.9)

    ax = axes[1]
    fe_sub = reg_df[
        (reg_df["spec"] == "FE_LogLevels_QuadDay")
        & (reg_df["se_type"] == "Cluster_League")
        & (reg_df["sample"] == "post_319")
        & (reg_df["term"].isin(["log_players", "retention_rate", "log1p_day", "is_weekend"]))
        & (reg_df["dep_var"].isin(["ln_divine_chaos", "ln_mirror_divine", "ln_hom_divine", "ln_apothecary_divine", "ln_doctor_divine"]))
    ].copy()
    dep_labels = {
        "ln_divine_chaos": "ln(D/C)",
        "ln_mirror_divine": "ln(Mirror/D)",
        "ln_hom_divine": "ln(HoM/D)",
        "ln_apothecary_divine": "ln(Apothecary/D)",
        "ln_doctor_divine": "ln(Doctor/D)",
    }
    term_offsets = {"log_players": 0.24, "retention_rate": 0.08, "log1p_day": -0.08, "is_weekend": -0.24}
    term_colors = {"log_players": "#1f78b4", "retention_rate": "#e7298a", "log1p_day": "#1b9e77", "is_weekend": "#d95f02"}
    dep_order = ["ln_divine_chaos", "ln_mirror_divine", "ln_hom_divine", "ln_apothecary_divine", "ln_doctor_divine"]
    y_pos = np.arange(len(dep_order))

    for term in ["log_players", "retention_rate", "log1p_day", "is_weekend"]:
        tsub = fe_sub[fe_sub["term"] == term].set_index("dep_var").reindex(dep_order)
        ys = y_pos + term_offsets[term]
        ax.errorbar(
            tsub["coef"], ys,
            xerr=[tsub["coef"] - tsub["ci_low_95"], tsub["ci_high_95"] - tsub["coef"]],
            fmt="o", color=term_colors[term], capsize=3, markersize=5.5, label=term
        )
    ax.axvline(0.0, color="black", linestyle="--", linewidth=1.0)
    ax.set_yticks(y_pos)
    ax.set_yticklabels([dep_labels[d] for d in dep_order])
    ax.set_title("(B) League FE Coefficients (95% League-Clustered CIs, Post-3.19)")
    ax.set_xlabel("Coefficient Estimate (Log-Level Response)")
    ax.legend(loc="lower right", frameon=True, framealpha=0.9)

    fig.suptitle("Player Retention & Fixed-Effects Price Elasticities (Post-3.19)", fontsize=13, fontweight="bold", y=0.99)
    fig.tight_layout(rect=[0, 0, 1, 0.95])
    fig.savefig(FIG_DIR / "fig3_player_retention_and_elasticity.png")
    plt.close(fig)

    # ------------------------------------------------------------------
    # Figure 4: Divination Card vs Underlying Parity Ratios (2x2)
    # ------------------------------------------------------------------
    fig, axes = plt.subplots(2, 2, figsize=(13.5, 9.0))
    pair_axes = [
        ("HoM x9 / Mirror", axes[0, 0], (0.4, 3.85), "upper right"),
        ("Apothecary x5 / Mageblood", axes[0, 1], (0.5, 4.4), "upper left"),
        ("Doctor x8 / Headhunter", axes[1, 0], (0.3, 1.8), "upper right"),
        ("SYBL x13 / Mirror Shard", axes[1, 1], (0.6, 1.4), "upper right"),
    ]
    reg_styles = [
        ("pre_319", "Pre-3.19 (3.12-3.18)", "#7570b3"),
        ("post_319_pre_faustus", "3.19-3.24 Pre-Faustus", "#d95f02"),
        ("post_319_mf_323", "3.23 Affliction MF", "#e7298a"),
        ("faustus_325_plus", "3.25+ Faustus Era", "#1b9e77"),
    ]

    for pair_label, ax, ylim, leg_loc in pair_axes:
        sub = parity_daily[
            (parity_daily["pair"] == pair_label)
            & (parity_daily["is_extreme_outlier"] == 0)
            & (parity_daily["league_day"] >= 1)
            & (parity_daily["league_day"] <= 90)
        ]
        for rkey, rlabel, rcol in reg_styles:
            rsub = sub[sub["regime"] == rkey]
            if len(rsub) < 10:
                continue
            med_line = rsub.groupby("league_day")["parity_ratio"].median()
            # Smooth 5-day rolling median for readability while keeping true level
            med_smooth = med_line.rolling(5, min_periods=1, center=True).median()
            ax.plot(med_smooth.index, med_smooth.values, color=rcol, linewidth=2.0, label=f"{rlabel} (med={rsub['parity_ratio'].median():.2f})")
        ax.axhline(1.0, color="black", linestyle="--", linewidth=1.2, label="Exact Parity = 1.00")
        ax.set_title(pair_label)
        ax.set_xlabel("League Day")
        ax.set_ylabel("N * P_card / P_underlying")
        ax.set_xlim(1, 90)
        ax.set_ylim(ylim)
        ax.legend(loc=leg_loc, frameon=True, framealpha=0.92, fontsize=7.8)

    fig.suptitle("Divination Card vs Underlying Arbitrage Parity Ratios by Regime (Clean Sample, Days 1-90)", fontsize=13.5, fontweight="bold", y=0.99)
    fig.tight_layout(rect=[0, 0, 1, 0.965])
    fig.savefig(FIG_DIR / "fig4_parity_ratios.png")
    plt.close(fig)

    # ------------------------------------------------------------------
    # Figure 5: Lead-Lag Cross-Correlation Functions (Divine vs Chaos Comparison)
    # ------------------------------------------------------------------
    fig, axes = plt.subplots(2, 3, figsize=(13.8, 7.8), sharex=True, sharey="row")
    ccf_pairs = [
        "D/C -> Mirror/D",
        "D/C -> HoM/D",
        "Mirror/D -> HoM/D",
        "D/C -> Mirror/C",
        "D/C -> HoM/C",
        "Mageblood/C -> Apothecary/C",
    ]
    for idx, (ax, pname) in enumerate(zip(axes.flat, ccf_pairs)):
        sub = ccf_df[ccf_df["pair"] == pname].sort_values("lag_days")
        if sub.empty:
            continue
        band = 1.96 * sub["se_approx"].mean()
        colors = ["#e7298a" if abs(v) > band else "#4e79a7" for v in sub["pearson_r"]]
        ax.bar(sub["lag_days"], sub["pearson_r"], color=colors, width=0.65)
        ax.axhline(band, color="black", linestyle="--", linewidth=0.9, alpha=0.7)
        ax.axhline(-band, color="black", linestyle="--", linewidth=0.9, alpha=0.7)
        ax.axhline(0.0, color="black", linewidth=0.8)
        ax.axvline(0.0, color="gray", linestyle=":", linewidth=0.9)
        ax.set_title(pname, fontsize=10)
        if idx < 3:
            ax.set_ylim(-0.76, 0.98)
        else:
            ax.set_ylim(-0.16, 0.36)
    for ax in axes[1, :]:
        ax.set_xlabel("Lag k (Days; k>0 means X leads Y)")
    for ax in axes[:, 0]:
        ax.set_ylabel("Cross-Corr (Daily Log-Returns)")

    fig.suptitle("Lead-Lag Cross-Correlation of Daily Log-Returns (Post-3.19, Pink = |r| > 95% Band)", fontsize=13, fontweight="bold", y=0.99)
    fig.tight_layout(rect=[0, 0, 1, 0.955])
    fig.savefig(FIG_DIR / "fig5_lead_lag_ccf.png")
    plt.close(fig)

    # ------------------------------------------------------------------
    # Figure 6: Variance Decomposition & Feature Importance
    # ------------------------------------------------------------------
    fig, axes = plt.subplots(1, 2, figsize=(13.5, 6.0))

    # Panel A: Shapley R2 decomposition stacked bars
    ax = axes[0]
    t_order = [
        "ln_divine_chaos_post319",
        "ln_divine_chaos_all",
        "ln_mirror_divine_post319",
        "ln_mirror_chaos_all",
        "ln_hom_divine_post319",
        "ln_apothecary_divine_post319",
        "ln_doctor_divine_post319",
        "ln_sybl_divine_post319",
    ]
    t_labels = {
        "ln_divine_chaos_post319": "ln(D/C) [Post-3.19]",
        "ln_divine_chaos_all": "ln(D/C) [All 3.12-3.30]",
        "ln_mirror_divine_post319": "ln(Mirror/D) [Post-3.19]",
        "ln_mirror_chaos_all": "ln(Mirror/C) [All 3.12-3.30]",
        "ln_hom_divine_post319": "ln(HoM/D) [Post-3.19]",
        "ln_apothecary_divine_post319": "ln(Apothecary/D) [Post-3.19]",
        "ln_doctor_divine_post319": "ln(Doctor/D) [Post-3.19]",
        "ln_sybl_divine_post319": "ln(SYBL/D) [Post-3.19]",
    }
    piv_shap = vdec_df.pivot(index="target", columns="group", values="shapley_r2").reindex(t_order)
    y_idx = np.arange(len(t_order))
    left = np.zeros(len(t_order))
    grp_colors = {
        "Time_Lifecycle": "#1b9e77",
        "Players_Retention": "#d95f02",
        "Structural_Regimes": "#7570b3",
    }
    for gk in ["Time_Lifecycle", "Players_Retention", "Structural_Regimes"]:
        vals = piv_shap[gk].fillna(0).to_numpy()
        ax.barh(y_idx, vals, left=left, color=grp_colors[gk], label=gk.replace("_", " "))
        left += vals
    ax.set_yticks(y_idx)
    ax.set_yticklabels([t_labels[t] for t in t_order])
    ax.set_xlabel("Shapley R² Contribution (Total Bar = Full OLS R²)")
    ax.set_title("(A) Exact Shapley R² Variance Decomposition")
    ax.set_xlim(0, 1.0)

    # Panel B: 5-Fold OOF RF Permutation Importance Shares
    ax = axes[1]
    piv_rf = vdec_df.pivot(index="target", columns="group", values="rf_perm_share_pct").reindex(t_order)
    left = np.zeros(len(t_order))
    for gk in ["Time_Lifecycle", "Players_Retention", "Structural_Regimes"]:
        vals = piv_rf[gk].fillna(0).to_numpy()
        ax.barh(y_idx, vals, left=left, color=grp_colors[gk], label=gk.replace("_", " "))
        left += vals
    ax.set_yticks(y_idx)
    ax.set_yticklabels([t_labels[t] for t in t_order])
    ax.set_xlabel("5-Fold OOF RF Permutation Share (%)")
    ax.set_title("(B) Out-of-Fold RF Permutation Importance Share")
    ax.set_xlim(0, 100)

    handles, labels = axes[0].get_legend_handles_labels()
    fig.legend(handles, labels, loc="lower center", ncol=3, frameon=True, framealpha=0.95, bbox_to_anchor=(0.5, 0.015), fontsize=9.5)
    fig.suptitle("Drivers of PoE 1 Prices: Lifecycle Time vs Player Activity vs Structural Regimes", fontsize=13, fontweight="bold", y=0.985)
    fig.tight_layout(rect=[0, 0.075, 1, 0.945])
    fig.savefig(FIG_DIR / "fig6_variance_decomposition.png")
    plt.close(fig)


def main() -> None:
    econ, pf, ev = load_data()
    wide = build_wide_daily_panel(econ, pf, ev)

    cov_df = compute_coverage_summary(econ, pf, ev, wide)
    traj_df, infl_df = compute_lifecycle_trajectories(wide)
    reg_df = run_panel_econometrics(wide)
    parity_df, parity_reg_df, parity_daily = compute_parity_analysis(wide)
    ccf_df, granger_df = compute_lead_lag_and_granger(wide)
    vdec_df = compute_variance_decomposition(wide)

    make_figures(wide, traj_df, infl_df, reg_df, parity_daily, ccf_df, vdec_df, ev)

    print("Analysis complete:")
    print(f"  wide panel shape: {wide.shape}")
    print(f"  01_coverage_summary: {len(cov_df)} rows")
    print(f"  02_lifecycle_trajectories: {len(traj_df)} rows")
    print(f"  02b_early_vs_late_inflation: {len(infl_df)} rows")
    print(f"  03_panel_regressions: {len(reg_df)} rows")
    print(f"  04_parity_ratios: {len(parity_df)} rows")
    print(f"  04b_parity_regressions: {len(parity_reg_df)} rows")
    print(f"  05_lead_lag_ccf: {len(ccf_df)} rows")
    print(f"  05b_granger_tests: {len(granger_df)} rows")
    print(f"  06_variance_decomposition: {len(vdec_df)} rows")


if __name__ == "__main__":
    main()
