#!/usr/bin/env python3
"""
Plotting script for spatial null test results.

Inputs:
- null_distributions.csv
- null_summary.csv

Outputs:
- fig_null_homo_dzdt.png
- fig_null_homo_variance.png
- fig_null_civ_dzdt.png
- fig_null_civ_variance.png
"""

import pandas as pd
import matplotlib.pyplot as plt

# ============================================================
# LOAD DATA
# ============================================================

df_null = pd.read_csv("null_distributions.csv")
df_sum  = pd.read_csv("null_summary.csv")

# Helper to extract observed values
def get_obs(metric, group):
    row = df_sum[df_sum["metric"] == metric]
    return row[f"obs_{group.lower()}"].values[0]

# ============================================================
# PLOTTING FUNCTION
# ============================================================

def plot_null(null_vals, obs_val, xlabel, title, fname):
    plt.figure(figsize=(6,4))

    plt.hist(
        null_vals,
        bins=40,
        density=True,
        alpha=0.7
    )

    plt.axvline(
        obs_val,
        linewidth=2,
        linestyle="--"
    )

    plt.xlabel(xlabel)
    plt.ylabel("Probability density")
    plt.title(title)
    plt.grid(alpha=0.3)

    plt.tight_layout()
    plt.savefig(fname, dpi=300)
    plt.close()

# ============================================================
# HOMO — |ΔZeff/Δt|
# ============================================================

plot_null(
    df_null["dz_homo"],
    get_obs("mean|dz/dt|", "homo"),
    xlabel="Mean |ΔZeff/Δt| (m / yr)",
    title="Null distribution: Early Homo\nsurface adjustment rate",
    fname="fig_null_homo_dzdt.png"
)

# ============================================================
# HOMO — VARIANCE OF ZERO-CONTOUR DISTANCE
# ============================================================

plot_null(
    df_null["var_homo"],
    get_obs("variance(zero-distance)", "homo"),
    xlabel="Variance of equilibrium-margin distance (deg²)",
    title="Null distribution: Early Homo\nspatial stability",
    fname="fig_null_homo_variance.png"
)

# ============================================================
# CIVILIZATIONS — |ΔZeff/Δt|
# ============================================================

plot_null(
    df_null["dz_civ"],
    get_obs("mean|dz/dt|", "civ"),
    xlabel="Mean |ΔZeff/Δt| (m / yr)",
    title="Null distribution: Early Civilizations\nsurface adjustment rate",
    fname="fig_null_civ_dzdt.png"
)

# ============================================================
# CIVILIZATIONS — VARIANCE OF ZERO-CONTOUR DISTANCE
# ============================================================

plot_null(
    df_null["var_civ"],
    get_obs("variance(zero-distance)", "civ"),
    xlabel="Variance of equilibrium-margin distance (deg²)",
    title="Null distribution: Early Civilizations\nspatial stability",
    fname="fig_null_civ_variance.png"
)

print("✓ Null-test figures generated")
