#!/usr/bin/env python3
"""make_japan_house_figures.py: figures and derived tables for the house-style Japan report.

Run from the repository root:
    python3 reports/japan-shocks-2026/make_japan_house_figures.py

Inputs (canonical source used by japan_cams_analysis.py):
    juno/Japan_CAMS_m5n_1850-2026_block1.csv  (ensemble means)
    juno/Japan_CAMS_m5n_1850-2026_block2.csv  (cross-agent envelope)
Operators: V = C + K - S + 0.5A; q_i = (0.6C_i + 0.4A_i)/10;
B_ij = sqrt(q_i q_j) * 2^(-(S_i+S_j)/10); node Bond Strength = mean of 7 pairwise bonds
(normalised CAMS calculator, as in data/v1.0_final_recompute/RECOMPUTE_REPORT.md).
"""
import os, json
import numpy as np, pandas as pd
import matplotlib
matplotlib.use("Agg")
import matplotlib.pyplot as plt
plt.rcParams["svg.hashsalt"] = "japan-house-2026"
plt.rcParams.update({"font.family": "DejaVu Sans", "font.size": 9, "svg.fonttype": "none"})

OUT = os.path.dirname(os.path.abspath(__file__))
NODES = ["Helm", "Shield", "Lore", "Stewards", "Craft", "Hands", "Archive", "Flow"]
COL = {"Helm": "#1B2A33", "Shield": "#C84C3E", "Lore": "#7B4F9D", "Stewards": "#D98B2B",
       "Craft": "#2F6F7D", "Hands": "#6B8E23", "Archive": "#8B5A2B", "Flow": "#1F77B4"}
sh = pd.read_csv(os.path.join(OUT, "japan_shock_comparison.csv"))
SHOCK_YEARS = sh.year.tolist()

b1 = pd.read_csv("juno/Japan_CAMS_m5n_1850-2026_block1.csv")
b2 = pd.read_csv("juno/Japan_CAMS_m5n_1850-2026_block2.csv")
assert len(b1) == 1416 and len(b2) == 1416
V = b1.Coherence + b1.Capacity - b1.Stress + 0.5 * b1.Abstraction
assert (V - b1["Node Value"]).abs().max() < 1e-9
b1["V"] = V

def bonds(g):
    g = g.set_index("Node").loc[NODES]
    q = ((0.6 * g.Coherence + 0.4 * g.Abstraction) / 10).values
    S = g.Stress.values
    B = np.sqrt(np.outer(q, q)) * 2 ** (-(S[:, None] + S[None, :]) / 10)
    np.fill_diagonal(B, np.nan)
    return pd.Series(np.nanmean(B, 1), index=NODES)

piv = lambda col: b1.pivot(index="Year", columns="Node", values=col)[NODES]
Vp = piv("V"); years = Vp.index.values
BS = b1.groupby("Year")[["Node", "Coherence", "Abstraction", "Stress"]].apply(bonds)[NODES]
env = b2.merge(b1[["Year", "Node", "V"]], on=["Year", "Node"])
Vmin = env.pivot(index="Year", columns="Node", values="V_min")[NODES]
Vmax = env.pivot(index="Year", columns="Node", values="V_max")[NODES]

# checks against the report's asserted values
sysV = Vp.mean(axis=1)
assert abs(sysV[1945] + 1.375) < 0.02 and abs(sysV[2020] - sysV[2019] + 4.71) < 0.02

def mark(ax, labels=False):
    for y in SHOCK_YEARS:
        ax.axvline(y, color="#9aa3ab", lw=0.6, ls=":", zorder=0)
    if labels:
        top = ax.get_ylim()[1]
        for y in SHOCK_YEARS:
            ax.text(y, top, str(y), rotation=90, fontsize=6.5, color="#5a6672", ha="right", va="top")

def save(fig, name):
    fig.savefig(os.path.join(OUT, name), format="svg", bbox_inches="tight", facecolor="white",
                metadata={"Date": None})
    plt.close(fig)

# Figure 1: node values, small multiples, Block 2 envelope band
fig, axes = plt.subplots(4, 2, figsize=(11, 10), sharex=True, sharey=True)
for ax, n in zip(axes.flat, NODES):
    ax.fill_between(years, Vmin[n], Vmax[n], color=COL[n], alpha=0.18, lw=0, label="Block 2 per-agent min to max")
    ax.plot(years, Vp[n], color=COL[n], lw=1.3, label="Ensemble mean V")
    ax.axhline(0, color="#1B2A33", lw=0.5)
    mark(ax)
    ax.set_title(n, loc="left", fontsize=10, fontweight="bold", color=COL[n])
    ax.grid(axis="y", color="#e3e7eb", lw=0.6)
    ax.spines[["top", "right"]].set_visible(False)
for ax in axes[:, 0]: ax.set_ylabel("Node Value V")
axes[0, 0].legend(fontsize=7, frameon=False, loc="upper left")
fig.suptitle("Figure 1. Japan node values, 1850-2026 (dotted lines: the twelve shock years of Table 1)", x=0.02, ha="left", fontsize=11, fontweight="bold")
fig.tight_layout(rect=(0, 0, 1, 0.97)); save(fig, "japan_fig1_node_values.svg")

# Figure 2: bond strength
fig, ax = plt.subplots(figsize=(11, 4.8))
for n in NODES: ax.plot(years, BS[n], color=COL[n], lw=1.1, label=n)
ax.set_ylim(0, None); mark(ax, labels=True)
ax.set_ylabel("Node Bond Strength (mean of 7 bonds)")
ax.grid(axis="y", color="#e3e7eb", lw=0.6); ax.spines[["top", "right"]].set_visible(False)
ax.legend(ncol=8, fontsize=7.5, frameon=False, loc="upper center", bbox_to_anchor=(0.5, -0.08))
ax.set_title("Figure 2. Bond Strength by node, normalised CAMS operator, m5n Block 1 means", loc="left", fontsize=11, fontweight="bold")
save(fig, "japan_fig2_bond_strength.svg")

# Figure 3: scoring dimensions heatmaps, common 1-10 scale
fig, axes = plt.subplots(4, 1, figsize=(11, 9.5), sharex=True)
for ax, (dim, lab) in zip(axes, [("Coherence", "Coherence C"), ("Capacity", "Capacity K"), ("Stress", "Stress S"), ("Abstraction", "Abstraction A")]):
    M = piv(dim).T.values
    im = ax.imshow(M, aspect="auto", cmap="viridis", vmin=1, vmax=10,
                   extent=(years[0] - 0.5, years[-1] + 0.5, len(NODES) - 0.5, -0.5), interpolation="nearest")
    ax.set_yticks(range(len(NODES))); ax.set_yticklabels(NODES, fontsize=7.5)
    ax.set_title(lab, loc="left", fontsize=9.5, fontweight="bold")
fig.colorbar(im, ax=axes, fraction=0.02, pad=0.01, label="Score (common 1-10 scale)")
fig.suptitle("Figure 3. Scoring dimensions by node and year, 1850-2026", x=0.02, ha="left", fontsize=11, fontweight="bold")
save(fig, "japan_fig3_dimensions_heatmap.svg")

# Figure 4: annual change in node value, diverging
D = Vp.diff()
lim = float(np.nanmax(np.abs(D.values)))
fig, ax = plt.subplots(figsize=(11, 3.6))
im = ax.imshow(D.T.values, aspect="auto", cmap="RdBu", vmin=-lim, vmax=lim,
               extent=(years[0] - 0.5, years[-1] + 0.5, len(NODES) - 0.5, -0.5), interpolation="nearest")
ax.set_yticks(range(len(NODES))); ax.set_yticklabels(NODES, fontsize=7.5)
ax.set_xticks(SHOCK_YEARS); ax.set_xticklabels(SHOCK_YEARS, rotation=90, fontsize=7)
fig.colorbar(im, ax=ax, fraction=0.02, pad=0.01, label="Change in V from previous year")
ax.set_title("Figure 4. Annual change in Node Value (blank first year; ticks mark the Table 1 shock years)", loc="left", fontsize=11, fontweight="bold")
save(fig, "japan_fig4_annual_change.svg")

# Figure 5: system mean V and weakest node, shocks marked
fig, ax = plt.subplots(figsize=(11, 4.4))
ax.plot(years, sysV, color="#2F6F7D", lw=1.6, label="System mean V (mean of 8 nodes)")
ax.plot(years, Vp.min(axis=1), color="#C84C3E", lw=1.0, label="Weakest node V")
ax.axhline(0, color="#1B2A33", lw=0.5)
ax.grid(axis="y", color="#e3e7eb", lw=0.6); ax.spines[["top", "right"]].set_visible(False)
mark(ax, labels=True)
ax.set_ylabel("Node Value V"); ax.legend(fontsize=8, frameon=False, loc="lower right")
ax.set_title("Figure 5. System mean and weakest node, 1850-2026, with the Table 1 shock years", loc="left", fontsize=11, fontweight="bold")
save(fig, "japan_fig5_system_trajectory.svg")

# Figure 6: analogue profiles and state-momentum map (from japan_analogues.csv)
an = pd.read_csv(os.path.join(OUT, "japan_analogues.csv")).dropna(subset=["dState", "dMom", "dSum"])
today = Vp.loc[2023:2026].mean()
wins = [("2002-2006", 2002, 2006), ("1880-1881", 1880, 1881), ("1952-1954", 1952, 1954), ("1925-1927", 1925, 1927)]
wcol = ["#2F6F7D", "#D98B2B", "#6B8E23", "#C84C3E"]
fig, (a1, a2) = plt.subplots(1, 2, figsize=(12, 4.8))
x = np.arange(len(NODES))
a1.plot(x, today.values, color="#1B2A33", lw=2.4, marker="o", label="Present, 2023-2026 mean")
for (lab, y0, y1), c in zip(wins, wcol):
    a1.plot(x, Vp.loc[y0:y1].mean().values, color=c, lw=1.2, marker=".", label=lab + " mean")
a1.set_xticks(x); a1.set_xticklabels(NODES, rotation=30, fontsize=8); a1.set_ylabel("Node Value V")
a1.grid(axis="y", color="#e3e7eb", lw=0.6); a1.spines[["top", "right"]].set_visible(False)
a1.legend(fontsize=7.5, frameon=False); a1.set_title("Present node profile against analogue windows", loc="left", fontsize=9.5, fontweight="bold")
top = an.sort_values("dSum").head(40)
a2.scatter(top.dState, top.dMom, s=18, color="#9aa3ab")
for _, r in top.sort_values("dSum").head(12).iterrows():
    a2.annotate(str(int(r.year)), (r.dState, r.dMom), fontsize=7, xytext=(3, 2), textcoords="offset points")
a2.set_xlabel("State distance to 2023-2026"); a2.set_ylabel("Momentum distance to 2023-2026")
a2.grid(color="#e3e7eb", lw=0.6); a2.spines[["top", "right"]].set_visible(False)
a2.set_title("State and momentum distance, 40 nearest years (12 nearest labelled)", loc="left", fontsize=9.5, fontweight="bold")
fig.suptitle("Figure 6. Analogues of the present configuration", x=0.02, ha="left", fontsize=11, fontweight="bold")
fig.tight_layout(rect=(0, 0, 1, 0.95)); save(fig, "japan_fig6_analogues.svg")

# Derived tables for the report page
rows = []
for _, r in sh.iterrows():
    y, n = int(r.year), r.failure_locus
    rows.append(dict(year=y, event=r.event, node=n, earlier=round(Vp.loc[y - 1, n], 2), later=round(Vp.loc[y, n], 2),
                     change=round(Vp.loc[y, n] - Vp.loc[y - 1, n], 2), table1_locus_dV=r.locus_dV))
cmp = pd.DataFrame(rows)
assert (cmp.change - cmp.table1_locus_dV).abs().max() < 0.06, cmp
cmp.to_csv(os.path.join(OUT, "japan_shock_locus_delta.csv"), index=False)
summ = dict(
    v1850=Vp.loc[1850].round(2).to_dict(), v2026=Vp.loc[2026].round(2).to_dict(),
    sys1850=round(sysV[1850], 2), sys2026=round(sysV[2026], 2),
    bs1850=BS.loc[1850].round(3).to_dict(), bs2026=BS.loc[2026].round(3).to_dict(),
    sd_mean={c: round(b2[c].mean(), 2) for c in ["C_sd", "K_sd", "S_sd", "A_sd"]},
    sd_2026={c: round(b2[b2.Year == 2026][c].mean(), 2) for c in ["C_sd", "K_sd", "S_sd", "A_sd"]},
    vrange_mean=round(b2.V_range.mean(), 2),
)
json.dump(summ, open(os.path.join(OUT, "japan_house_summary.json"), "w"), indent=1)
print(cmp.to_string()); print(json.dumps(summ, indent=1))
