"""Figures made specifically for the onboarding guide (all computed from the data / the verified scorer port).

  figures/g1_avgc_label_timeline.png   KUL-AV-GC ground truth of one real trial: talker constant, side flips at 300 s
  figures/g2_scorer_quirk.png          the official scorer (Python port) on a PERFECT decoder, reverting switch 40 s vs 60 s later
  figures/g3_front_end.png             recommended causal front end and how the 1-s lookahead budget is spent
  figures/ds_fig*.png                  the example-trial figures embedded in 'EEG-sAAD Data Story.html' (extracted as-is)
"""
import base64
import os
import re
import sys

import matplotlib

matplotlib.use("Agg")
import matplotlib.pyplot as plt  # noqa: E402
import numpy as np  # noqa: E402
from matplotlib.patches import FancyBboxPatch  # noqa: E402

HERE = os.path.dirname(os.path.abspath(__file__))
ROOT = os.path.abspath(os.path.join(HERE, "..", ".."))
FIG = os.path.join(HERE, "figures")
sys.path.insert(0, os.path.join(ROOT, "reports", "eda_full", "scripts"))
from scorer import compute_switch_latency  # noqa: E402

os.makedirs(FIG, exist_ok=True)
RED = "#d62728"

# ---------------------------------------------------------------- g1: KUL-AV-GC labels of one real trial
z = np.load(os.path.join(ROOT, "reports/eda_full/cache/cnd/dataset-001-subject-001-trial-001.npz"), allow_pickle=True)
fs = 128
t = np.arange(len(z["att_col"])) / fs
az = z["att_az"].astype(float)
fig, axs = plt.subplots(3, 1, figsize=(9, 4.6), sharex=True, gridspec_kw=dict(hspace=0.55))
axs[0].step(t, z["att_stream"], color=RED, where="post")
axs[0].set_yticks([1, 2], ["stream 1", "stream 2"])
axs[0].set_ylim(0.5, 2.5)
axs[0].set_title("Attended TALKER (CND attendedStream): constant for the whole trial", fontsize=9, loc="left")
axs[1].step(t, np.sign(az), color=RED, where="post")
axs[1].set_yticks([-1, 1], ["left (-90°)", "right (+90°)"])
axs[1].set_ylim(-1.6, 1.6)
axs[1].set_title("Attended SIDE (CND attendedAzimuth): flips at t = 300 s (the talkers swap sides)", fontsize=9, loc="left")
lab = str(z["cond"])
trial_label = np.sign(az[0])
axs[2].step(t, np.full_like(t, trial_label), color="gray", where="post")
axs[2].fill_between(t, -1.6, 1.6, where=np.sign(az) != trial_label, color="#fbe3e3", step="post")
axs[2].set_yticks([-1, 1], ["left", "right"])
axs[2].set_ylim(-1.6, 1.6)
axs[2].set_title("Trial-level label in metadata.pkl (side at onset): wrong for the shaded half", fontsize=9, loc="left")
axs[2].set_xlabel("time in trial (s)")
for a in axs:
    a.axvline(300, color="k", lw=0.6, ls=":")
    a.spines[["top", "right"]].set_visible(False)
fig.suptitle(f"KUL-AV-GC subject 1, trial 1 ({lab}); the same pattern holds in all 99 trials", fontsize=10)
fig.savefig(os.path.join(FIG, "g1_avgc_label_timeline.png"), dpi=150, bbox_inches="tight")
plt.close(fig)

# ---------------------------------------------------------------- g2: scorer quirk on a PERFECT decoder
fs2 = 10
fig, axs = plt.subplots(2, 1, figsize=(9, 4.4), sharex=True, gridspec_kw=dict(hspace=0.7))
for ax, gap in zip(axs, (40, 60)):
    n = int(300 * fs2)
    gt = np.zeros(n)
    s1, s2 = 50 * fs2, (50 + gap) * fs2
    gt[s1:s2] = 1
    L, ell, sdt, tau, nov = compute_switch_latency(gt, gt, [s1, s2], fs2)
    tt = np.arange(n) / fs2
    ax.step(tt, gt, color="k", where="post", lw=1.2, label="ground truth = prediction (perfect decoder)")
    ax.axvspan(50, 150, color="#e8eef5", label="search window of switch 1 [t0, t0 + 100 s]")
    res1 = "UNDETECTED (SDT = Inf, score 0)" if np.isinf(sdt[0]) else f"detected, SDT = {sdt[0]:.1f} s"
    ax.set_title(f"Next (reverting) switch {gap} s later -> switch 1: {res1}; switch 2: SDT = {sdt[1]:.1f} s",
                 fontsize=9, loc="left", color=(RED if np.isinf(sdt[0]) else "#2e7d32"))
    ax.set_yticks([0, 1], ["talker A", "talker B"])
    ax.set_ylim(-0.3, 1.5)
    ax.spines[["top", "right"]].set_visible(False)
    if gap == 40:
        ax.legend(fontsize=7, loc="upper right", frameon=False)
axs[1].set_xlabel("time (s)")
fig.suptitle("Official scorer (verified Python port) applied to a decoder that is right on every sample", fontsize=10)
fig.savefig(os.path.join(FIG, "g2_scorer_quirk.png"), dpi=150, bbox_inches="tight")
plt.close(fig)

# ---------------------------------------------------------------- g3: front end + lookahead budget
steps = ["raw EEG\n128 Hz", "match channels\nby name\n(common 57)", "causal HP 0.5 Hz\n(state-initialised)",
         "common average\nreference", "causal BP 1-9 Hz\n+ anti-alias,\n-> 32 Hz", "running robust\nz-score\n(30 s, clip ±5)",
         "drop 1-s\nwarm-up", "backward decoder\nEEG lags 0-500 ms", "1-s correlation\nwindows,\n0.25-s hop",
         "causal integrator\n(MA / HMM)", "one label per\n128 Hz sample"]
fig, ax = plt.subplots(figsize=(10, 4.6))
ax.set_xlim(0, 7.2)
ax.set_ylim(-2.25, 2.9)
ax.axis("off")
rows = [(steps[:7], 1.55, "#e8eef5", "FRONT END (per trial, causal)"), (steps[7:], -0.05, "#e7f3e8", "DECODING (input = front-end output)")]
for r, (items, y, col, title) in enumerate(rows):
    ax.text(0.05, y + 1.2, title, fontsize=8, fontweight="bold", color="#1f3a5f")
    for i, s_ in enumerate(items):
        c = "#fde2e2" if (r == 1 and i == 0) else col
        ax.add_patch(FancyBboxPatch((i * 1.02 + 0.05, y), 0.9, 1.0, boxstyle="round,pad=0.02", fc=c, ec="#5a6b80", lw=0.8))
        ax.text(i * 1.02 + 0.5, y + 0.5, s_, ha="center", va="center", fontsize=7.2)
        if i < len(items) - 1:
            ax.annotate("", xy=(i * 1.02 + 1.07, y + 0.5), xytext=(i * 1.02 + 0.95, y + 0.5),
                        arrowprops=dict(arrowstyle="->", lw=0.8))
ax.text(4.2, 0.45, "The same causal filters and z-score\nare applied to both speech envelopes.", fontsize=7, color="#5a6b80")
# budget bar
ax.text(0.05, -0.75, "How the 1-s lookahead budget is spent", fontsize=8, fontweight="bold", color="#1f3a5f")
ax.add_patch(plt.Rectangle((0.05, -1.45), 3.0, 0.5, fc="#fbe3e3", ec="k", lw=0.6))
ax.add_patch(plt.Rectangle((3.05, -1.45), 3.0, 0.5, fc="#fff2cc", ec="k", lw=0.6))
ax.text(1.55, -1.2, "decoder: EEG up to 500 ms after\neach envelope sample", ha="center", va="center", fontsize=7)
ax.text(4.55, -1.2, "decision labels samples from\n500 ms before its window end", ha="center", va="center", fontsize=7)
ax.text(6.12, -1.2, "= 1000 ms", ha="left", va="center", fontsize=8, fontweight="bold")
ax.text(0.05, -1.95, "Filters, CAR, z-score and integrator are causal: they add delay, not lookahead.\n"
        "Zero-phase (filtfilt) filtering would read the future and is NOT allowed at test time.", fontsize=7, color="#444444")
fig.savefig(os.path.join(FIG, "g3_front_end.png"), dpi=150, bbox_inches="tight")
plt.close(fig)

# ---------------------------------------------------------------- example-trial figures from the Data Story
html = open(os.path.join(ROOT, "EEG-sAAD Data Story.html"), encoding="utf-8", errors="replace").read()
for i, m in enumerate(re.finditer(r'<img[^>]*src="data:image/png;base64,([^"]+)"', html)):
    open(os.path.join(FIG, f"ds_fig{i + 1}.png"), "wb").write(base64.b64decode(m.group(1)))
print("figures written to", FIG)
