"""依頼 376 の図 (上から見た図. ブロックを真ん中に. 横 = 右 (根元から奥を見て), 縦 = 奥). system の python3 で動く.
読むもの: traj_376.npy (explore_376.py)・result_376.json (analyze_376.py). 書くもの: so101/check_376/fig_*.png"""
import json
from pathlib import Path

import matplotlib
import numpy as np

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

import analyze_376 as A  # noqa: E402

HERE = Path(__file__).resolve().parent
plt.rcParams["font.family"] = "Hiragino Sans"
C_OK, C_NG = "#2a6fdb", "#e07b00"
C_DEMO, C_DET = "#8a8a8a", "#8e44ad"
DIR_C = {"右": "#d62728", "左": "#2ca02c", "奥": "#1f77b4", "手前": "#9467bd", "その場": "#7f7f7f"}
LIM_R, LIM_F = (-90, 130), (-90, 90)


def base(ax, title, box_dir=None):
    ax.add_patch(Rectangle((-10.85, -10.85), 21.7, 21.7, fc="#f4b6b6", ec="#c0392b", lw=1, zorder=1))
    ax.axhline(0, c="#ccc", lw=0.6, zorder=0)
    ax.axvline(0, c="#ccc", lw=0.6, zorder=0)
    ax.set_xlim(*LIM_R)
    ax.set_ylim(*LIM_F)
    ax.set_aspect("equal")
    ax.set_xlabel("← 左　　右 → (mm)")
    ax.set_ylabel("← 手前 (根元)　　奥 → (mm)")
    ax.set_title(title, fontsize=10)
    if box_dir is not None:
        d = box_dir / np.linalg.norm(box_dir) * 60
        ax.annotate("", xy=(d[0], d[1]), xytext=(0, 0), arrowprops=dict(arrowstyle="->", color="#555", lw=1.2, ls="--"), zorder=2)
        ax.text(d[0] * 1.12, d[1] * 1.12, "箱", fontsize=8, color="#555", ha="center", va="center")


def real_paths(Z, R):
    """描くコマ: ブロックから 80 mm 以内に初めて入った所から, 成功はつかんだ +0.5 秒, 失敗は最後のブロックでの閉じ +3 秒 (終わりまで)"""
    out = []
    for t in R["trials"]:
        e = Z["data"][t["trial"]]
        P = e["P"]
        n = len(P)
        at = A.block_ref(e["track"], e["b0"]["area"], e["xy0"])
        B = np.array([at(i) for i in range(n)])
        dist = np.linalg.norm(P[:, :2] - B, axis=1)
        k = np.nonzero(dist < 80)[0]
        if not len(k):
            continue
        s = int(k[0])
        held = [a["frame"] for a in t["attempts"] if a["kind"] == "held"]
        near = [a["frame"] for a in t["attempts"]]
        if t["result"] == "success":
            end = held[-1] + 15
        else:
            end = (near[-1] + 90) if near else int(np.argmin(dist)) + 90
        end = min(end, n - 1)
        b = e["xy0"]
        rp = A.rel(P[s:end + 1], b)
        out.append({"t": t, "rp": rp, "b": b, "s": s, "P": P})
    return out


def draw_real(ax, paths, place=None):
    for p in paths:
        t = p["t"]
        if place and t["place"] != place:
            continue
        c = C_OK if t["result"] == "success" else C_NG
        ax.plot(p["rp"][:, 0], p["rp"][:, 1], c=c, lw=0.9, alpha=0.75, zorder=3)
        for a in t["attempts"]:
            q = A.rel(p["P"][a["frame"]], p["b"])[0]
            if a["kind"] == "held" and t["result"] == "success":
                ax.plot(q[0], q[1], "o", ms=5, mfc=C_OK, mec="k", mew=0.5, zorder=5)
            else:
                ax.plot(q[0], q[1], "x", ms=6, mew=1.6, c=C_NG if t["result"] == "failure" else C_OK, zorder=5)


def fig_real(Z, R):
    paths = real_paths(Z, R)
    fig, ax = plt.subplots(figsize=(8, 7))
    base(ax, "実機 30 回 (so101f・依頼 373): ブロックから 80 mm に入ってから つかむまで / 失敗は最後の閉じの 3 秒後まで\n"
             "青 = 成功 12・橙 = 失敗 18. ○ = つかんだ所・× = 空で閉じた所 (ブロックの 50 mm 以内)")
    draw_real(ax, paths)
    for pl in range(1, 6):
        b = np.median([p["b"] for p in paths if p["t"]["place"] == pl], 0)
        d = A.vrel(A.BOX_XY - b, b)
        d = d / np.linalg.norm(d) * 75
        ax.annotate("", xy=(d[0], d[1]), xytext=(0, 0), arrowprops=dict(arrowstyle="->", color="#555", lw=0.8, ls="--"), zorder=2)
        ax.text(d[0] * 1.1, d[1] * 1.1, f"箱({pl})", fontsize=7, color="#555", ha="center")
    fig.tight_layout()
    fig.savefig(HERE / "fig_real_topview.png", dpi=130)
    plt.close(fig)

    fig, axs = plt.subplots(2, 3, figsize=(15, 9.5))
    for pl, ax in zip(range(1, 6), axs.flat):
        ts = [p for p in paths if p["t"]["place"] == pl]
        ok = sum(p["t"]["result"] == "success" for p in ts)
        b = np.median([p["b"] for p in ts], 0)
        base(ax, f"場所{pl} (ブロック 机の座標 {b[0]:.0f}, {b[1]:.0f} mm)  成功 {ok}/{len(ts)}", A.vrel(A.BOX_XY - b, b))
        draw_real(ax, paths, pl)
    ax = axs.flat[5]
    draw_moves(ax, R)
    fig.tight_layout()
    fig.savefig(HERE / "fig_real_by_place.png", dpi=110)
    plt.close(fig)


def draw_moves(ax, R, key="after_2s"):
    base(ax, "空で閉じた所 → 2 秒後 の爪の間の点 (全部の試み 40)\n色 = 2 秒後の向き (右・左・奥・手前・その場 (10 mm 未満))")
    for m in R["misses"]:
        a = m[key]
        c = DIR_C[a["dir"]]
        ax.annotate("", xy=(m["right"] + a["right"], m["fwd"] + a["fwd"]), xytext=(m["right"], m["fwd"]),
                    arrowprops=dict(arrowstyle="->", color=c, lw=1.0, alpha=0.85), zorder=4)
        ax.plot(m["right"], m["fwd"], "x", c="k", ms=4, mew=1, zorder=5)
    tl = R["tally"]["all_misses_" + key]
    txt = "  ".join(f"{d} {tl[d]['count']}" for d in ("右", "左", "奥", "手前", "その場"))
    ax.text(LIM_R[0] + 4, LIM_F[0] + 6, txt, fontsize=8)
    for d, c in DIR_C.items():
        ax.plot([], [], c=c, label=d)
    ax.legend(fontsize=7, loc="upper left")


def fig_moves(R):
    fig, axs = plt.subplots(1, 2, figsize=(14, 6.5))
    draw_moves(axs[0], R, "after_2s")
    ax = axs[1]
    base(ax, "空で閉じた所 → 次に閉じた所 (次の試み. 34)\n色 = 向き")
    for m in R["misses"]:
        a = m.get("next")
        if not a:
            continue
        ax.annotate("", xy=(m["right"] + a["right"], m["fwd"] + a["fwd"]), xytext=(m["right"], m["fwd"]),
                    arrowprops=dict(arrowstyle="->", color=DIR_C[a["dir"]], lw=1.0, alpha=0.85), zorder=4)
        ax.plot(m["right"], m["fwd"], "x", c="k", ms=4, mew=1, zorder=5)
    tl = R["tally"]["all_misses_next"]
    ax.text(LIM_R[0] + 4, LIM_F[0] + 6, "  ".join(f"{d} {tl[d]['count']}" for d in ("右", "左", "奥", "手前", "その場")), fontsize=8)
    fig.tight_layout()
    fig.savefig(HERE / "fig_miss_moves.png", dpi=120)
    plt.close(fig)


def fig_demo(Z, R):
    fig, axs = plt.subplots(1, 2, figsize=(15, 7))
    ax = axs[0]
    base(ax, "お手本 50 本 (so101_redblock_box_ideal_var_v2_success_v1): ブロックから 80 mm に入ってから つかむまで\n"
             "灰 = まっすぐ 40・紫 = 外れて戻る (DETOUR. ブロックの上 50 mm で) 10. ○ = つかんだ所")
    dm = {d["ep"]: d for d in R["demo"]}
    for name, e in Z["demo"].items():
        P, b, g = e["P"], e["xy0"], e["Q"][:, 5]
        ev = A.close_events(g)
        i = ev[0]
        dist = np.linalg.norm(P[:, :2] - b, axis=1)
        s = int(np.nonzero(dist < 80)[0][0])
        rp = A.rel(P[s:i + 1], b)
        det = e["meta"].get("detour")
        ax.plot(rp[:, 0], rp[:, 1], c=C_DET if det else C_DEMO, lw=0.9 if det else 0.6, alpha=0.9 if det else 0.6, zorder=4 if det else 3)
        ax.plot(rp[-1, 0], rp[-1, 1], "o", ms=3.5, mfc=C_DET if det else C_DEMO, mec="k", mew=0.3, zorder=5)
    ax = axs[1]
    base(ax, "閉じた所の比べ: お手本のつかんだ所 (灰 ○) / 実機の成功のつかんだ所 (青 ○) / 実機の空で閉じた所 (橙 ×)")
    for d in R["demo"]:
        ax.plot(d["grasp_rel"][0], d["grasp_rel"][1], "o", ms=4, mfc=C_DEMO, mec="k", mew=0.3, alpha=0.8)
    for t in R["trials"]:
        for a in t["attempts"]:
            if a["kind"] == "held" and t["result"] == "success":
                ax.plot(a["right"], a["fwd"], "o", ms=6, mfc=C_OK, mec="k", mew=0.4)
    for m in R["misses"]:
        ax.plot(m["right"], m["fwd"], "x", ms=6, mew=1.5, c=C_NG)
    ax.set_xlim(-50, 70)
    ax.set_ylim(-50, 50)
    fig.tight_layout()
    fig.savefig(HERE / "fig_demo_topview.png", dpi=120)
    plt.close(fig)


def fig_height(R):
    fig, ax = plt.subplots(figsize=(7, 4.5))
    dz = [d["grasp_rel"][2] for d in R["demo"]]
    hz = [a["z"] for t in R["trials"] if t["result"] == "success" for a in t["attempts"] if a["kind"] == "held"]
    mz = [m["z"] for m in R["misses"]]
    bins = np.arange(0, 40, 2.5)
    ax.hist([dz, hz, mz], bins=bins, label=[f"お手本のつかんだ所 ({len(dz)})", f"実機 成功のつかんだ所 ({len(hz)})", f"実機 空で閉じた所 ({len(mz)})"],
            color=[C_DEMO, C_OK, C_NG])
    ax.axvline(21.7, c="#c0392b", ls="--", lw=1)
    ax.text(22, ax.get_ylim()[1] * 0.9, "ブロックの上の面 21.7", fontsize=8, color="#c0392b")
    ax.set_xlabel("閉じたときの 爪の間の点の高さ (机の面から mm)")
    ax.set_ylabel("回数")
    ax.legend(fontsize=8)
    fig.tight_layout()
    fig.savefig(HERE / "fig_close_height.png", dpi=120)
    plt.close(fig)


def main():
    Z = np.load(HERE / "traj_376.npy", allow_pickle=True).item()
    R = json.loads((HERE / "result_376.json").read_text())
    fig_real(Z, R)
    fig_moves(R)
    fig_demo(Z, R)
    fig_height(R)


if __name__ == "__main__":
    main()
