"""依頼 335 の 1・2: 爪の値の換算 と 手首カメラの付き方 (gripper の body に対する 位置 3・向き 3) を, 実機の手首の映像に合わせて出す.
アームのサーボ・カメラには触らない (記録の動画を読むだけ). KIOXIA には書かない.

お手本 = teleop_even_v1 の 50 本 (simreplay_334 と同じ). 場所ごとに 本を交互に「合わせ」「確かめ」に分ける (各 25 本).

1. 爪の値の換算 q (rad) = q_h + k × (g − g_h)
   - g_h = つかんでいる間 (依頼 334 の帯 9.5〜13.5 の いちばん長い所) の爪の値の中央値 (本ごとの中央値の中央値)
   - q_h = 幅 21.7mm のブロックに 両方の爪の面が触れる角度 (sim_335.grasp_block_pose. 爪の内側の面は平らな段なので 置き方によらずほぼ同じ)
   - k = 傾き. 手首カメラの映像の 爪の縁から出す (2 と一緒に合わせる). 爪とカメラは同じ部品に付いているので, 実機の爪は全部のコマで
     同じ所に写る (動く爪は爪の値だけで動く). そこで 爪の値の帯ごと (0〜2.5・4〜9・9.5〜13.5・15〜25・25〜35・35〜50) に
     手首の絵の中央値をとると, 背景が消えて爪の縁が残る. その縁 (Canny) と シムの爪の輪郭の距離 (chamfer) を使う.
   - 確かめ: 合わせたあと 帯ごとに 動く爪の角度だけを自由に合わせ (1 つずつ), 直線からのずれを見る.
     サーボの目盛りから出る傾き (ptm_follower.json の gripper の range: (max − min) × 360/4096 / 100) とも比べる.
2. 手首カメラの付き方: 次の和を Nelder-Mead で小さくする (7 つ: 位置 3・回転ベクトル 3・k)
   - 固定側の爪の輪郭 → 実機の縁の距離 (px. 20 で頭打ち) の平均 (帯ごと)
   - 動く爪の輪郭 → 実機の縁の距離 の平均 (帯ごと. 角度は換算から)
   - ブロックが机の上にある間のコマ (HOME・ブロックの上. 依頼 334 の段階. 爪が閉じ始める 5 コマ前まで):
     ブロック (依頼 334 で本ごとに測った机の上の位置・向き・大きさ) の 8 隅を写した形 と 実機の赤い所 の
     重心の距離 (px. 80 で頭打ち) × W_CEN + (1 − IoU) × W_IOU
     腕の姿勢は記録の角度・台座は記録の回ごと (依頼 334 と同じ).
   確かめの本で 同じ数字を出す. 依頼 330 の値 (向きだけ合わせた) でも同じ数字を出して並べる.
出力: so101/check_335/wrist_grip_335.json, wrist_grip_fit_335.png (帯ごとの中央値の絵に 前 (依頼 330) と 後 の爪の輪郭),
      wrist_block_fit_335.png (机の上のブロックのコマ: 実機の赤い所 (黄) と 前 (青)・後 (緑) のブロック)

使い方 (conda の lerobot 環境で):
    python so101/sim/fit_wrist_grip_335.py --cache   # 中央値の絵・机の上のブロックのコマを集める → check_335/_cache_335.npz
    python so101/sim/fit_wrist_grip_335.py --fit     # 合わせる → wrist_grip_335.json・絵
"""

import argparse
import json
import math
import sys
from datetime import datetime
from pathlib import Path

import cv2
import numpy as np

HERE = Path(__file__).resolve().parent
sys.path.insert(0, str(HERE))
import sim_330 as S  # noqa: E402
import sim_331 as T  # noqa: E402
import sim_335 as G  # noqa: E402
import simreplay_334 as R  # noqa: E402
from measure_scene_330 import hull_mask, iou, nelder_mead, red_mask  # noqa: E402

OUT = G.OUT
CACHE = OUT / "_cache_335.npz"
BINS = [(0.0, 2.5), (4.0, 9.0), (9.5, 13.5), (15.0, 25.0), (25.0, 35.0), (35.0, 50.0)]
HOLD_BIN = 2
MED_STEP = 3  # 中央値に使うコマの間隔
MED_MAX = 120  # 帯ごとの中央値に使うコマ数の上限
TABLE_PER_EP = 6  # 机の上のブロックのコマ (本ごと)
TABLE_MIN_PX = 600
CAP_EDGE = 30.0
CANNY = (8, 25)  # 帯ごとの中央値の絵の縁. 白い爪と白い机の境は出ず, 爪の内側の縁 (歯の段) と 動く爪の外の縁の一部が出る
INNER_BOTTOM = 15  # 内側の縁: 絵の下の端からこの px は使わない
TIP_BINS = (0, 5)  # 固定側の爪の先の点を測る帯 (動く爪が離れている or 閉じている. ブロックが爪の間にない)
TIP_WIN = (240, 300, 280, 340)  # 実機の固定側の爪の先を探す窓 (x0, x1, y0, y1)
W_TIP = 1.0
REAL_EDGE_Y0 = 200  # 実機の縁 → シムの内側の縁 の距離に使う 実機の縁の点 (この行より下. 爪のある所)
CAP_CEN = 80.0
W_CEN, W_IOU = 0.15, 10.0


def split(idx):
    """場所ごとに 新しい番号の順に交互 (0 番目・2 番目… = 合わせ, 1・3… = 確かめ)."""
    by = {}
    for i, e in enumerate(idx["episodes"]):
        by.setdefault(e["place"], []).append(i)
    fit, chk = [], []
    for p in sorted(by):
        for n, i in enumerate(by[p]):
            (fit if n % 2 == 0 else chk).append(i)
    return sorted(fit), sorted(chk)


def hold_value(g):
    ev = R.grip_events(g)
    if ev is None or ev["r"] is None:
        return None
    return float(np.median(g[ev["c"]:ev["r"]]))


# ---- 集める ----------------------------------------------------------------------------------

def cache_mode(idx):
    OUT.mkdir(parents=True, exist_ok=True)
    import pandas as pd
    fr = pd.read_csv(R.OUT / "frames_334.csv", usecols=["new_episode_index", "frame", "stage", "wrist_red_real_px"])
    cams = S.load_cameras()
    maps = {k: S.DistortMap(cams[k]["K"], cams[k]["D"]) for k in ("desk", "wrist")}
    box330, base330, wrist330 = R.base_scene()
    sc = json.loads((R.OUT / "scene_334.json").read_text())
    fit, chk = split(idx)
    out = {}
    holds = []
    table = {"ep": [], "frame": [], "gp": [], "gR": [], "block": [], "mask_rle": []}
    for tag, eps in (("fit", fit), ("chk", chk)):
        acc = {b: [] for b in range(len(BINS))}
        gvals = {b: [] for b in range(len(BINS))}
        for i in eps:
            e = idx["episodes"][i]
            _, st, _ = T.read_episode_any(e["source"], e["episode_index"])
            g = st[:, 5]
            hv = hold_value(g)
            if hv is not None:
                holds.append((i, hv))
            ev = R.grip_events(g)
            cs = ev["cs"] if ev else len(g)
            d = fr[(fr["new_episode_index"] == i) & fr["stage"].isin(["HOME", "ABOVE_BLOCK"]) & (fr["frame"] < cs - 5)
                   & (fr["wrist_red_real_px"] >= TABLE_MIN_PX)]
            ks = d["frame"].to_numpy()
            want = set(ks[np.linspace(0, len(ks) - 1, min(TABLE_PER_EP * 3, len(ks))).astype(int)]) if len(ks) else set()
            b0 = sc["episodes"][i]
            box, base = R.scene_of(sc, i, box330, base330)
            rp = R.Replay({"block": {"xy": b0["block_xy_mm"], "yaw": b0["block_yaw_deg"], "size": b0["block_size_mm"]}, "box": box},
                          base, wrist330, maps, cams, render=False)
            got = 0
            for k, im in R.iter_frames(e["source"], e["episode_index"], "wrist"):
                if k % MED_STEP == 0:
                    for b, (lo, hi) in enumerate(BINS):
                        if lo <= g[k] < hi:
                            acc[b].append(im)
                            gvals[b].append(g[k])
                if k in want and got < TABLE_PER_EP:
                    rm = red_mask(im)
                    if rm is None or rm.sum() < TABLE_MIN_PX or rm[:3].any() or rm[-3:].any() or rm[:, :3].any() or rm[:, -3:].any():
                        continue
                    rp.pose_arm(st[k])
                    gp, gR = rp.gripper_pose()
                    table["ep"].append(i)
                    table["frame"].append(k)
                    table["gp"].append(gp)
                    table["gR"].append(gR)
                    table["block"].append([b0["block_xy_mm"][0], b0["block_xy_mm"][1], b0["block_yaw_deg"], b0["block_size_mm"]])
                    table["mask_rle"].append(np.packbits(rm))
                    got += 1
            # 帯ごとの中央値: 上限を超えたら 間引く (メモリ)
            for b in acc:
                if len(acc[b]) > 3 * MED_MAX:
                    keep = np.linspace(0, len(acc[b]) - 1, 2 * MED_MAX).astype(int)
                    acc[b] = [acc[b][j] for j in keep]
                    gvals[b] = [gvals[b][j] for j in keep]
            print(tag, i, "table frames", got, flush=True)
        for b in acc:
            if not acc[b]:
                continue
            keep = np.linspace(0, len(acc[b]) - 1, min(MED_MAX, len(acc[b]))).astype(int)
            out[f"med_{tag}_{b}"] = np.median(np.stack([acc[b][j] for j in keep]), 0).astype(np.uint8)
            out[f"g_{tag}_{b}"] = np.array([np.median(gvals[b]), len(acc[b])])
            print(tag, BINS[b], "frames", len(acc[b]), "g median", round(float(np.median(gvals[b])), 2))
    for k, v in table.items():
        out[f"table_{k}"] = np.array(v)
    out["holds"] = np.array(holds)
    out["fit_eps"], out["chk_eps"] = np.array(fit), np.array(chk)
    np.savez_compressed(CACHE, **out)
    print("saved", CACHE)


# ---- 合わせる --------------------------------------------------------------------------------

class Problem:
    def __init__(self, C, jaws, K, Dd, q_h, g_h):
        self.C, self.jaws, self.K, self.D, self.q_h, self.g_h = C, jaws, K, Dd, q_h, g_h
        self.edges, self.dts, self.gbin, self.real_pts = {}, {}, {}, {}
        for tag in ("fit", "chk"):
            for b in range(len(BINS)):
                key = f"med_{tag}_{b}"
                if key not in C:
                    continue
                im = C[key]
                e = cv2.Canny(cv2.GaussianBlur(cv2.cvtColor(im, cv2.COLOR_BGR2GRAY), (5, 5), 0), *CANNY)
                rm = red_mask(im)
                if rm is not None:
                    e[cv2.dilate(rm.astype(np.uint8), np.ones((9, 9), np.uint8)) > 0] = 0
                self.edges[(tag, b)] = e
                self.dts[(tag, b)] = cv2.distanceTransform((e == 0).astype(np.uint8), cv2.DIST_L2, 3)
                ys, xs = np.nonzero(e[REAL_EDGE_Y0:])
                self.real_pts[(tag, b)] = np.c_[xs, ys + REAL_EDGE_Y0]
                self.gbin[(tag, b)] = float(C[f"g_{tag}_{b}"][0])
        self.real_tip = {}
        for tag in ("fit", "chk"):
            tips = []
            x0, x1, y0, y1 = TIP_WIN
            for b in TIP_BINS:
                if (tag, b) in self.edges:
                    ys, xs = np.nonzero(self.edges[(tag, b)][y0:y1, x0:x1])
                    k = np.argsort(ys)[:3]
                    tips.append([xs[k].mean() + x0, ys[k].mean() + y0])
            self.real_tip[tag] = np.mean(tips, 0)
        fit_eps = set(C["fit_eps"].tolist())
        self.table = {"fit": [], "chk": []}
        for j in range(len(C["table_ep"])):
            rm = np.unpackbits(C["table_mask_rle"][j])[:S.H * S.W].reshape(S.H, S.W) > 0
            ys, xs = np.nonzero(rm)
            x, y, yaw, s = C["table_block"][j]
            c8 = S.box_corners([x, y], yaw, [s, s], 0.0, s)
            tag = "fit" if int(C["table_ep"][j]) in fit_eps else "chk"
            self.table[tag].append({"ep": int(C["table_ep"][j]), "frame": int(C["table_frame"][j]), "gp": C["table_gp"][j],
                                    "gR": C["table_gR"][j], "c8": c8, "rm": rm, "cen": np.array([xs.mean(), ys.mean()])})

    def cam(self, p):
        return G.wrist_cam({"pos_mm": p[:3], "rotvec": p[3:6]}, self.K, self.D)

    def q_of(self, g, k):
        return float(np.clip(self.q_h + k * (g - self.g_h), *self.jaws.rng))

    def jaw_terms(self, cam, k, tag, q_override=None):
        fixed = inner_edge(G.raster(self.jaws.tri_px([G.FIXED_JAW_MESH], 0.0, cam)), "right")
        out = []
        for b in range(len(BINS)):
            if (tag, b) not in self.dts:
                continue
            dt = self.dts[(tag, b)]
            q = self.q_of(self.gbin[(tag, b)], k) if q_override is None else q_override.get(b, self.q_of(self.gbin[(tag, b)], k))
            mv = inner_edge(G.raster(self.jaws.tri_px([G.MOVING_MESH], q, cam)), "left")
            cf = float(np.mean(np.minimum(dt[fixed[:, 1], fixed[:, 0]], CAP_EDGE))) if len(fixed) > 20 else CAP_EDGE
            cm = float(np.mean(np.minimum(dt[mv[:, 1], mv[:, 0]], CAP_EDGE))) if len(mv) > 20 else CAP_EDGE
            # 実機の縁 → シムの内側の縁 (両方の爪). 爪の先の高さ・歯の段の位置が決まる
            sm = np.full((S.H, S.W), 255, np.uint8)
            for pts in (fixed, mv):
                if len(pts):
                    sm[pts[:, 1], pts[:, 0]] = 0
            dts = cv2.distanceTransform(sm, cv2.DIST_L2, 3)
            rp = self.real_pts[(tag, b)]
            cr = float(np.mean(np.minimum(dts[rp[:, 1], rp[:, 0]], CAP_EDGE))) if len(rp) else 0.0
            out.append((b, cf, cm, cr))
        return out

    def fixed_tip(self, cam):
        """シムの固定側の爪の先 (形のいちばん上の 5 点の平均)."""
        mk = G.raster(self.jaws.tri_px([G.FIXED_JAW_MESH], 0.0, cam))
        ys, xs = np.nonzero(mk)
        if len(ys) < 15:
            return None
        k = np.argsort(ys)[:5]
        return np.array([xs[k].mean(), ys[k].mean()])

    def table_terms(self, cam, tag):
        cens, ious = [], []
        for it in self.table[tag]:
            px, ok = G.project_wrist(it["c8"], cam, (it["gp"], it["gR"]))
            if not ok.all():
                cens.append(CAP_CEN)
                ious.append(0.0)
                continue
            hm = hull_mask(px, (S.H, S.W))
            if hm.sum() < 10:
                cens.append(CAP_CEN)
                ious.append(0.0)
                continue
            ys, xs = np.nonzero(hm)
            cens.append(min(CAP_CEN, float(np.hypot(xs.mean() - it["cen"][0], ys.mean() - it["cen"][1]))))
            ious.append(iou(hm, it["rm"]))
        return np.array(cens), np.array(ious)

    def cost(self, p, tag="fit", detail=False):
        cam = self.cam(p)
        jt = self.jaw_terms(cam, p[6], tag)
        cen, io = self.table_terms(cam, tag)
        tip = self.fixed_tip(cam)
        tip_d = float(np.linalg.norm(tip - self.real_tip[tag])) if tip is not None else 100.0
        c = (float(np.mean([x[1] for x in jt])) + float(np.mean([x[2] for x in jt])) + float(np.mean([x[3] for x in jt]))
             + W_TIP * tip_d + W_CEN * float(np.mean(cen)) + W_IOU * (1 - float(np.mean(io))))
        if detail:
            return {"cost": round(c, 3), "fixed_jaw_edge_px": round(float(np.mean([x[1] for x in jt])), 2),
                    "moving_jaw_edge_px": round(float(np.mean([x[2] for x in jt])), 2),
                    "moving_jaw_edge_px_by_bin": {f"{BINS[t[0]][0]}-{BINS[t[0]][1]}": round(t[2], 2) for t in jt},
                    "fixed_jaw_tip_px": round(tip_d, 2), "real_fixed_tip_px": np.round(self.real_tip[tag], 1).tolist(),
                    "real_edge_to_sim_px": round(float(np.mean([x[3] for x in jt])), 2),
                    "table_frames": int(len(cen)), "table_block_centroid_px_median": round(float(np.median(cen)), 1),
                    "table_block_centroid_px_mean": round(float(np.mean(cen)), 1),
                    "table_block_centroid_px_p90": round(float(np.percentile(cen, 90)), 1),
                    "table_block_iou_mean": round(float(np.mean(io)), 3)}
        return c


def inner_edge(mask, side):
    """爪の内側の縁 (相手の爪に向いた側): 行ごとに 固定側は右の端, 動く爪は左の端. 絵の縁で切れる所・下の端は除く."""
    ys, xs = np.nonzero(mask[: S.H - INNER_BOTTOM])
    if not len(ys):
        return np.zeros((0, 2), int)
    order = np.lexsort((xs if side == "left" else -xs, ys))
    ys, xs = ys[order], xs[order]
    first = np.r_[True, ys[1:] != ys[:-1]]
    pts = np.c_[xs[first], ys[first]]
    return pts[(pts[:, 0] > 2) & (pts[:, 0] < S.W - 3)]


def contact_q_h(C, idx):
    """幅 21.7mm のブロックに 両方の爪が触れる角度 (合わせの本の つかんだコマで出し, 中央値)."""
    cams = S.load_cameras()
    maps = {k: S.DistortMap(cams[k]["K"], cams[k]["D"]) for k in ("desk", "wrist")}
    box330, base330, wrist330 = R.base_scene()
    sc = json.loads((R.OUT / "scene_334.json").read_text())
    rels = json.loads((R.OUT / "episodes_334.json").read_text())["scene"]["grasp_rel_333_wrist"]
    qs = []
    jaws = None
    for i in C["fit_eps"]:
        e = idx["episodes"][int(i)]
        _, st, _ = T.read_episode_any(e["source"], e["episode_index"])
        ev = R.grip_events(st[:, 5])
        if ev is None:
            continue
        b0 = sc["episodes"][int(i)]
        box, base = R.scene_of(sc, int(i), box330, base330)
        rp = R.Replay({"block": {"xy": b0["block_xy_mm"], "yaw": 0, "size": G.BLOCK_MM}, "box": box}, base, wrist330, maps, cams,
                      render=False)
        jaws = jaws or G.Jaws(rp.m)
        rp.pose_arm(st[ev["c"]])
        tip, a, b = rp.jaw_dirs()
        gp, gR = rp.gripper_pose()
        _, _, q, gaps = G.grasp_block_pose(jaws, gp, gR, tip, b, rels[str(e["place"])]["along"], G.BLOCK_MM, 0.0)
        qs.append(q)
    return float(np.median(qs)), float(np.min(qs)), float(np.max(qs)), jaws, rp.m


def fit_mode(idx):
    C = dict(np.load(CACHE))
    cams = S.load_cameras()
    K, Dd = cams["wrist"]["K"], cams["wrist"]["D"]
    holds = C["holds"]
    fit_set = set(C["fit_eps"].tolist())
    g_h = float(np.median([h for i, h in holds if int(i) in fit_set]))
    q_h, q_lo, q_hi, jaws, m = contact_q_h(C, idx)
    old = G.old_map(m)
    calib = json.loads(G.FOLLOWER_CALIB.read_text())["gripper"]
    k_calib = math.radians((calib["range_max"] - calib["range_min"]) * 360 / 4096 / 100)
    print("g_h", g_h, "q_h deg", math.degrees(q_h), "k_calib deg", math.degrees(k_calib), "old", old)
    P = Problem(C, jaws, K, Dd, q_h, g_h)
    wr330 = json.loads((R.C330 / "wrist_cam_330.json").read_text())["fit"]
    # 依頼 330 の付き方 + 依頼 330〜334 の換算 (k はそのまま. q_h を通らないので 動く爪は前の換算で別に測る)
    p330_old = np.r_[wr330["pos_mm"], wr330["rotvec"], old["k"]]

    def cost_old_map(p, tag):
        P2 = Problem.__new__(Problem)
        P2.__dict__.update(P.__dict__)
        P2.q_h, P2.g_h = old["q0"], 0.0
        return P2.cost(p, tag, detail=True)

    before = {"fit": cost_old_map(p330_old, "fit"), "chk": cost_old_map(p330_old, "chk")}
    print("before", before)
    x0 = np.r_[wr330["pos_mm"], wr330["rotvec"], k_calib]
    best = None
    for st in ([4, 4, 4, 0.05, 0.05, 0.05, 0.002],):
        x, v = nelder_mead(lambda p: P.cost(p), x0, st, iters=900, tol=1e-5)
        x, v = nelder_mead(lambda p: P.cost(p), x, [1.5, 1.5, 1.5, 0.02, 0.02, 0.02, 0.001], iters=600, tol=1e-6)
        if best is None or v < best[1]:
            best = (x, v)
    x = best[0]
    after = {"fit": P.cost(x, "fit", detail=True), "chk": P.cost(x, "chk", detail=True)}
    print("after", after)
    # 確かめ: 帯ごとに 動く爪の角度だけを自由に (1 つずつ)
    cam = P.cam(x)
    free = {}
    for tag in ("fit", "chk"):
        free[tag] = {}
        for b in range(len(BINS)):
            if (tag, b) not in P.dts or b == HOLD_BIN and False:
                continue
            dt = P.dts[(tag, b)]

            def cm(qd):
                mv = inner_edge(G.raster(jaws.tri_px([G.MOVING_MESH], math.radians(qd), cam)), "left")
                return float(np.mean(np.minimum(dt[mv[:, 1], mv[:, 0]], CAP_EDGE))) if len(mv) > 20 else CAP_EDGE
            qs = np.arange(-10.0, 100.0, 0.5)
            vals = np.array([cm(q) for q in qs])
            j = int(np.argmin(vals))
            lo, hi = qs[max(0, j - 1)], qs[min(len(qs) - 1, j + 1)]
            for _ in range(25):
                a1, a2 = lo + (hi - lo) / 3, hi - (hi - lo) / 3
                if cm(a1) < cm(a2):
                    hi = a2
                else:
                    lo = a1
            qb = (lo + hi) / 2
            free[tag][b] = {"g": round(P.gbin[(tag, b)], 2), "q_free_deg": round(qb, 2), "edge_px": round(cm(qb), 2),
                            "q_map_deg": round(math.degrees(P.q_of(P.gbin[(tag, b)], x[6])), 2),
                            "q_old_deg": round(math.degrees(G.g_to_q(old, P.gbin[(tag, b)], jaws.rng)), 2)}
    # 帯ごとの自由な角度に 直線を当てる (合わせの本. 閉じた 0〜2.5 は 爪どうしが当たって止まるので除く)
    pts = [(v["g"], v["q_free_deg"]) for b, v in free["fit"].items() if b not in (0,)]
    A = np.c_[np.ones(len(pts)), [p[0] for p in pts]]
    coef = np.linalg.lstsq(A, np.array([p[1] for p in pts]), rcond=None)[0]
    k_fit = float(x[6])
    q0_new = q_h - k_fit * g_h
    res = {
        "time": datetime.now().isoformat(timespec="seconds"), "made_by": "so101/sim/fit_wrist_grip_335.py (依頼 335)",
        "frame": "手首カメラ: gripper の body (MJCF so101_new_calib_camera.xml) の座標 mm. 向きは OpenCV のカメラ (x 右・y 下・z 前) の列",
        "split": {"fit_episodes": C["fit_eps"].tolist(), "check_episodes": C["chk_eps"].tolist(),
                  "how": "場所ごとに 新しい番号の順に交互 (0・2・4… 番目 = 合わせ, 1・3・5… = 確かめ)"},
        "gripper_map": {
            "formula": "q_rad = q0 + k × g (g = LeRobot の爪の値. 関節の範囲 [-0.1745, 1.7453] で頭打ち)",
            "old": {"q0_rad": round(old["q0"], 5), "k_rad_per_unit": round(old["k"], 6), "k_deg_per_unit": round(math.degrees(old["k"]), 4),
                    "q_at_g_h_deg": round(math.degrees(G.g_to_q(old, g_h, jaws.rng)), 2),
                    "note": "依頼 330〜334: 0〜100 を関節の下限〜上限に線形"},
            "new": {"q0_rad": round(q0_new, 5), "k_rad_per_unit": round(k_fit, 6), "k_deg_per_unit": round(math.degrees(k_fit), 4),
                    "q_at_g_h_deg": round(math.degrees(q_h), 2)},
            "g_h": round(g_h, 3), "g_h_how": "合わせの本の つかんでいる間の爪の値 (本ごとの中央値) の中央値",
            "q_h_deg": round(math.degrees(q_h), 3), "q_h_range_over_episodes_deg": [round(math.degrees(q_lo), 3), round(math.degrees(q_hi), 3)],
            "q_h_how": "幅 21.7mm のブロックを 固定側の爪の面に触れる所に置き, 動く爪が触れる角度 (すき間 0)",
            "k_from_servo_ticks_deg_per_unit": round(math.degrees(k_calib), 4),
            "k_from_servo_ticks_how": f"{G.FOLLOWER_CALIB.name} の gripper range {calib['range_min']}〜{calib['range_max']} × 360/4096 / 100",
            "free_angle_by_bin": free,
            "free_angle_line_fit_deg": {"q_at_g0": round(float(coef[0]), 2), "deg_per_unit": round(float(coef[1]), 4),
                                        "how": "合わせの本の帯ごとの自由な角度 (0〜2.5 を除く) に直線"}},
        "wrist_cam": {"before_330": {"pos_mm": wr330["pos_mm"], "rotvec": wr330["rotvec"]},
                      "after": {"pos_mm": np.round(x[:3], 2).tolist(), "rotvec": np.round(x[3:6], 5).tolist(),
                                "R_cols_xyz": np.round(S.rotvec_to_R(x[3:6]), 4).tolist()},
                      "moved_mm": round(float(np.linalg.norm(x[:3] - np.array(wr330["pos_mm"]))), 2),
                      "moved_xyz_mm": np.round(x[:3] - np.array(wr330["pos_mm"]), 2).tolist(),
                      "rotated_deg": round(math.degrees(np.linalg.norm(cv2.Rodrigues(S.rotvec_to_R(wr330["rotvec"]).T @ S.rotvec_to_R(x[3:6]))[0])), 2)},
        "scores": {"before_330_and_old_map": before, "after": after,
                   "how": "jaw_edge = シムの爪の輪郭から 実機の帯ごとの中央値の絵の縁までの距離 (px, 20 で頭打ち) の平均. "
                          "table_block = 机の上のブロックのコマの 赤い所の重心の差 (px, 80 で頭打ち) と IoU"},
        "weights": {"W_CEN": W_CEN, "W_IOU": W_IOU, "CAP_EDGE": CAP_EDGE, "CAP_CEN": CAP_CEN},
        "bins": BINS, "bin_g_median": {tag: {f"{BINS[b][0]}-{BINS[b][1]}": round(P.gbin[(tag, b)], 2) for b in range(len(BINS)) if (tag, b) in P.gbin}
                                      for tag in ("fit", "chk")},
    }
    OUT.mkdir(parents=True, exist_ok=True)
    G.FIT_JSON.write_text(json.dumps(res, ensure_ascii=False, indent=1))
    draw(P, C, p330_old, old, x)
    print(json.dumps({k: res[k] for k in ("gripper_map", "wrist_cam")}, ensure_ascii=False, indent=1))


def draw(P, C, p_old, old, x):
    cam_o, cam_n = P.cam(p_old), P.cam(x)
    rows = []
    for b in range(len(BINS)):
        if ("fit", b) not in P.dts:
            continue
        vis = C[f"med_fit_{b}"].copy()
        g = P.gbin[("fit", b)]
        for cam, q, col in ((cam_o, G.g_to_q(old, g, P.jaws.rng), (255, 0, 0)), (cam_n, P.q_of(g, x[6]), (0, 200, 0))):
            for names, qq in (([G.FIXED_JAW_MESH], 0.0), ([G.MOVING_MESH], q)):
                mk = G.raster(P.jaws.tri_px(names, qq, cam))
                cn, _ = cv2.findContours(mk.astype(np.uint8), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE)
                cv2.drawContours(vis, cn, -1, col, 2)
        cv2.putText(vis, f"g={g:.1f}  blue=before(330) green=after", (8, 26), cv2.FONT_HERSHEY_SIMPLEX, 0.7, (0, 0, 255), 2)
        rows.append(cv2.resize(vis, (427, 320)))
    while len(rows) % 3:
        rows.append(np.zeros_like(rows[0]))
    cv2.imwrite(str(OUT / "wrist_grip_fit_335.png"), np.vstack([np.hstack(rows[i:i + 3]) for i in range(0, len(rows), 3)]))
    # 机の上のブロック: 確かめの本から 8 枚
    its = P.table["chk"][:: max(1, len(P.table["chk"]) // 8)][:8]
    tiles = []
    for it in its:
        vis =np.full((S.H, S.W, 3), 255, np.uint8)
        vis[it["rm"]] = (0, 200, 255)
        for cam, col in ((cam_o, (255, 0, 0)), (cam_n, (0, 160, 0))):
            px, ok = G.project_wrist(it["c8"], cam, (it["gp"], it["gR"]))
            if ok.all():
                hm = hull_mask(px, (S.H, S.W))
                cn, _ = cv2.findContours(hm.astype(np.uint8), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE)
                cv2.drawContours(vis, cn, -1, col, 2)
        for names, qq, col in (([G.FIXED_JAW_MESH], 0.0, (120, 120, 120)),):
            mk = G.raster(P.jaws.tri_px(names, qq, cam_n))
            cn, _ = cv2.findContours(mk.astype(np.uint8), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE)
            cv2.drawContours(vis, cn, -1, col, 1)
        cv2.putText(vis, f"ep{it['ep']} f{it['frame']} yellow=real blue=before green=after", (8, 26), cv2.FONT_HERSHEY_SIMPLEX, 0.6,
                    (0, 0, 0), 2)
        tiles.append(cv2.resize(vis, (320, 240)))
    while len(tiles) % 4:
        tiles.append(np.zeros_like(tiles[0]))
    cv2.imwrite(str(OUT / "wrist_block_fit_335.png"), np.vstack([np.hstack(tiles[i:i + 4]) for i in range(0, len(tiles), 4)]))


def main():
    ap = argparse.ArgumentParser()
    ap.add_argument("--cache", action="store_true")
    ap.add_argument("--fit", action="store_true")
    args = ap.parse_args()
    idx = R.even_episodes()
    if args.cache:
        cache_mode(idx)
    if args.fit:
        fit_mode(idx)


if __name__ == "__main__":
    main()
