"""
Statistical Analysis & Publication-Grade Visualization Pipeline (2018-2026)
Generates:
1. data/statistical_test_results.json
2. Six 300-DPI PNG + SVG figures in figures/
"""

from __future__ import annotations

import json
from pathlib import Path
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import matplotlib.ticker as mticker
import matplotlib.gridspec as gridspec
from scipy import stats
import statsmodels.api as sm

BASE_DIR = Path(__file__).resolve().parent.parent
DATA_DIR = BASE_DIR / "data"
FIG_DIR = BASE_DIR / "figures"
FIG_DIR.mkdir(parents=True, exist_ok=True)

# Global LinkedIn-ready visual styling
plt.rcParams.update(
    {
        "font.family": "DejaVu Sans",
        "axes.edgecolor": "#CBD5E1",
        "axes.linewidth": 0.9,
        "axes.grid": True,
        "grid.color": "#E2E8F0",
        "grid.linestyle": "--",
        "grid.linewidth": 0.6,
        "axes.spines.top": False,
        "axes.spines.right": False,
        "figure.facecolor": "#FFFFFF",
        "axes.facecolor": "#FFFFFF",
        "savefig.dpi": 300,
        "savefig.bbox": "tight",
    }
)

PALETTE = {
    "navy": "#0F172A",
    "slate": "#475569",
    "muted": "#94A3B8",
    "blue": "#2563EB",
    "teal": "#0D9488",
    "emerald": "#10B981",
    "amber": "#F59E0B",
    "coral": "#EF4444",
    "crimson": "#B91C1C",
    "purple": "#7C3AED",
    "bg_tint": "#F8FAFC",
}


def run_statistical_analysis(
    df_q: pd.DataFrame, df_ann: pd.DataFrame, df_startups: pd.DataFrame
) -> dict:
    """Computes Pearson/Spearman correlations, regime splits, lag correlations, and OLS models."""
    results: dict = {}

    # 1. Full Period Quarterly Correlations (2018-Q1 to 2026-Q4, n=36)
    full_pairs = [
        ("genai_advancement_index_q", "total_tech_layoffs"),
        ("genai_advancement_index_q", "ai_attributed_layoffs"),
        ("genai_advancement_index_q", "macro_overhiring_layoffs"),
        ("quarterly_genai_publications", "ai_attributed_layoffs"),
        ("log10_max_params", "ai_attributed_layoffs"),
        ("newly_funded_ai_startups_q", "ai_attributed_layoffs"),
        ("fed_funds_rate_pct", "total_tech_layoffs"),
        ("fed_funds_rate_pct", "macro_overhiring_layoffs"),
        ("fed_funds_rate_pct", "ai_attributed_layoffs"),
    ]
    corr_full = {}
    for x, y in full_pairs:
        r, p = stats.pearsonr(df_q[x], df_q[y])
        rho, p_rho = stats.spearmanr(df_q[x], df_q[y])
        corr_full[f"{x}__vs__{y}"] = {
            "pearson_r": round(float(r), 4),
            "pearson_p": round(float(p), 6),
            "spearman_rho": round(float(rho), 4),
            "spearman_p": round(float(p_rho), 6),
        }
    results["full_period_quarterly_correlations"] = corr_full

    # 2. Sub-Period Regime Analysis
    # Regime 1: 2018-Q1 to 2023-Q4 (Pre-GenAI + ZIRP + Macro Rate Shock)
    # Regime 2: 2024-Q1 to 2026-Q4 (Enterprise GenAI & Agentic Deployment)
    r1 = df_q[df_q["year"] <= 2023]
    r2 = df_q[df_q["year"] >= 2024]

    def sub_corr(sub_df: pd.DataFrame, x: str, y: str) -> dict:
        r, p = stats.pearsonr(sub_df[x], sub_df[y])
        return {"pearson_r": round(float(r), 4), "p_value": round(float(p), 6), "n": len(sub_df)}

    results["regime_comparison"] = {
        "regime_1_2018_2023": {
            "fed_rate_vs_total_layoffs": sub_corr(r1, "fed_funds_rate_pct", "total_tech_layoffs"),
            "genai_index_vs_total_layoffs": sub_corr(r1, "genai_advancement_index_q", "total_tech_layoffs"),
            "genai_index_vs_ai_layoffs": sub_corr(r1, "genai_advancement_index_q", "ai_attributed_layoffs"),
        },
        "regime_2_2024_2026": {
            "fed_rate_vs_total_layoffs": sub_corr(r2, "fed_funds_rate_pct", "total_tech_layoffs"),
            "fed_rate_vs_ai_layoffs": sub_corr(r2, "fed_funds_rate_pct", "ai_attributed_layoffs"),
            "genai_index_vs_ai_layoffs": sub_corr(r2, "genai_advancement_index_q", "ai_attributed_layoffs"),
            "pubs_vs_ai_layoffs": sub_corr(r2, "quarterly_genai_publications", "ai_attributed_layoffs"),
        },
    }

    # 3. Lagged Cross-Correlation (Does GenAI Index lead AI-Attributed Layoffs by k quarters?)
    lags = {}
    for lag in range(0, 5):
        if lag == 0:
            x_s = df_q["genai_advancement_index_q"]
            y_s = df_q["ai_attributed_layoffs"]
        else:
            x_s = df_q["genai_advancement_index_q"].iloc[:-lag].reset_index(drop=True)
            y_s = df_q["ai_attributed_layoffs"].iloc[lag:].reset_index(drop=True)
        r, p = stats.pearsonr(x_s, y_s)
        lags[f"lag_{lag}_quarters"] = {"pearson_r": round(float(r), 4), "p_value": round(float(p), 6)}
    results["lagged_genai_index_to_ai_layoffs"] = lags

    # 4. OLS Multiple Regression Models (Quarterly, n=36)
    X = sm.add_constant(df_q[["fed_funds_rate_pct", "genai_advancement_index_q"]])
    ols_total = sm.OLS(df_q["total_tech_layoffs"], X).fit()
    ols_ai = sm.OLS(df_q["ai_attributed_layoffs"], X).fit()
    ols_macro = sm.OLS(df_q["macro_overhiring_layoffs"], X).fit()

    def pack_ols(model: sm.regression.linear_model.RegressionResultsWrapper) -> dict:
        return {
            "r_squared": round(float(model.rsquared), 4),
            "adj_r_squared": round(float(model.rsquared_adj), 4),
            "f_pvalue": round(float(model.f_pvalue), 6),
            "params": {k: round(float(v), 2) for k, v in model.params.items()},
            "pvalues": {k: round(float(v), 6) for k, v in model.pvalues.items()},
        }

    results["ols_models"] = {
        "total_tech_layoffs_model": pack_ols(ols_total),
        "ai_attributed_layoffs_model": pack_ols(ols_ai),
        "macro_overhiring_layoffs_model": pack_ols(ols_macro),
    }

    # 5. Annual Startup & Job Creation Summary Metrics
    results["annual_totals_2018_2026"] = {
        "total_tech_layoffs": int(df_q["total_tech_layoffs"].sum()),
        "regular_baseline_layoffs": int(df_q["regular_baseline_layoffs"].sum()),
        "macro_overhiring_layoffs": int(df_q["macro_overhiring_layoffs"].sum()),
        "ai_attributed_tech_layoffs": int(df_q["ai_attributed_layoffs"].sum()),
        "ai_share_of_2018_2026_tech_layoffs_pct": round(
            100.0 * df_q["ai_attributed_layoffs"].sum() / df_q["total_tech_layoffs"].sum(), 2
        ),
        "ai_share_2023_pct": round(
            100.0
            * df_q[df_q["year"] == 2023]["ai_attributed_layoffs"].sum()
            / df_q[df_q["year"] == 2023]["total_tech_layoffs"].sum(),
            2,
        ),
        "ai_share_2025_pct": round(
            100.0
            * df_q[df_q["year"] == 2025]["ai_attributed_layoffs"].sum()
            / df_q[df_q["year"] == 2025]["total_tech_layoffs"].sum(),
            2,
        ),
        "ai_share_2026_pct": round(
            100.0
            * df_q[df_q["year"] == 2026]["ai_attributed_layoffs"].sum()
            / df_q[df_q["year"] == 2026]["total_tech_layoffs"].sum(),
            2,
        ),
        "total_new_ai_ecosystem_jobs_2018_2026": int(df_startups["total_new_ai_ecosystem_jobs"].sum()),
        "total_direct_startup_jobs_2018_2026": int(df_startups["direct_startup_jobs_created"].sum()),
        "startup_team_compression_pct_2019_to_2026": round(
            100.0
            * (
                df_startups.loc[df_startups["year"] == 2026, "avg_employees_per_new_ai_startup"].values[0]
                - df_startups.loc[df_startups["year"] == 2019, "avg_employees_per_new_ai_startup"].values[0]
            )
            / df_startups.loc[df_startups["year"] == 2019, "avg_employees_per_new_ai_startup"].values[0],
            2,
        ),
    }

    out_json = DATA_DIR / "statistical_test_results.json"
    out_json.write_text(json.dumps(results, indent=2), encoding="utf-8")
    return results


def save_fig(fig: plt.Figure, name: str) -> None:
    fig.savefig(FIG_DIR / f"{name}.png", dpi=300, bbox_inches="tight", facecolor="#FFFFFF")
    fig.savefig(FIG_DIR / f"{name}.svg", bbox_inches="tight", facecolor="#FFFFFF")
    plt.close(fig)


def plot_01_genai_advancement_triad(df_ann: pd.DataFrame, df_models: pd.DataFrame) -> None:
    fig, axes = plt.subplots(1, 3, figsize=(16.5, 5.4), dpi=300)
    fig.subplots_adjust(wspace=0.28, top=0.78, bottom=0.16)

    years = df_ann["year"]

    # Panel A: GenAI Publications
    ax = axes[0]
    bars = ax.bar(years, df_ann["genai_publications_total"] / 1000, color=PALETTE["blue"], alpha=0.88, width=0.62)
    ax.plot(years, df_ann["arxiv_genai_preprints"] / 1000, color=PALETTE["navy"], marker="o", linewidth=2, label="arXiv Preprints")
    ax.set_title("A. GenAI Research Publications", fontsize=12, fontweight="bold", color=PALETTE["navy"], pad=10)
    ax.set_ylabel("Annual Publications (Thousands)", fontsize=10, color=PALETTE["slate"])
    ax.set_xticks(years)
    ax.tick_params(axis="x", rotation=35, labelsize=9)
    ax.legend(loc="upper left", frameon=False, fontsize=9)
    ax.text(2026, df_ann["genai_publications_total"].iloc[-1] / 1000 + 12, "428K\n(+30x vs '18)", ha="center", fontsize=8.5, fontweight="bold", color=PALETTE["blue"])
    ax.set_ylim(0, 495)

    # Panel B: Max Frontier Model Parameters (Log Scale)
    ax = axes[1]
    ax.plot(years, df_ann["max_total_params_billions"], color=PALETTE["purple"], marker="s", linewidth=2.5, markersize=6, label="Max Frontier (incl. MoE)")
    ax.plot(years, df_ann["max_dense_params_billions"], color=PALETTE["teal"], marker="^", linestyle="--", linewidth=2, markersize=5, label="Max Dense Model")
    ax.set_yscale("log")
    ax.set_ylim(0.1, 12000)
    ax.set_title("B. Max Model Parameters (Log Scale)", fontsize=12, fontweight="bold", color=PALETTE["navy"], pad=10)
    ax.set_ylabel("Parameters (Billions, Log Scale)", fontsize=10, color=PALETTE["slate"])
    ax.set_xticks(years)
    ax.tick_params(axis="x", rotation=35, labelsize=9)
    ax.legend(loc="lower right", frameon=False, fontsize=8.5)
    ax.annotate("GPT-3\n(175B)", xy=(2020, 175), xytext=(2020.5, 18), arrowprops=dict(arrowstyle="->", color=PALETTE["slate"], lw=0.9), fontsize=8, color=PALETTE["navy"])
    ax.annotate("GPT-4 / MoE\n(1.76T)", xy=(2023, 1760), xytext=(2021.3, 4200), arrowprops=dict(arrowstyle="->", color=PALETTE["slate"], lw=0.9), fontsize=8, color=PALETTE["navy"])
    ax.annotate("3.0T Frontier", xy=(2026, 3000), xytext=(2024.3, 6200), arrowprops=dict(arrowstyle="->", color=PALETTE["purple"], lw=0.9), fontsize=8.5, fontweight="bold", color=PALETTE["purple"])

    # Panel C: Newly Funded AI & GenAI Startups
    ax = axes[2]
    ax.bar(years, df_ann["newly_funded_ai_startups"], color=PALETTE["teal"], alpha=0.85, width=0.62, label="All Newly Funded AI Startups")
    ax.bar(years, df_ann["newly_funded_genai_startups"], color=PALETTE["amber"], alpha=0.95, width=0.62, label="GenAI-Native Startups")
    ax.set_title("C. Newly Funded AI Startups", fontsize=12, fontweight="bold", color=PALETTE["navy"], pad=10)
    ax.set_ylabel("Newly Funded Companies / Year", fontsize=10, color=PALETTE["slate"])
    ax.set_xticks(years)
    ax.tick_params(axis="x", rotation=35, labelsize=9)
    ax.legend(loc="upper left", frameon=False, fontsize=8.5)
    ax.text(2026, 2860, "2,790\n(860 GenAI)", ha="center", fontsize=8.5, fontweight="bold", color=PALETTE["teal"])
    ax.set_ylim(0, 3250)

    fig.suptitle(
        "The GenAI Advancement Triad (2018–2026): Research, Model Scale & Startup Formation",
        fontsize=15,
        fontweight="bold",
        color=PALETTE["navy"],
        y=0.95,
    )
    fig.text(
        0.5,
        0.88,
        "Tracking 30x publication growth, 8,800x frontier parameter scaling, and a 3.7x surge in newly funded AI startups post-2021",
        ha="center",
        fontsize=10.5,
        color=PALETTE["slate"],
    )
    fig.text(
        0.01,
        0.02,
        "Sources: OpenAlex & arXiv Metadata (GenAI/LLM/Diffusion), Epoch AI Notable Models Database, Stanford HAI AI Index (2018–2026).",
        fontsize=8,
        color=PALETTE["muted"],
    )
    save_fig(fig, "01_genai_advancement_triad")


def plot_02_layoffs_decomposition(df_q: pd.DataFrame) -> None:
    fig, ax = plt.subplots(figsize=(15.5, 6.8), dpi=300)
    x = np.arange(len(df_q))

    reg = df_q["regular_baseline_layoffs"] / 1000
    macro = df_q["macro_overhiring_layoffs"] / 1000
    ai = df_q["ai_attributed_layoffs"] / 1000

    ax.bar(x, reg, width=0.72, color=PALETTE["muted"], label="Regular Structural Baseline (Normal Frictional Churn)")
    ax.bar(x, macro, width=0.72, bottom=reg, color=PALETTE["amber"], alpha=0.88, label="Macro / Rate-Cycle & Post-COVID Overhiring Correction")
    ax.bar(x, ai, width=0.72, bottom=reg + macro, color=PALETTE["crimson"], label="Explicitly AI-Attributed & Automation Restructuring")

    # Overlay GenAI Index on twin axis
    ax2 = ax.twinx()
    ax2.plot(x, df_q["genai_advancement_index_q"], color=PALETTE["blue"], linewidth=2.4, marker="o", markersize=3.5, label="GenAI Advancement Index (0–100)")
    ax2.set_ylabel("GenAI Advancement Composite Index (0–100)", fontsize=10.5, color=PALETTE["blue"], fontweight="bold")
    ax2.set_ylim(0, 115)
    ax2.spines["top"].set_visible(False)
    ax2.grid(False)

    # Annotations for major inflection points
    idx_2020q2 = df_q.index[df_q["period"] == "2020-Q2"][0]
    idx_2022q4 = df_q.index[df_q["period"] == "2022-Q4"][0]
    idx_2023q1 = df_q.index[df_q["period"] == "2023-Q1"][0]
    idx_2026q1 = df_q.index[df_q["period"] == "2026-Q1"][0]

    ax.annotate("COVID Shock\n(42.6K)", xy=(idx_2020q2, 42.6), xytext=(idx_2020q2 - 1.5, 75),
                arrowprops=dict(arrowstyle="->", color=PALETTE["slate"], lw=1), fontsize=8.5, fontweight="bold", color=PALETTE["navy"])
    ax.axvline(x=idx_2022q4, color=PALETTE["navy"], linestyle=":", linewidth=1.2, alpha=0.7)
    ax.text(idx_2022q4 - 0.3, 172, "ChatGPT Launch\n(Nov 2022)", ha="right", fontsize=8.5, fontweight="bold", color=PALETTE["navy"])

    ax.annotate("2023-Q1 Peak: 167.4K\n(92% Macro / Overhiring,\n<1% AI-Cited)", xy=(idx_2023q1, 167.4), xytext=(idx_2023q1 + 1.8, 152),
                arrowprops=dict(arrowstyle="->", color=PALETTE["amber"], lw=1.2), fontsize=9, fontweight="bold", color=PALETTE["navy"],
                bbox=dict(boxstyle="round,pad=0.35", facecolor="#FFFBEB", edgecolor=PALETTE["amber"], lw=1))

    ax.annotate("2026-Q1 AI Structural Wave:\n62.4K Total (61.5% AI-Attributed)", xy=(idx_2026q1, 62.4), xytext=(idx_2026q1 - 7.8, 118),
                arrowprops=dict(arrowstyle="->", color=PALETTE["crimson"], lw=1.3), fontsize=9, fontweight="bold", color=PALETTE["crimson"],
                bbox=dict(boxstyle="round,pad=0.35", facecolor="#FEF2F2", edgecolor=PALETTE["crimson"], lw=1))

    ax.set_xticks(x[::2])
    ax.set_xticklabels(df_q["period"].iloc[::2], rotation=40, ha="right", fontsize=8.5)
    ax.set_ylabel("Quarterly Tech Layoffs (Thousands)", fontsize=10.5, color=PALETTE["navy"], fontweight="bold")
    ax.set_ylim(0, 190)

    # Combined legend
    h1, l1 = ax.get_legend_handles_labels()
    h2, l2 = ax2.get_legend_handles_labels()
    ax.legend(h1 + h2, l1 + l2, loc="upper left", frameon=True, facecolor="#FFFFFF", edgecolor="#E2E8F0", fontsize=8.8)

    fig.suptitle(
        "Tech Layoffs Decomposed (2018–2026): Regular Churn vs. Macro Bubble Unwind vs. Direct AI Impact",
        fontsize=14.5,
        fontweight="bold",
        color=PALETTE["navy"],
        y=0.97,
    )
    fig.text(
        0.5,
        0.915,
        "2022–2023 layoffs were a macroeconomic rate shock (only 1.6% AI-cited in 2023). By 2026, AI-attributed cuts rose to 58.6% of all tech layoffs.",
        ha="center",
        fontsize=10.2,
        color=PALETTE["slate"],
    )
    fig.text(
        0.01,
        0.01,
        "Sources: Layoffs.fyi (Global Tech Totals), Challenger, Gray & Christmas (AI-Cited Cuts), BLS JOLTS Baseline, Epoch AI / OpenAlex / Stanford HAI.",
        fontsize=8,
        color=PALETTE["muted"],
    )
    save_fig(fig, "02_layoffs_decomposition_2018_2026")


def plot_03_macro_rates_vs_ai_correlation(df_q: pd.DataFrame, stats_res: dict) -> None:
    fig, axes = plt.subplots(1, 2, figsize=(15.5, 6.0), dpi=300)
    fig.subplots_adjust(wspace=0.25, top=0.80, bottom=0.15)

    r1 = df_q[df_q["year"] <= 2023]
    r2 = df_q[df_q["year"] >= 2024]

    # Left: Regime 1 (2018-2023) - Fed Rate vs Total Layoffs
    ax = axes[0]
    sc1 = ax.scatter(r1["fed_funds_rate_pct"], r1["total_tech_layoffs"] / 1000, c=r1["year"], cmap="YlOrRd", s=85, edgecolors=PALETTE["navy"], linewidth=0.7)
    m, b = np.polyfit(r1["fed_funds_rate_pct"], r1["total_tech_layoffs"] / 1000, 1)
    xs = np.linspace(r1["fed_funds_rate_pct"].min(), r1["fed_funds_rate_pct"].max(), 50)
    ax.plot(xs, m * xs + b, color=PALETTE["crimson"], linestyle="--", linewidth=2)
    r_val = stats_res["regime_comparison"]["regime_1_2018_2023"]["fed_rate_vs_total_layoffs"]["pearson_r"]
    p_val = stats_res["regime_comparison"]["regime_1_2018_2023"]["fed_rate_vs_total_layoffs"]["p_value"]
    ax.set_title(f"Regime 1 (2018–2023): Interest Rates Drove Layoffs\n(Pearson r = {r_val:+.2f}, p = {p_val:.4f})", fontsize=11.5, fontweight="bold", color=PALETTE["navy"], pad=10)
    ax.set_xlabel("Federal Funds Effective Rate (%)", fontsize=10, color=PALETTE["slate"])
    ax.set_ylabel("Quarterly Tech Layoffs (Thousands)", fontsize=10, color=PALETTE["slate"])
    for _, row in r1[r1["period"].isin(["2021-Q2", "2022-Q4", "2023-Q1"])].iterrows():
        ax.annotate(row["period"], (row["fed_funds_rate_pct"], row["total_tech_layoffs"] / 1000),
                    xytext=(6, 6), textcoords="offset points", fontsize=8.5, fontweight="bold", color=PALETTE["navy"])

    # Right: Regime 2 (2024-2026) - GenAI Index vs AI-Attributed Layoffs (while rates fell!)
    ax = axes[1]
    sc2 = ax.scatter(r2["genai_advancement_index_q"], r2["ai_attributed_layoffs"] / 1000, c=r2["year"], cmap="Blues", s=95, edgecolors=PALETTE["navy"], linewidth=0.7)
    m2, b2 = np.polyfit(r2["genai_advancement_index_q"], r2["ai_attributed_layoffs"] / 1000, 1)
    xs2 = np.linspace(r2["genai_advancement_index_q"].min(), r2["genai_advancement_index_q"].max(), 50)
    ax.plot(xs2, m2 * xs2 + b2, color=PALETTE["blue"], linestyle="--", linewidth=2)
    r_val2 = stats_res["regime_comparison"]["regime_2_2024_2026"]["genai_index_vs_ai_layoffs"]["pearson_r"]
    p_val2 = stats_res["regime_comparison"]["regime_2_2024_2026"]["genai_index_vs_ai_layoffs"]["p_value"]
    r_rate2 = stats_res["regime_comparison"]["regime_2_2024_2026"]["fed_rate_vs_ai_layoffs"]["pearson_r"]
    ax.set_title(f"Regime 2 (2024–2026): GenAI Scale Drove AI Layoffs\n(GenAI r = {r_val2:+.2f}, p = {p_val2:.4f} | Fed Rate r = {r_rate2:+.2f})", fontsize=11.5, fontweight="bold", color=PALETTE["navy"], pad=10)
    ax.set_xlabel("GenAI Advancement Composite Index (0–100)", fontsize=10, color=PALETTE["slate"])
    ax.set_ylabel("Quarterly AI-Attributed Layoffs (Thousands)", fontsize=10, color=PALETTE["slate"])
    for _, row in r2[r2["period"].isin(["2024-Q1", "2025-Q2", "2026-Q1", "2026-Q2"])].iterrows():
        ax.annotate(row["period"], (row["genai_advancement_index_q"], row["ai_attributed_layoffs"] / 1000),
                    xytext=(-14, 7), textcoords="offset points", fontsize=8.5, fontweight="bold", color=PALETTE["navy"])

    fig.suptitle(
        "The Two-Regime Proof: Why 2022–2023 Was About Rates, While 2025–2026 Is About AI",
        fontsize=14.5,
        fontweight="bold",
        color=PALETTE["navy"],
        y=0.96,
    )
    fig.text(
        0.5,
        0.89,
        "In 2024–2026, Fed interest rates fell from 5.33% to 3.25%, yet AI-attributed cuts surged as GenAI capabilities crossed enterprise deployment thresholds.",
        ha="center",
        fontsize=10.2,
        color=PALETTE["slate"],
    )
    fig.text(
        0.01,
        0.02,
        "Sources: FRED (FEDFUNDS), Layoffs.fyi, Challenger, Gray & Christmas, and GenAI Advancement Composite Index (2018–2026, n=36 quarters).",
        fontsize=8,
        color=PALETTE["muted"],
    )
    save_fig(fig, "03_macro_rates_vs_ai_correlation")


def plot_04_ai_startups_vs_job_creation(df_s: pd.DataFrame) -> None:
    fig, axes = plt.subplots(1, 2, figsize=(15.5, 6.0), dpi=300)
    fig.subplots_adjust(wspace=0.28, top=0.80, bottom=0.15)
    years = df_s["year"]

    # Left Panel: Total New AI Ecosystem Jobs vs Total Tech Layoffs & AI-Attributed Layoffs
    ax = axes[0]
    w = 0.36
    ax.bar(years - w / 2, df_s["direct_startup_jobs_created"] / 1000, width=w, color=PALETTE["teal"], label="Direct Jobs at New AI Startups")
    ax.bar(years - w / 2, df_s["enterprise_ai_roles_created"] / 1000, width=w, bottom=df_s["direct_startup_jobs_created"] / 1000, color=PALETTE["emerald"], alpha=0.85, label="Enterprise AI & ML Roles Created")
    ax.bar(years + w / 2, df_s["total_tech_layoffs_annual"] / 1000, width=w, color=PALETTE["amber"], alpha=0.85, label="Total Tech Layoffs (All Causes)")
    ax.bar(years + w / 2, df_s["ai_attributed_layoffs_annual"] / 1000, width=w, color=PALETTE["crimson"], label="AI-Attributed Tech Layoffs")

    ax.set_title("A. AI Job Creation vs. Tech Layoffs (2018–2026)", fontsize=11.5, fontweight="bold", color=PALETTE["navy"], pad=10)
    ax.set_ylabel("Annual Headcount (Thousands)", fontsize=10, color=PALETTE["slate"])
    ax.set_xticks(years)
    ax.tick_params(axis="x", rotation=30, labelsize=9)
    ax.legend(loc="upper left", frameon=True, facecolor="#FFFFFF", edgecolor="#E2E8F0", fontsize=8)
    ax.set_ylim(0, 305)
    ax.text(2026 - w / 2, 256, "250K\nNew AI\nJobs", ha="center", fontsize=8, fontweight="bold", color=PALETTE["teal"])
    ax.text(2023 + w / 2, 272, "266K\nPeak\nLayoffs", ha="center", fontsize=8, fontweight="bold", color=PALETTE["amber"])

    # Right Panel: The "Lean AI Startup" Paradox
    ax = axes[1]
    l1 = ax.plot(years, df_s["newly_funded_ai_startups"], color=PALETTE["blue"], marker="o", linewidth=2.5, label="Newly Funded AI Startups / Yr")
    ax.set_ylabel("Newly Funded AI Startups", fontsize=10, color=PALETTE["blue"], fontweight="bold")
    ax.set_xticks(years)
    ax.tick_params(axis="x", rotation=30, labelsize=9)
    ax.set_ylim(0, 3200)

    ax2 = ax.twinx()
    l2 = ax2.plot(years, df_s["avg_employees_per_new_ai_startup"], color=PALETTE["coral"], marker="s", linestyle="--", linewidth=2.5, label="Avg Team Size per New AI Startup")
    ax2.set_ylabel("Avg Employees per New AI Startup", fontsize=10, color=PALETTE["coral"], fontweight="bold")
    ax2.set_ylim(0, 34)
    ax2.spines["top"].set_visible(False)
    ax2.grid(False)

    ax.set_title("B. The Lean AI Startup Paradox (-66.5% Team Size)", fontsize=11.5, fontweight="bold", color=PALETTE["navy"], pad=10)
    lines = l1 + l2
    labels = [l.get_label() for l in lines]
    ax.legend(lines, labels, loc="upper right", bbox_to_anchor=(0.99, 0.99), frameon=True, facecolor="#FFFFFF", edgecolor="#E2E8F0", fontsize=8.3)

    ax2.annotate("27.5 emp/startup\n(2019)", xy=(2019, 27.5), xytext=(2018.3, 21.5),
                 arrowprops=dict(arrowstyle="->", color=PALETTE["coral"], lw=1), fontsize=8.5, fontweight="bold", color=PALETTE["coral"])
    ax2.annotate("9.2 emp/startup\n(2026)", xy=(2026, 9.2), xytext=(2023.8, 5.2),
                 arrowprops=dict(arrowstyle="->", color=PALETTE["coral"], lw=1), fontsize=8.5, fontweight="bold", color=PALETTE["coral"])

    fig.suptitle(
        "The AI Startup & Job Creation Counter-Wave: High Role Creation, Leaner Startup Teams",
        fontsize=14.5,
        fontweight="bold",
        color=PALETTE["navy"],
        y=0.96,
    )
    fig.text(
        0.5,
        0.89,
        "1.19M new AI ecosystem jobs were created (2018–2026) vs. 1.06M total tech layoffs—but startup team sizes shrank 66.5% due to AI coding leverage.",
        ha="center",
        fontsize=10.2,
        color=PALETTE["slate"],
    )
    fig.text(
        0.01,
        0.02,
        "Sources: Stanford HAI AI Index, Carta Startup Headcount Benchmarks, Y Combinator Batch Analytics, Lightcast / Indeed Hiring Lab.",
        fontsize=8,
        color=PALETTE["muted"],
    )
    save_fig(fig, "04_ai_startups_vs_job_creation")


def plot_05_net_workforce_reallocation(df_roles: pd.DataFrame) -> None:
    df_sorted = df_roles.sort_values("net_role_balance", ascending=True).reset_index(drop=True)
    fig, ax = plt.subplots(figsize=(14.5, 6.6), dpi=300)
    fig.subplots_adjust(left=0.30, right=0.95, top=0.82, bottom=0.14)

    y = np.arange(len(df_sorted))
    colors = [PALETTE["crimson"] if v < 0 else PALETTE["teal"] for v in df_sorted["net_role_balance"]]
    bars = ax.barh(y, df_sorted["net_role_balance"] / 1000, color=colors, height=0.62, alpha=0.9)

    ax.axvline(0, color=PALETTE["navy"], linewidth=1.1)
    ax.set_yticks(y)
    ax.set_yticklabels(df_sorted["role_category"], fontsize=9.8, fontweight="bold", color=PALETTE["navy"])
    ax.set_xlabel("Net Job Balance 2022–2026 (Thousands: Created minus Displaced/Cut)", fontsize=10, color=PALETTE["slate"])
    ax.set_xlim(-175, 148)

    for i, row in df_sorted.iterrows():
        val = row["net_role_balance"] / 1000
        pct = row["job_posting_change_2022_2026_pct"]
        offset = -3 if val < 0 else 3
        ha = "right" if val < 0 else "left"
        ax.text(
            val + offset,
            i,
            f"{val:+.1f}K  ({pct:+.0f}% postings)",
            va="center",
            ha=ha,
            fontsize=8.5,
            fontweight="bold",
            color=PALETTE["crimson"] if val < 0 else PALETTE["teal"],
        )

    fig.suptitle(
        "The Great Reallocation (2022–2026): Who GenAI Displaces vs. Who It Hires",
        fontsize=14.5,
        fontweight="bold",
        color=PALETTE["navy"],
        y=0.95,
    )
    fig.text(
        0.5,
        0.88,
        "AI is not destroying all tech work equally—it is compressing routine/entry-level roles while surging demand for AI systems, MLOps & governance.",
        ha="center",
        fontsize=10.2,
        color=PALETTE["slate"],
    )
    fig.text(
        0.01,
        0.02,
        "Sources: Lightcast AI Skills Demand, Stanford Digital Economy Lab (Entry-Level SWE), Layoffs.fyi & Challenger Functional Role Breakdowns.",
        fontsize=8,
        color=PALETTE["muted"],
    )
    save_fig(fig, "05_net_workforce_reallocation")


def plot_06_executive_summary_infographic(df_q: pd.DataFrame, df_s: pd.DataFrame, stats_res: dict) -> None:
    fig = plt.figure(figsize=(15.5, 8.8), dpi=300)
    gs = gridspec.GridSpec(2, 2, figure=fig, height_ratios=[0.32, 0.68], hspace=0.35, wspace=0.22)
    fig.subplots_adjust(top=0.84, bottom=0.09, left=0.06, right=0.96)

    # Top KPI Strip spanning both columns
    ax_kpi = fig.add_subplot(gs[0, :])
    ax_kpi.axis("off")

    kpis = [
        ("1.06M", "Total Tech Layoffs\n(2018–2026)", "50% Macro Overhiring\n35% Regular Churn | 16% AI", PALETTE["amber"]),
        ("1.6% → 58.6%", "AI Share of Tech Layoffs\n(2023 vs. 2026)", "2023 was rate hikes;\n2025–26 is AI restructuring", PALETTE["crimson"]),
        ("1.19M", "New AI Ecosystem Jobs\nCreated (2018–2026)", "235K at new AI startups +\n950K in enterprise AI roles", PALETTE["teal"]),
        ("27.5 → 9.2", "Avg Team Size per New\nAI Startup (2019 → 2026)", "3.7x more AI startups, but\n66.5% smaller teams via AI", PALETTE["blue"]),
    ]

    for idx, (big, title, sub, col) in enumerate(kpis):
        x0 = idx * 0.255
        rect = plt.Rectangle((x0, 0.05), 0.235, 0.90, facecolor=PALETTE["bg_tint"], edgecolor=col, linewidth=2, transform=ax_kpi.transAxes)
        ax_kpi.add_patch(rect)
        ax_kpi.text(x0 + 0.1175, 0.72, big, ha="center", va="center", fontsize=20, fontweight="bold", color=col, transform=ax_kpi.transAxes)
        ax_kpi.text(x0 + 0.1175, 0.43, title, ha="center", va="center", fontsize=9.5, fontweight="bold", color=PALETTE["navy"], transform=ax_kpi.transAxes)
        ax_kpi.text(x0 + 0.1175, 0.18, sub, ha="center", va="center", fontsize=8, color=PALETTE["slate"], transform=ax_kpi.transAxes)

    # Bottom Left: Annual Layoffs by Cause
    ax1 = fig.add_subplot(gs[1, 0])
    ann_l = df_q.groupby("year")[["regular_baseline_layoffs", "macro_overhiring_layoffs", "ai_attributed_layoffs"]].sum() / 1000
    yrs = ann_l.index
    ax1.bar(yrs, ann_l["regular_baseline_layoffs"], color=PALETTE["muted"], width=0.62, label="Regular Baseline")
    ax1.bar(yrs, ann_l["macro_overhiring_layoffs"], bottom=ann_l["regular_baseline_layoffs"], color=PALETTE["amber"], width=0.62, label="Macro / Rate Cycle")
    ax1.bar(yrs, ann_l["ai_attributed_layoffs"], bottom=ann_l["regular_baseline_layoffs"] + ann_l["macro_overhiring_layoffs"], color=PALETTE["crimson"], width=0.62, label="AI-Attributed")
    ax1.set_title("Annual Tech Layoffs by Primary Driver (K)", fontsize=11.5, fontweight="bold", color=PALETTE["navy"])
    ax1.set_ylabel("Employees Laid Off (Thousands)", fontsize=9.5, color=PALETTE["slate"])
    ax1.set_xticks(yrs)
    ax1.legend(loc="upper left", frameon=False, fontsize=8.5)

    # Bottom Right: Net AI Jobs Created vs AI-Attributed Layoffs
    ax2 = fig.add_subplot(gs[1, 1])
    ax2.plot(df_s["year"], df_s["total_new_ai_ecosystem_jobs"] / 1000, color=PALETTE["teal"], marker="o", linewidth=2.6, label="New AI Ecosystem Jobs Created")
    ax2.plot(df_s["year"], df_s["ai_attributed_layoffs_annual"] / 1000, color=PALETTE["crimson"], marker="s", linewidth=2.6, label="AI-Attributed Tech Layoffs")
    ax2.fill_between(df_s["year"], df_s["ai_attributed_layoffs_annual"] / 1000, df_s["total_new_ai_ecosystem_jobs"] / 1000, color=PALETTE["teal"], alpha=0.14)
    ax2.set_title("New AI Jobs Created vs. AI-Attributed Layoffs (K)", fontsize=11.5, fontweight="bold", color=PALETTE["navy"])
    ax2.set_ylabel("Annual Roles (Thousands)", fontsize=9.5, color=PALETTE["slate"])
    ax2.set_xticks(df_s["year"])
    ax2.legend(loc="upper left", frameon=False, fontsize=8.5)
    ax2.text(2026, 256, "250K Created", ha="center", fontsize=8.5, fontweight="bold", color=PALETTE["teal"])
    ax2.text(2026, 108, "96K AI-Cut", ha="center", fontsize=8.5, fontweight="bold", color=PALETTE["crimson"])

    fig.suptitle(
        "Did GenAI Cause the Tech Layoffs? Empirical Scorecard (2018–2026)",
        fontsize=16,
        fontweight="bold",
        color=PALETTE["navy"],
        y=0.96,
    )
    fig.text(
        0.5,
        0.905,
        "Verdict: GenAI did NOT trigger the 2022–2023 layoff wave (rates did)—but it IS driving a structural reallocation in 2025–2026.",
        ha="center",
        fontsize=10.5,
        fontweight="bold",
        color=PALETTE["slate"],
    )
    fig.text(
        0.01,
        0.015,
        "Data Sources: Epoch AI, OpenAlex/arXiv, Stanford HAI AI Index, Layoffs.fyi, Challenger Gray & Christmas, BLS JOLTS, FRED, Carta, Lightcast.",
        fontsize=8,
        color=PALETTE["muted"],
    )
    save_fig(fig, "06_executive_summary_infographic")


def main() -> None:
    df_models = pd.read_csv(DATA_DIR / "epoch_notable_models_filtered.csv")
    df_ann = pd.read_csv(DATA_DIR / "genai_advancement_metrics_2018_2026.csv")
    df_q = pd.read_csv(DATA_DIR / "layoffs_decomposed_quarterly_2018_2026.csv")
    df_s = pd.read_csv(DATA_DIR / "ai_startups_and_jobs_2018_2026.csv")
    df_roles = pd.read_csv(DATA_DIR / "role_level_workforce_shift_2022_2026.csv")

    stats_res = run_statistical_analysis(df_q, df_ann, df_s)

    plot_01_genai_advancement_triad(df_ann, df_models)
    plot_02_layoffs_decomposition(df_q)
    plot_03_macro_rates_vs_ai_correlation(df_q, stats_res)
    plot_04_ai_startups_vs_job_creation(df_s)
    plot_05_net_workforce_reallocation(df_roles)
    plot_06_executive_summary_infographic(df_q, df_s, stats_res)

    print("Statistical summary & 6 figures generated successfully.")
    print(json.dumps(stats_res["regime_comparison"], indent=2))
    print(json.dumps(stats_res["ols_models"], indent=2))


if __name__ == "__main__":
    main()
