"""依頼 400 の図 (python3. matplotlib). 入力 result_400.json・_data/eval_400.npy
  fig_phase_err_400.png   段階ごとの 爪の間の点の 予想 − 実際 (横・高さ. 今のシム / 入れたシム)
  fig_grasp_z_400.png     つかむ所の 爪の高さ (実際 − 指令) と 予想 (本ごとの点)
  fig_example_400.png     肩の指令が下がる本 1 本の 肩・肘・爪の高さ (指令・実際・予想)
"""
import json
from pathlib import Path

import matplotlib
import numpy as np

matplotlib.use("Agg")
import matplotlib.pyplot as plt  # noqa: E402

HERE = Path(__file__).resolve().parent
plt.rcParams["font.family"] = ["Hiragino Sans", "sans-serif"]
NONE_C, CH_C, REAL_C = "#9aa0a6", "#1f6feb", "#222222"
SET_JA = {"sv1_odd": "成功 50 本の奇数", "rec": "つかみ直し 25 回", "f": "so101f 30 回", "g": "so101g 7 回"}


def main():
    res = json.loads((HERE / "result_400.json").read_text())
    ch = res["chosen"]
    ev = np.load(HERE / "_data/eval_400.npy", allow_pickle=True)
    pj = res["phase_ja"]

    # 1. 段階ごと
    sets = ["sv1_odd", "rec", "f", "g"]
    fig, axes = plt.subplots(2, len(sets), figsize=(4.2 * len(sets), 7.5), sharey="row")
    for c, s in enumerate(sets):
        T0, T1 = res["sets"][s]["none"], res["sets"][s][ch]
        order = ["approach", "to_above", "recover", "descend", "close", "lift", "to_box", "return", "after"]
        phs = sorted([p for p in T0 if p != "all"], key=lambda p: order.index(p) if p in order else 99)
        x = np.arange(len(phs))
        for r, (key, lab) in enumerate((("horiz_med_mm", "横 (机の上) の差 中央値 mm"), ("z_med_abs_mm", "高さの差 |中央値| mm"))):
            ax = axes[r, c]
            ax.bar(x - 0.2, [T0[p][key] for p in phs], 0.4, color=NONE_C, label="今のシム (指令どおり)")
            ax.bar(x + 0.2, [T1[p][key] for p in phs], 0.4, color=CH_C, label=f"入れたシム ({ch})")
            ax.set_xticks(x, [pj.get(p, p) for p in phs], rotation=60, ha="right", fontsize=8)
            if c == 0:
                ax.set_ylabel(lab)
            if r == 0:
                ax.set_title(f"{SET_JA[s]}")
            ax.grid(axis="y", alpha=0.3)
    axes[0, 0].legend(fontsize=8)
    fig.suptitle("段階ごとの 爪の間の点 予想 − 実際 (全部のコマ)")
    fig.tight_layout()
    fig.savefig(HERE / "fig_phase_err_400.png", dpi=120)
    plt.close(fig)

    # 2. つかむ所の高さ
    G0 = {r["name"]: r for r in res["grasp"]["none"]["rows"]}
    G1 = {r["name"]: r for r in res["grasp"][ch]["rows"]}
    fig, axes = plt.subplots(1, 3, figsize=(16, 5.2))
    mk = {"sv1_even": ("o", "成功 偶数 (決めた本)"), "sv1_odd": ("s", "成功 奇数"), "rec": ("^", "つかみ直し"),
          "f": ("D", "so101f"), "g": ("P", "so101g")}
    ax = axes[0]
    for s, (m, lab) in mk.items():
        R = [G1[n] for n in G1 if G1[n]["set"] == s]
        col = ["#d1242f" if r["shoulder_cmd_change_descend_deg"] < 0 else "#1a7f37" for r in R]
        ax.scatter([r["real_minus_cmd_z"] for r in R], [r["pred_minus_cmd_z"] for r in R], marker=m, c=col, s=28,
                   alpha=0.8, label=lab, edgecolors="none")
    lim = [-24, 8]
    ax.plot(lim, lim, "k--", lw=0.8)
    ax.axhline(0, color=NONE_C, lw=2, label="今のシム (予想 0)")
    ax.set_xlim(lim), ax.set_ylim(lim)
    ax.set_xlabel("実際 − 指令 (つかむ所の爪の高さ mm)")
    ax.set_ylabel(f"予想 ({ch}) − 指令 mm")
    ax.set_title("赤 = 下りる間に肩の指令が下がる本・緑 = 上がる本")
    ax.legend(fontsize=7, loc="upper left")
    ax.grid(alpha=0.3)
    # 横のずれ
    for ax, k, ttl in ((axes[1], 0, "右"), (axes[2], 1, "奥")):
        for s, (m, lab) in mk.items():
            R = [n for n in G1 if G1[n]["set"] == s]
            ax.scatter([G1[n]["real_minus_cmd_rf"][k] for n in R], [G1[n]["pred_minus_cmd_rf"][k] for n in R], marker=m,
                       s=24, alpha=0.8, color=CH_C, edgecolors="none")
        lim2 = [-12, 12]
        ax.plot(lim2, lim2, "k--", lw=0.8)
        ax.axhline(0, color=NONE_C, lw=2)
        ax.set_xlim(lim2), ax.set_ylim(lim2)
        ax.set_xlabel(f"実際 − 指令 ({ttl} mm)")
        ax.set_ylabel(f"予想 − 指令 ({ttl} mm)")
        ax.set_title(f"つかむ所の横のずれ ({ttl})")
        ax.grid(alpha=0.3)
    fig.suptitle("つかむ所 (爪が実際に閉じたコマ) の 爪の間の点: 実際と予想 (1 点 = 1 本)")
    fig.tight_layout()
    fig.savefig(HERE / "fig_grasp_z_400.png", dpi=120)
    plt.close(fig)

    # 3. 例: 肩の指令が下がる本で 実際 − 指令 がいちばん大きい本 (確かめる本から)
    cand = [r for r in G0.values() if r["set"] != "sv1_even" and r["shoulder_cmd_change_descend_deg"] < 0]
    if not cand:
        cand = [r for r in G0.values() if r["shoulder_cmd_change_descend_deg"] < 0]
    pick = min(cand, key=lambda r: r["real_minus_cmd_z"])["name"]
    up = [r for r in G0.values() if r["set"] != "sv1_even" and r["shoulder_cmd_change_descend_deg"] > 0]
    pick2 = up[0]["name"] if up else None
    fig, axes = plt.subplots(3, 2, figsize=(13, 9), sharex="col")
    for c, nm in enumerate([pick, pick2]):
        if nm is None:
            continue
        e = next(e for e in ev if e["name"] == nm)
        ph = {n: (a, b) for n, a, b in e["phases"]}
        a0, b0 = ph["descend"][0] - 20, ph["lift"][1] + 10
        t = np.arange(a0, b0)
        Q1 = e["models"][ch]["jerr"] + e["state"][1:, :5]
        for r, (j, lab) in enumerate(((1, "肩 (度)"), (2, "肘 (度)"))):
            ax = axes[r, c]
            ax.plot(t, e["sent"][t, j], color=NONE_C, ls="--", label="指令 (= 今のシム)")
            ax.plot(t, e["state"][t + 1, j], color=REAL_C, label="実際")
            ax.plot(t, Q1[t, j], color=CH_C, label=f"予想 ({ch})")
            ax.set_ylabel(lab)
            ax.grid(alpha=0.3)
        ax = axes[2, c]
        ax.plot(t, e["P_sent"][t, 2], color=NONE_C, ls="--")
        ax.plot(t, e["P_state"][t + 1, 2], color=REAL_C)
        ax.plot(t, e["models"][ch]["Pq"][t, 2], color=CH_C)
        ax.set_ylabel("爪の間の点の高さ (mm)")
        ax.set_xlabel("コマ")
        for k, v in ph.items():
            if a0 <= v[0] <= b0:
                for a in axes[:, c]:
                    a.axvline(v[0], color="#bbb", lw=0.7)
                axes[0, c].text(v[0], axes[0, c].get_ylim()[1], pj.get(k, k), fontsize=7, va="bottom")
        axes[0, c].set_title(f"{nm} ({'肩の指令が下がる' if c == 0 else '肩の指令が上がる'})", pad=14)
    axes[0, 0].legend(fontsize=8)
    fig.tight_layout()
    fig.savefig(HERE / "fig_example_400.png", dpi=120)
    plt.close(fig)
    print("[WROTE] figs", pick, pick2)


if __name__ == "__main__":
    main()
