"""Figures of the solver report: pipeline diagram and the path of the scores."""
import matplotlib
matplotlib.use("Agg")
import matplotlib.pyplot as plt
from matplotlib.patches import FancyBboxPatch

plt.rcParams.update({"font.family": "DejaVu Sans", "font.size": 9})
INK, MUTED, ACC, ACC2, FILL = "#0b0b0b", "#52514e", "#184f95", "#b5591d", "#eef2f8"

# 1. pipeline
fig, ax = plt.subplots(figsize=(9.6, 4.6)); ax.set_xlim(0, 104); ax.set_ylim(0, 50); ax.axis("off")
def box(x, y, w, h, text, fc=FILL, ec=ACC, bold=False, fs=7.4):
    ax.add_patch(FancyBboxPatch((x, y), w, h, boxstyle="round,pad=0.3,rounding_size=1.2", fc=fc, ec=ec, lw=1.1))
    ax.text(x + w / 2, y + h / 2, text, ha="center", va="center", fontsize=fs, color=INK, weight="bold" if bold else "normal")
def arrow(x0, y0, x1, y1):
    ax.annotate("", (x1, y1), (x0, y0), arrowprops=dict(arrowstyle="->", color=MUTED, lw=1))
box(0.5, 20, 15, 10, "Cửa sổ 5 s\n4 kênh × 640 mẫu\nµV, chưa lọc", bold=True)
box(19, 20, 17.5, 10, "Low-pass 45 Hz\ncausal, giữ trạng thái\n1 s đầu bản ghi = 0", fs=7.1)
box(40, 33, 17, 10, "CNN 1-D, 4 block\nmean + max pooling\n→ 256 số")
box(40, 7, 17, 10, "217 feature STFT\nchuẩn hoá → MLP\n→ 64 số")
box(61, 20, 11, 10, "Linear\n320 → 96")
box(75.5, 20, 12, 10, "GRU 128\ngiữ trạng thái\ngiữa cửa sổ")
box(91, 20, 12.5, 10, "Head 121 lớp\n0, 5, …, 600 s")
for a in ((16.2, 25, 18.6, 25), (36.9, 27, 39.6, 37), (36.9, 23, 39.6, 13), (57.7, 38, 60.5, 28), (57.7, 12, 60.5, 22),
          (72.7, 25, 75, 25), (88.2, 25, 90.5, 25)):
    arrow(*a)
ax.text(38.5, 4.3, "(cột artifact tính từ tín hiệu thô)", fontsize=6.3, color=MUTED, ha="left")
box(61, 2, 42.5, 9, "× 8 model (seed 42-49): trung bình 8 phân phối\n→ TRUNG VỊ = số giây còn lại tới N2", fc="#fdf3ea", ec=ACC2, bold=True, fs=7.6)
arrow(97.2, 19.5, 97.2, 11.5)
ax.text(0.5, 47, "Suy luận: từng cửa sổ một theo thời gian; reset_state() giữa hai bản ghi", fontsize=8.5, color=INK, weight="bold")
ax.text(0.5, 43.5, "Chỉ lúc train: random start 0-3 phút, mask cửa sổ đầu,", fontsize=7.6, color=ACC2)
ax.text(0.5, 40.5, "mixup, gain, hoán đổi bán cầu, nhiễu Gauss", fontsize=7.6, color=ACC2)
fig.savefig("figures/fig1_pipeline.png", dpi=200, bbox_inches="tight"); plt.close(fig)

# 2. path of the scores
fig, (a1, a2) = plt.subplots(1, 2, figsize=(9.2, 3.3), gridspec_kw=dict(width_ratios=[1.45, 1]))
steps = [("CNN+GRU\n(chỉ thô)", 48.4), ("XGBoost\n+ feature", 46.9), ("CNN+feature\n+GRU", 42.2), ("+ low-pass\n45 Hz", 41.5),
         ("+ head\nphân phối", 41.0), ("+ E4 phần\nđầu bản ghi", 40.5), ("+ ensemble\n5 model", 39.6)]
a1.plot(range(len(steps)), [s[1] for s in steps], "o-", color=ACC, lw=1.6, ms=5)
for i, (n, v) in enumerate(steps):
    a1.text(i, v + 0.45, f"{v:.1f}", ha="center", fontsize=7.5, color=INK)
a1.set_xticks(range(len(steps))); a1.set_xticklabels([s[0] for s in steps], fontsize=6.6)
a1.set_ylabel("W-bMAE CV 5 fold (s)"); a1.set_title("CV theo người: từng bước của công thức", fontsize=9, loc="left")
a1.set_ylim(38.5, 50); a1.grid(axis="y", color="#e1e0d9", lw=0.6); a1.spines[["top", "right"]].set_visible(False)
subs = [("Ensemble\n5 model", 44.83), ("Ensemble\n8 model", 44.19), ("+ E4", 43.75), ("+ augment\n(A9M)", 43.07)]
a2.plot(range(len(subs)), [s[1] for s in subs], "o-", color=MUTED, lw=1.2, ms=5)
a2.plot([len(subs) - 1], [subs[-1][1]], "o", color=ACC2, ms=7)
for i, (n, v) in enumerate(subs):
    a2.text(i, v + 0.09, f"{v:.2f}", ha="center", fontsize=8, color=INK)
a2.set_xticks(range(len(subs))); a2.set_xticklabels([s[0] for s in subs], fontsize=7)
a2.set_ylim(42.6, 45.3); a2.set_xlim(-0.4, len(subs) - 0.6); a2.set_ylabel("W-bMAE test công khai (s)")
a2.set_title("Solver đã build (40 bản ghi)", fontsize=9, loc="left"); a2.grid(axis="y", color="#e1e0d9", lw=0.6)
a2.spines[["top", "right"]].set_visible(False)
fig.tight_layout(); fig.savefig("figures/fig2_scores.png", dpi=200, bbox_inches="tight"); plt.close(fig)
print("ok")
