"""依頼 377 の 2: 上から見た図 (traj_377.json から. python3・matplotlib. 字は英字).

  fig_topview_<案>.png : 15 本. ブロックごとの向き (横 = right, 縦 = forward. 依頼 376 と同じ) で ブロックを真ん中に置き,
      爪の間の点の道 (ブロックの上 → 外した所 → 上がる → [流れる] → 戻る → つかむ所) を区間ごとの色で.
      × = 空で閉じた所, ○ = つかむ所, 灰の四角 = ブロック (21.7 mm), 点線の矢印 = 箱の向き.
  fig_places.png : 机の上の 15 本の置く所 (アームの座標. +x 奥・+y 左) と 外した所 (案 A・B)

  python3 so101/check_377/figs_377.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

HERE = Path(__file__).resolve().parent
BOX = np.array([186.9, -197.7])
SEGS = [("ABOVE_BLOCK", "MISS_OPEN", "tab:red", "down to miss"), ("MISS_REOPEN", "MISS_UP", "tab:orange", "rise"),
        ("MISS_UP", "DRIFT", "tab:purple", "drift (box dir)"), ("DRIFT", "RETRY_ABOVE", "tab:blue", "back"),
        ("MISS_UP", "RETRY_ABOVE", "tab:blue", "back"), ("RETRY_ABOVE", "GRASP_OPEN", "tab:green", "down to grasp"),
        ("MISS_UP", "GRASP_OPEN", "tab:green", "down to grasp")]


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)[..., :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 topview(rows, tag):
    fig, axs = plt.subplots(3, 5, figsize=(19, 11.5))
    for ax, row in zip(axs.T.ravel(), sorted(rows, key=lambda r: (r["place"], r["n"]))):
        if row.get("made") is False:
            ax.set_title(f"ep{row['n']:02d} place{row['place']} path not made", fontsize=9, color="tab:red")
            continue
        b = np.array(row["block_xy_mm"])
        T = rel(np.array(row["track_mm"]), b)
        kf = row["keyframes"]
        done = set()
        for a, z, col, name in SEGS:
            if a in kf and z in kf and (a, z) not in done and not (z == "GRASP_OPEN" and a == "MISS_UP" and "RETRY_ABOVE" in kf) \
                    and not (a == "MISS_UP" and z == "RETRY_ABOVE" and "DRIFT" in kf):
                done.add((a, z))
                ax.plot(T[kf[a]:kf[z] + 1, 0], T[kf[a]:kf[z] + 1, 1], "-", color=col, lw=1.8, label=name)
        ax.add_patch(Polygon(square(b, row["yaw"]), closed=True, fc="0.85", ec="0.3"))
        m = rel(np.array(row["miss_point_mm"]), b)
        g = rel(np.array(row["grasp_point_mm"]), b)
        ax.plot(*m, "x", color="k", ms=10, mew=2)
        ax.plot(*g, "o", mfc="none", mec="k", ms=10, mew=1.5)
        bd = rel(b + (BOX - b) / np.linalg.norm(BOX - b) * 40, b)
        ax.annotate("", xy=bd, xytext=(0, 0), arrowprops=dict(arrowstyle="->", ls=":", color="0.4"))
        r = row["recover"]
        k = r["kind"] + ("/" + r["miss_kind"] if r.get("miss_kind") else "")
        amt = f"fwd {r.get('d_fwd_mm', 0):+g} right {r.get('d_right_mm', 0):+g} dz {r.get('dz_mm', 0):+g}" + \
              (f" drift {r['drift_mm']:g}" if r.get("drift_mm") else "")
        c = row["contact"]["arm_block_min_mm"]
        ax.set_title(f"ep{row['n']:02d} place{row['place']} (plan {row['from_plan_index'] + 1}) {k}\n{amt}\n"
                     f"arm-block {c:+.1f} mm {'OK' if row['ok'] else 'TOUCH/NG'}", fontsize=9,
                     color="k" if row["ok"] else "tab:red")
        ax.set_aspect("equal")
        ax.set_xlim(-60, 60)
        ax.set_ylim(-50, 50)
        ax.axhline(0, color="0.9", lw=0.5)
        ax.axvline(0, color="0.9", lw=0.5)
        ax.tick_params(labelsize=7)
    h, lab = axs[0, 0].get_legend_handles_labels()
    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=6, fontsize=10)
    fig.suptitle(f"request 377 plan {tag.upper()}: gripper-center path, block frame (x = right, y = forward / mm). "
                 f"x = empty close, o = grasp, dotted arrow = box direction. columns = place 1..5", fontsize=12)
    fig.tight_layout(rect=(0, 0.04, 1, 0.96))
    out = HERE / f"fig_topview_{tag}.png"
    fig.savefig(out, dpi=90)
    plt.close(fig)
    return out


def places(D):
    fig, ax = plt.subplots(figsize=(8, 8))
    for tag, mk, col in (("a", "x", "tab:red"), ("b", "+", "tab:blue")):
        for row in [x for x in D.get(tag, []) if x.get("made") is not False]:
            b = np.array(row["block_xy_mm"])
            m = np.array(row["miss_point_mm"])
            ax.plot([-b[1], -m[1]], [b[0], m[0]], "-", color=col, lw=0.8)
            ax.plot(-m[1], m[0], mk, color=col, ms=8, label=f"miss plan {tag.upper()}")
    for row in D.get("b", []):
        b = np.array(row["block_xy_mm"])
        ax.plot(-b[1], b[0], "s", color="0.4", ms=7)
        ax.annotate(f"{row['n']:02d}/p{row['place']}", (-b[1], b[0]), xytext=(4, 4), textcoords="offset points", fontsize=8)
    ax.add_patch(plt.Rectangle((-BOX[1] - 40, BOX[0] - 40), 80, 80, fc="none", ec="k"))
    ax.plot(0, 0, "k^", ms=10)
    h, lab = ax.get_legend_handles_labels()
    u = dict(zip(lab, h))
    ax.legend(u.values(), u.keys())
    ax.set_aspect("equal")
    ax.set_xlabel("right (-y) mm")
    ax.set_ylabel("forward (+x) mm")
    ax.set_title("request 377: 15 blocks (square) and empty-close points; base = triangle, box = square")
    out = HERE / "fig_places.png"
    fig.savefig(out, dpi=90)
    plt.close(fig)
    return out


def main():
    D = json.loads((HERE / "traj_377.json").read_text())
    for tag in ("a", "b"):
        if tag in D:
            print(topview(D[tag], tag))
    print(places(D))


if __name__ == "__main__":
    main()
