"""依頼 380 の図: 6 本を上から見た図 (check_380.json から. python3・matplotlib. 字は日本語).

  fig_topview_380.png : ブロックごとの向き (横 = 右, 縦 = 奥. 依頼 376 と同じ) で ブロックを真ん中に置き,
      つかむ所 (GRASP_OPEN) の 固定側の爪・動く爪 (開いた) の形 (高さ 30 mm より下の頂点を上から見た外形) を
      案 B (点線) と 案 C (塗り) で. 爪の間の点の道 (戻る → つかむ所) も B (灰) と C (緑).
      11 本目は 奥 +40 mm の道が作れないので 奥 +28 mm で作った値 (check_380_fwd11_28.json)

  python3 so101/check_380/figs_380.py
"""
import json
import math
from pathlib import Path

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

plt.rcParams["font.family"] = "Hiragino Sans"
HERE = Path(__file__).resolve().parent


def frame(b):
    u = np.asarray(b[:2], float) / np.linalg.norm(b[:2])
    return u, np.array([u[1], -u[0]])


def rel(P, b):
    u, r = frame(b)
    d = np.asarray(P, float)[..., :2] - np.asarray(b[:2])
    return np.stack([d @ r, d @ u], -1)


def square(b, yaw):
    u, r = frame(b)
    a = math.radians(yaw)
    out = []
    for sx, sy in ((1, 1), (-1, 1), (-1, -1), (1, -1)):
        c = np.array([math.cos(a), math.sin(a)]) * sx * 10.85 + np.array([-math.sin(a), math.cos(a)]) * sy * 10.85
        out.append([c @ r, c @ u])
    return out


def hull(P):
    from scipy.spatial import ConvexHull
    P = np.asarray(P, float)
    if len(P) < 3:
        return None
    return P[ConvexHull(P).vertices]


def main():
    D = json.loads((HERE / "check_380.json").read_text())
    alt = {r["plan_index"]: r for r in json.loads((HERE / "check_380_fwd11_28.json").read_text())["episodes"]}
    fig, axs = plt.subplots(2, 3, figsize=(16, 13.5))
    for ax, row in zip(axs.ravel(), D["episodes"]):
        note = ""
        if "foot_c" not in row:
            row, note = alt[row["plan_index"]], "（奥 +40 は道が作れない。奥 +28 で作った値）"
        b = np.array(row["block_xy_mm"])
        ax.add_patch(Polygon(square(b, row["yaw"]), closed=True, fc="#f4b6b6", ec="#b22222", lw=1.5, label="ブロック (21.7 mm)"))
        for tag, ls, alpha in (("b", ":", 0.0), ("c", "-", 0.35)):
            for k, col, name in (("fixed", "#1f5fbf", "固定側の爪"), ("moving", "#e07b00", "動く爪 (開いた)")):
                h = hull(rel(np.array(row[f"foot_{tag}"][k]), b))
                if h is None:
                    continue
                ax.add_patch(Polygon(h, closed=True, fc=col if tag == "c" else "none", alpha=1.0 if tag == "b" else alpha,
                                     ec=col, ls=ls, lw=1.6, label=f"{name}・案 {'C' if tag == 'c' else 'B'}"))
        for tag, col, name, kf in (("b", "0.5", "爪の間の点 案 B", "b_keyframes"), ("c", "tab:green", "爪の間の点 案 C", "c_keyframes")):
            T = rel(np.array(row[f"{tag}_track_mm"]), b)
            k = row[kf]
            a0 = k["ABOVE_BLOCK"]
            bk = k.get("RETRY_ABOVE", k["MISS_UP"]) - a0
            g = k["GRASP_OPEN"] - a0
            ax.plot(T[bk:g + 1, 0], T[bk:g + 1, 1], "-", color=col, lw=2, label=f"{name} (戻る → つかむ所)")
            ax.plot(*T[g], "o", mfc="none", mec=col, ms=10, mew=2)
        c, w = row["c"].get("cmd") or {}, row["c"].get("worst") or {}
        ax.set_title(f"{row['n']} 本目（場所{row['place']}）左へ {row['left_mm']:g} mm 寄せた{note}\n"
                     f"依頼 379 の R: {', '.join('%+.1f' % x['R'] for x in row['r379'])} mm\n"
                     f"指令: 動く爪 {c.get('moving_block_min_mm')}・固定側 {c.get('fixed_block_min_mm')} mm・"
                     f"挟める {'はい' if c.get('pinch_ok') else 'いいえ'}\n"
                     f"沈んだ関節の最小: 動く爪 {w.get('moving_block_min_mm')}・固定側 {w.get('fixed_block_min_mm')} mm",
                     fontsize=10)
        ax.set_aspect("equal")
        ax.set_xlim(-45, 45)
        ax.set_ylim(-40, 40)
        ax.axhline(0, color="0.9", lw=0.5)
        ax.axvline(0, color="0.9", lw=0.5)
        ax.set_xlabel("右 (mm)")
        ax.set_ylabel("奥 (mm)")
    seen = {}
    for ax in axs.ravel():
        for hh, ll in zip(*ax.get_legend_handles_labels()):
            seen.setdefault(ll, hh)
    fig.legend(list(seen.values()), list(seen.keys()), loc="lower center", ncol=4, fontsize=10)
    fig.suptitle("依頼 380：つかむ所（GRASP_OPEN）を上から見た図。ブロックごとの向き（横 = 右・縦 = 奥）。"
                 "爪の形は高さ 30 mm より下。点線 = 案 B・塗り = 案 C（左へ寄せた）。○ = つかむ所の爪の間の点", fontsize=12)
    fig.tight_layout(rect=(0, 0.07, 1, 0.95), h_pad=3)
    out = HERE / "fig_topview_380.png"
    fig.savefig(out, dpi=90)
    plt.close(fig)
    print(out)


if __name__ == "__main__":
    main()
