#!/usr/bin/env python3
"""依頼 429 の 3-8: 上から見た 爪とブロックの図 (check_429/fig_429.png). アームなし.
場所ごとに 爪の座標 (横 = 爪の閉じる向き a・縦 = それに直角で腕から外へ b. 原点 = 爪の先. 依頼 426 の測り方と同じ) で ブロックの真ん中を描く:
  425 の実機 27 回 (手首の絵で測った所. 成功 ● / 外した ×)・427 の補正のあとの実機 19 回 (測った所. 全部成功 ●)・
  429 の計算の道 (427 の 19 回・425 の 27 回と同じ読んだ画素・向きで作った道で 429 の形が予想する所 ◆. 実機ではない)
灰色の四角 = 427 の 19 回の真ん中に置いた ブロック (一辺 21.7 mm). 縦の線 = 爪 (固定側・開いた動く爪) の内側の目安 (測った回の中央).

  (lerobot の環境で) python so101/check_429/fig_429.py points   → check_429/fig_429_points.json (シムで出す)
  (matplotlib のある python で) python3 so101/check_429/fig_429.py draw  → check_429/fig_429.png
"""
import json
import sys
from pathlib import Path

import numpy as np

HERE = Path(__file__).resolve().parent
SO101 = HERE.parent
sys.path.insert(0, str(SO101 / "check_426"))
sys.path.insert(0, str(HERE))

C425, C427, C429 = "#2a78d6", "#eb6834", "#1baf7a"
INK, MUTED, GRID = "#222222", "#6b6b66", "#e4e3df"
HALF = 21.7 / 2


def measured():
    out = []
    for src in (SO101 / "check_426" / "measure_426.json", HERE / "measure_429.json"):
        for o in json.loads(src.read_text())["trials"]:
            if "wrist" in o and o["group"] in ("425", "427"):
                w = o["wrist"]
                out.append({"group": o["group"], "place": o["place"], "ok": o["result"] == "success", "a": w["along_a"], "b": w["along_b"],
                            "gf": w["gap_fixed"], "gm": w["gap_moving"]})
    return out


def predicted(rig, m):
    import model_429 as MD
    import var_lib_314 as V
    out = []
    for kind in ("s427", "r425"):
        for f in sorted((HERE / "table_429").glob(f"{kind}_*.json")):
            for r in json.loads(f.read_text())["rows"]:
                n = r["new"]
                if not n.get("ok"):
                    continue
                go = np.asarray(n["go"], float)
                _, R = V.tcp_arm(rig.W.w.chain, go[:5] + m["_off"])
                w = np.asarray(n["bxy"], float) + np.asarray(m["e0_xy_mm"], float) + (R @ np.asarray(m["v_gripper_mm"], float))[:2]
                rel = rig.relation_w(np.asarray(n["go_pred"], float), w, float(r["yaw_read"]), off=True)
                out.append({"group": "429", "set": kind, "place": r["place"], "a": rel["along_a"], "b": rel["along_b"]})
    return out


def points():
    import measure_426 as M
    import model_429 as MD
    rig = M.Rig()
    m = MD.load()
    meas = measured()
    pred = predicted(rig, m)
    (HERE / "fig_429_points.json").write_text(json.dumps({"measured": meas, "predicted_429": pred}, ensure_ascii=False, indent=0))
    print("fig_429_points.json", len(meas), len(pred))


def draw():
    import matplotlib
    matplotlib.use("Agg")
    import matplotlib.pyplot as plt
    from matplotlib import font_manager
    for name in ("Hiragino Sans", "Hiragino Maru Gothic Pro", "AppleGothic"):
        if any(name in f.name for f in font_manager.fontManager.ttflist):
            plt.rcParams["font.family"] = name
            break
    d = json.loads((HERE / "fig_429_points.json").read_text())
    meas, pred = d["measured"], d["predicted_429"]
    m27 = [r for r in meas if r["group"] == "427"]
    ca, cb = float(np.median([r["a"] for r in m27])), float(np.median([r["b"] for r in m27]))
    fx = float(np.median([r["a"] + HALF + r["gf"] for r in meas if r["gf"] is not None]))
    mv = float(np.median([r["a"] - HALF - r["gm"] for r in meas if r["gm"] is not None]))
    fig, axs = plt.subplots(1, 4, figsize=(17, 5.6), sharey=True)
    for ax, place in zip(axs, (2, 3, 4, 5)):
        ax.set_facecolor("white")
        ax.grid(True, color=GRID, lw=0.8)
        ax.add_patch(plt.Rectangle((ca - HALF, cb - HALF), 2 * HALF, 2 * HALF, fc="#d9d8d3", ec="#b5b4ae", lw=1, zorder=0))
        for x, lab in ((fx, "固定側の爪"), (mv, "動く爪 (開き)")):
            ax.plot([x, x], [-35, 15], color=MUTED, lw=3, solid_capstyle="round", zorder=1)
            ax.text(x, 17, lab, ha="center", va="bottom", fontsize=8, color=MUTED)
        for r in meas:
            if r["place"] != place:
                continue
            col = C425 if r["group"] == "425" else C427
            if r["ok"]:
                ax.scatter(r["a"], r["b"], s=46, marker="o", color=col, edgecolor="white", lw=1.2, zorder=3)
            else:
                ax.scatter(r["a"], r["b"], s=58, marker="x", color=col, lw=2, zorder=3)
        for r in pred:
            if r["place"] == place:
                ax.scatter(r["a"], r["b"], s=48, marker="D", color=C429, edgecolor="white", lw=1.0, zorder=4)
        ax.set_title(f"場所{place}", fontsize=12, color=INK)
        ax.set_xlim(min(mv, -60) - 8, 12)
        ax.set_ylim(-40, 45)
        ax.set_aspect("equal")
        ax.set_xlabel("爪の閉じる向き a (mm. 固定側の爪へ +)", fontsize=9, color=MUTED)
        ax.tick_params(colors=MUTED, labelsize=8)
        for s in ax.spines.values():
            s.set_color(GRID)
    axs[0].set_ylabel("爪に直角 b (mm. 腕から外 = 爪の先の向こうへ +)", fontsize=9, color=MUTED)
    from matplotlib.lines import Line2D
    h = [Line2D([], [], ls="", marker="o", color=C425, mec="white", ms=8, label="425 実機・成功 (測った所)"),
         Line2D([], [], ls="", marker="x", color=C425, mew=2, ms=8, label="425 実機・外した (測った所)"),
         Line2D([], [], ls="", marker="o", color=C427, mec="white", ms=8, label="427 補正のあと 実機・成功 (測った所)"),
         Line2D([], [], ls="", marker="D", color=C429, mec="white", ms=7, label="429 の計算の道 (予想. 実機ではない)")]
    fig.legend(handles=h, loc="upper center", ncol=4, frameon=False, fontsize=10, bbox_to_anchor=(0.5, 1.0))
    fig.suptitle("上から見た 爪とブロックの真ん中 (爪の座標. 灰色 = 427 の成功の真ん中に置いたブロック)", y=0.92, fontsize=12, color=INK)
    fig.tight_layout(rect=(0, 0, 1, 0.9))
    fig.savefig(HERE / "fig_429.png", dpi=130, facecolor="white")
    print("fig_429.png", len(meas), len(pred))


if __name__ == "__main__":
    points() if sys.argv[1:] == ["points"] else draw()
