"""依頼 386 の図. system の python3 で動く.
読むもの: traj_386.npy (explore_386.py)・result_386.json (analyze_386.py). 書くもの: so101/check_386/fig_*.png"""
import json
from pathlib import Path

import matplotlib
import numpy as np

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

import analyze_386 as A  # noqa: E402

HERE = Path(__file__).resolve().parent
plt.rcParams["font.family"] = "Hiragino Sans"
C_OK, C_NG, C_DEMO = "#2a6fdb", "#e07b00", "#555555"
HS = [int(h) for h in A.H_GRID if h >= 10]


def demo_profiles(demo):
    """お手本 success_v1 の 実際の関節 (state) の 最初に下りる道 (GRASP_CLOSED まで) の 高さごとの 横のずれ・向きのずれ"""
    lat, yaw = [], []
    for e in demo.values():
        if e["kind"] != "success_v1":
            continue
        byaw = e["read_yaw"] if e["read_yaw"] is not None else e["yaw_plan"]
        lo = int(np.argmax(e["Ps"][:e["kf"]["ABOVE_BLOCK"], 2]))
        a, b = [], []
        for h in HS:
            k = A.cross(e["Ps"][:, 2], h, lo, e["kf"]["GRASP_CLOSED"])
            q = None if k is None or k == lo else A.point(e["Ps"], e["Js"], k, e["xy0"], byaw)
            a.append(np.nan if q is None else q["lat"])
            b.append(np.nan if q is None else q["yaw"])
        lat.append(a)
        yaw.append(b)
    return np.array(lat), np.array(yaw)


def fig_height(res, demo):
    P = res["real_profiles_grid"]
    dl, dy = demo_profiles(demo)
    fig, axs = plt.subplots(1, 2, figsize=(13, 6.5), sharey=True)
    for ax, key, dd, xmax, xl in ((axs[0], "lat", dl, 90, "ブロックとの横のずれ (mm)"), (axs[1], "yaw", dy, 16, "爪の向きのずれ (度)")):
        for n, p in P.items():
            if p["model"] != "so101f":
                continue
            x = [p[key].get(str(h)) for h in HS]
            x = [np.nan if v is None else v for v in x]
            ax.plot(x, HS, c=C_OK if p["result"] == "success" else C_NG, lw=0.9, alpha=0.55)
        for res_, c, lab in (("success", C_OK, "so101f 成功 12 回 (中央値)"), ("failure", C_NG, "so101f 失敗 18 回 (中央値)")):
            m = [res["real_table"][f"so101f_{res_}"][str(h)][key] for h in HS]
            ax.plot([np.nan if v is None else v["median"] for v in m], HS, c=c, lw=3, label=lab)
        ax.fill_betweenx(HS, np.nanpercentile(dd, 0, axis=0), np.nanpercentile(dd, 100, axis=0), color=C_DEMO, alpha=0.18,
                         label="コードの道 (お手本 50 本の実際) 最小〜最大")
        ax.plot(np.nanmedian(dd, 0), HS, c=C_DEMO, lw=3, ls="--", label="コードの道 中央値")
        for h, lab in ((55.5, "候補 B (50)"), (85.5, "候補 A (80)"), (35.5, "候補 C (30)"), (20.5, "候補 D (15)")):
            ax.axhline(h, c="#999", lw=0.8, ls=":")
            ax.text(xmax * 0.98, h + 1, lab, ha="right", fontsize=8, color="#666")
        ax.set_xlim(0, xmax)
        ax.set_ylim(5, 150)
        ax.set_xlabel(xl)
        ax.grid(alpha=0.3)
    axs[0].set_ylabel("爪の間の点の高さ − ブロックの真ん中 (mm)")
    axs[0].legend(fontsize=8, loc="upper right")
    axs[0].set_title("横のずれ (最初に下りる道. 細い線 = 1 回ずつ)")
    axs[1].set_title("爪の向きのずれ (90° で同じ)")
    fig.suptitle("依頼 386: 高さごとのずれ — π0.5 (so101f 実機 30 回) とコードの道 (お手本 success_v1 50 本)")
    fig.tight_layout()
    fig.savefig(HERE / "fig_height_lat.png", dpi=110)
    plt.close(fig)


def fig_cand(res):
    C = res["candidates"]
    keys = ["80", "50", "30", "15"]
    labs = [f"{k} mm\n(点 {C[k]['h_center_mm']:.0f})" for k in keys]
    fig, axs = plt.subplots(1, 3, figsize=(15, 5))
    ab = [C[k]["so101f"]["fail_above"] for k in keys]
    be = [C[k]["so101f"]["fail_below"] for k in keys]
    nv = [C[k]["so101f"]["fail_never"] for k in keys]
    x = np.arange(len(keys))
    axs[0].bar(x, ab, color="#2ca02c", label="上で外れ始めた (コードが受け持てば消える見込み)")
    axs[0].bar(x, be, bottom=ab, color="#ff9f40", label="下で外れ始めた (π0.5 しだい)")
    axs[0].bar(x, nv, bottom=np.add(ab, be), color="#bbbbbb", label="最後まで成功の幅の中 (閉じ方・高さ. 消えない)")
    for i in range(len(keys)):
        axs[0].text(i, ab[i] / 2, str(ab[i]), ha="center", va="center", color="white")
    axs[0].set_xticks(x, labs)
    axs[0].set_ylabel("so101f の失敗 (回. 全 18)")
    axs[0].set_title("渡す高さ (つかむ所から真上) と so101f の失敗")
    axs[0].set_ylim(0, 26)
    axs[0].legend(fontsize=8, loc="upper center")
    s_close = [C[k]["pi_to_close_s"]["median"] for k in keys]
    s_lift = [C[k]["pi_to_lift_s"]["median"] for k in keys]
    axs[1].bar(x - 0.2, s_close, 0.4, color=C_OK, label="閉じ終わりまで")
    axs[1].bar(x + 0.2, s_lift, 0.4, color="#7aa6f0", label="持ち上げ (LIFT) まで")
    axs[1].set_xticks(x, labs)
    axs[1].set_ylabel("秒 (お手本 64 本の中央値)")
    axs[1].set_title("π0.5 が受け持つ長さ")
    axs[1].legend(fontsize=8)
    left = [C[k]["frames_left_total"] for k in keys]
    lift = [C[k]["frames_left_to_lift_total"] for k in keys]
    axs[2].bar(x - 0.2, left, 0.4, color="#8e44ad", label="渡す所から最後まで")
    axs[2].bar(x + 0.2, lift, 0.4, color="#c39bd3", label="渡す所から持ち上げまで")
    axs[2].axhline(C["50"]["frames_all_total"], c="#999", ls="--", lw=1)
    axs[2].text(3.4, C["50"]["frames_all_total"], f"今 {C['50']['frames_all_total']:,} コマ", ha="right", va="bottom", fontsize=8)
    axs[2].set_xticks(x, labs)
    axs[2].set_ylabel("コマ (お手本 64 本の合計)")
    axs[2].set_title("お手本を渡す所で切ったときに残るコマ")
    axs[2].legend(fontsize=8)
    fig.tight_layout()
    fig.savefig(HERE / "fig_candidates.png", dpi=110)
    plt.close(fig)


def fig_lag(res):
    T = res["demo_table"]["success_v1"]
    hs = ["120", "80", "50", "30", "15"]
    fig, ax = plt.subplots(figsize=(8, 4.5))
    for key, c, lab in (("cmd_state_d3", "#d62728", "指令と実際の 爪の間の点の差 (同じコマ)"), ("state_lat", C_DEMO, "実際の爪の間の点とブロック (横)"),
                        ("cmd_lat_vs_block", "#1f77b4", "指令の爪の間の点とブロック (横)")):
        m = [T[h][key]["median"] for h in hs]
        lo_ = [T[h][key]["p25"] for h in hs]
        hi_ = [T[h][key]["p75"] for h in hs]
        ax.errorbar(range(len(hs)), m, yerr=[np.subtract(m, lo_), np.subtract(hi_, m)], marker="o", c=c, capsize=4, label=lab)
    ax.set_xticks(range(len(hs)), [f"{h} mm" for h in hs])
    ax.set_xlabel("高さ (爪の間の点 − ブロックの真ん中)")
    ax.set_ylabel("mm (中央値と 25〜75%)")
    ax.set_title("コードの道 (お手本 success_v1 50 本) の 高さごとの差")
    ax.grid(alpha=0.3)
    ax.legend(fontsize=8)
    fig.tight_layout()
    fig.savefig(HERE / "fig_code_accuracy.png", dpi=110)
    plt.close(fig)


def main():
    res = json.loads((HERE / "result_386.json").read_text())
    d = np.load(HERE / "traj_386.npy", allow_pickle=True).item()
    fig_height(res, d["demo"])
    fig_cand(res)
    fig_lag(res)


if __name__ == "__main__":
    main()
