"""依頼 390 (2): 腕の細部の 置き方を 当てはめの本 (check_363/tune01. 割り振り 1. 比べる 3 本と別. 依頼 366 と同じ) の 実機の机側の絵に合わせる.
  --board : 手首カメラの基板の 黒い所 (実機: L < 40 の塊) に Blender の基板の四角を合わせる. 動かすのは 基板の面の中のずれ (e1・e2)・面の向きのずれ (n)・
            面の中の回り・面の傾き (e1・e2 まわり)・黒い所の大きさ (倍率). 費用 = 1 − IoU (写した四角 と 実機の黒い所) の平均
  --ring  : ケーブルの輪 (g18 の留め具の所の 黒い輪). 中心 (g18 の座標)・軸の向き・半径 を 実機のケーブルらしい画素 (fit_cable_366.real_cable_mask) に寄せる (輪 → 実機 の片向き)
  --cable2: 2 本目の黒い線 (手首のサーボ g20 から 肘 g12 へ 前腕に沿う線). 実機のケーブルらしい画素から 今の黒いケーブル (cable_366 の線) の 4px 以内を除いた所に 両向きで寄せる
  --loops : 手首のサーボ g20 の右の 赤白の線の輪 (g20 → g22. 依頼 366 の wire_wrist の当てはめ直し). 実機の赤い線らしい画素 (a* > 10. 腕から 45px・g20 の真ん中から 45px 以内) に
            両向きで寄せる. rest は 45mm 以上 (実機は サーボの上に立つ輪)
→ fit/<名>_390.json・figs/fit_<名>_390.png (当てはめの本の 6 コマに重ねた絵)

使い方 (conda の lerobot 環境で): python so101/sim/look_390/fit_390.py --board|--ring|--cable2|--loops
"""
import argparse
import json
import sys
from pathlib import Path

import cv2
import numpy as np

HERE = Path(__file__).resolve().parent
SO101 = HERE.parent.parent
sys.path.insert(0, str(SO101 / "blender"))
import cable_366 as CB  # noqa: E402
import fit_cable_366 as FC  # noqa: E402

SRC = SO101 / "check_363" / "tune01"
P = json.loads((SRC / "poses.json").read_text())
FR = P["frames"]
SHOW = [60, 120, 140, 180, 210, 240]
CAP = 15.0
MESH = np.load(SO101 / "check_361" / "scene" / "meshes.npz")
V32 = MESH["wrist_camera_so101_v1_v"].astype(float) * 1000
C0, NN, E1, E2 = CB.cam_board_frame(V32)
_part = CB.cam_face_parts(V32, MESH["wrist_camera_so101_v1_f"].astype(int))
_bv = V32[np.unique(MESH["wrist_camera_so101_v1_f"][_part == 0])]
U0, U1 = float(((_bv - C0) @ E1).min()), float(((_bv - C0) @ E1).max())
W0, W1 = float(((_bv - C0) @ E2).min()), float(((_bv - C0) @ E2).max())
BC = C0 + (U0 + U1) / 2 * E1 + (W0 + W1) / 2 * E2  # 基板の四角の真ん中 (g32 の座標 mm)
HU, HW = (U1 - U0) / 2, (W1 - W0) / 2


def real(k):
    return cv2.imread(str(SRC / "real" / f"{k:03d}_desk.png"))


def mjlab(k):
    return cv2.imread(str(SRC / "lab" / f"{k:03d}_desk.png"), 0)


def Lof(img):
    return cv2.cvtColor(img.astype(np.float32) / 255, cv2.COLOR_BGR2LAB)[..., 0]


def rot(axis, deg):
    a = np.radians(deg)
    axis = np.asarray(axis, float) / np.linalg.norm(axis)
    K = np.array([[0, -axis[2], axis[1]], [axis[2], 0, -axis[0]], [-axis[1], axis[0], 0]])
    return np.eye(3) + np.sin(a) * K + (1 - np.cos(a)) * K @ K


def board_M(x):
    """x = (du, dv, dn mm, 回り θ, 傾き a1 (e1 まわり), a2 (e2 まわり) 度, 倍率 s) → g32 の座標の 4×4 (mm. 基板の真ん中のまわり)."""
    du, dv, dn, th, a1, a2, s = x
    R = rot(E1, a1) @ rot(E2, a2) @ rot(NN, th)
    M = np.eye(4)
    M[:3, :3] = R * s
    M[:3, 3] = BC - M[:3, :3] @ BC + du * E1 + dv * E2 + dn * NN
    return M


def board_corners(x, inner=1.0):
    pts = [BC + su * HU * inner * E1 + sw * HW * inner * E2 for su, sw in ((-1, -1), (1, -1), (1, 1), (-1, 1))]
    M = board_M(x)
    return [M[:3, :3] @ p + M[:3, 3] for p in pts]


def poly_px(geoms, g, pts_mm):
    return FC.project(np.vstack([CB.world_pt(geoms, g, p) for p in pts_mm]))


class BoardFit:
    def __init__(self):
        self.items = []
        for f in FR:
            k = f["frame"]
            px = poly_px(f["geoms"], "g32", board_corners(np.array([0, 0, 0, 0, 0, 0, 1.0])))
            sim = np.zeros((480, 640), np.uint8)
            cv2.fillPoly(sim, [px.astype(np.int32)], 1)
            if sim.sum() < 400:
                continue
            L = Lof(real(k))
            near = cv2.dilate(sim, np.ones((41, 41), np.uint8)) > 0
            dark = ((L < 40) & near).astype(np.uint8)
            dark = cv2.morphologyEx(dark, cv2.MORPH_OPEN, np.ones((5, 5), np.uint8))
            dark = cv2.morphologyEx(dark, cv2.MORPH_CLOSE, np.ones((7, 7), np.uint8))
            n, cc, st, _ = cv2.connectedComponentsWithStats(dark, 8)
            if n < 2:
                continue
            ov = [int(((cc == j) & (sim > 0)).sum()) for j in range(n)]
            j = int(np.argmax(ov[1:])) + 1
            m = cc == j
            self.items.append((f, m, near))

    def cost(self, x):
        c = []
        for f, m, near in self.items:
            px = poly_px(f["geoms"], "g32", board_corners(x))
            sim = np.zeros(m.shape, np.uint8)
            cv2.fillPoly(sim, [px.astype(np.int32)], 1)
            s = sim > 0
            c.append(1 - (s & m).sum() / max(1, (s | m).sum()))
        return float(np.mean(c))


def descend(cost, x, step, lo, hi, rounds=4, n_rand=0, rng=None):
    best = cost(x)
    print("start", round(best, 4), flush=True)
    for j in range(n_rand):
        y = lo + rng.random(len(x)) * (hi - lo)
        cy = cost(y)
        if cy < best:
            best, x = cy, y
            print("rand", j, round(best, 4), flush=True)
    step = np.asarray(step, float)
    for r in range(rounds):
        improved = True
        while improved:
            improved = False
            for i in range(len(x)):
                for sgn in (1, -1):
                    y = x.copy()
                    y[i] = np.clip(y[i] + sgn * step[i], lo[i], hi[i])
                    if y[i] == x[i]:
                        continue
                    cy = cost(y)
                    if cy < best - 1e-5:
                        best, x, improved = cy, y, True
                        break
        print("round", r, round(best, 4), flush=True)
        step = step / 2
    return x, best


def fit_board():
    B = BoardFit()
    x0 = np.array([0, 0, 0, 0, 0, 0, 1.0])
    c0 = B.cost(x0)
    lo = np.array([-8, -8, -6, -20, -20, -20, 0.7])
    hi = np.array([8, 8, 6, 20, 20, 20, 1.2])
    x, best = descend(B.cost, x0.copy(), [2, 2, 2, 4, 4, 4, 0.05], lo, hi, rounds=5)
    res = {"made_by": "so101/sim/look_390/fit_390.py --board (依頼 390)", "book": "check_363/tune01", "frames": len(B.items),
           "how": "実機の机側の絵で 基板のまわり 20px の L < 40 の塊 (開いて閉じた) と, Blender の基板の四角 (g32 の形の 基板の面の外接の四角) を写したものの IoU を上げる",
           "board_mm": {"u": [round(U0, 2), round(U1, 2)], "v": [round(W0, 2), round(W1, 2)], "center_g32": [round(float(v), 2) for v in BC]},
           "x_names": ["du_mm (e1)", "dv_mm (e2)", "dn_mm (法線)", "回り 度 (法線まわり)", "傾き 度 (e1 まわり)", "傾き 度 (e2 まわり)", "黒い所の倍率"],
           "x": [round(float(v), 3) for v in x], "cost_before": round(c0, 4), "cost_after": round(best, 4),
           "M_g32_mm": board_M(x).round(5).tolist()}
    (HERE / "fit" / "board_390.json").write_text(json.dumps(res, ensure_ascii=False, indent=1))
    print(json.dumps({k: res[k] for k in ("x", "cost_before", "cost_after", "frames")}))
    tiles = []
    for f, m, near in B.items:
        if f["frame"] not in SHOW:
            continue
        im = real(f["frame"])
        im[m & ~cv2.erode(m.astype(np.uint8), np.ones((3, 3), np.uint8)).astype(bool)] = (0, 255, 255)
        for xx, col in ((x0, (0, 0, 255)), (x, (0, 255, 0))):
            cv2.polylines(im, [poly_px(f["geoms"], "g32", board_corners(xx)).astype(np.int32)], True, col, 1, cv2.LINE_AA)
        tiles.append(crop_at(im, poly_px(f["geoms"], "g32", board_corners(x)).mean(0), 70, 4))
    save_tiles(tiles, "fit_board_390.png")


def crop_at(im, c, h, z):
    x0 = int(np.clip(c[0] - h, 0, 640 - 2 * h))
    y0 = int(np.clip(c[1] - h, 0, 480 - 2 * h))
    return cv2.resize(im[y0:y0 + 2 * h, x0:x0 + 2 * h], None, fx=z, fy=z, interpolation=cv2.INTER_NEAREST)


def save_tiles(tiles, name):
    if not tiles:
        return
    while len(tiles) % 3:
        tiles.append(np.zeros_like(tiles[0]))
    cv2.imwrite(str(HERE / "figs" / name), np.vstack([np.hstack(tiles[i:i + 3]) for i in range(0, len(tiles), 3)]))


# ---- 輪 ----
def ring_pts(geoms, x, n=36):
    """x = (中心 g18 の座標 mm ×3, 軸の向き (方位・仰角 度. g18 の座標), 半径 mm)."""
    c = x[:3]
    az, el, R = np.radians(x[3]), np.radians(x[4]), x[5]
    ax = np.array([np.cos(el) * np.cos(az), np.cos(el) * np.sin(az), np.sin(el)])
    a = np.cross(ax, [0, 0, 1.0]) if abs(ax[2]) < 0.9 else np.cross(ax, [1.0, 0, 0])
    a /= np.linalg.norm(a)
    b = np.cross(ax, a)
    t = np.linspace(0, 2 * np.pi, n, endpoint=False)
    return [c + R * (np.cos(tt) * a + np.sin(tt) * b) for tt in t], ax, a, b


class MaskFit:
    """線 (画素の並び) を 実機のマスクに寄せる費用 (片向き = 線 → 実機, 両向き = さらに 実機 (範囲 roi の中) → 線)."""

    def __init__(self, mask_fn, frames, both=False):
        self.items = []
        for f in FR:
            if f["frame"] not in frames:
                continue
            m = mask_fn(f)
            if m is None or m.sum() < 20:
                continue
            D = np.minimum(cv2.distanceTransform((~m).astype(np.uint8), cv2.DIST_L2, 3), CAP)
            self.items.append((f, m, D))
        self.both = both

    def cost_px(self, pxs):
        tot = []
        for (f, m, D), px in zip(self.items, pxs):
            px = FC.dense(px)
            ins = (px[:, 0] >= 0) & (px[:, 0] < 639) & (px[:, 1] >= 0) & (px[:, 1] < 479)
            q = px[ins].astype(int)
            t1 = float(D[q[:, 1], q[:, 0]].mean()) if len(q) else CAP
            t2 = 0.0
            if self.both:
                sim = np.zeros(m.shape, np.uint8)
                cv2.polylines(sim, [px.astype(np.int32)], False, 1, 1)
                Ds = np.minimum(cv2.distanceTransform((1 - sim).astype(np.uint8), cv2.DIST_L2, 3), CAP)
                t2 = float(Ds[m].mean())
            tot.append(t1 + t2)
        return float(np.mean(tot))


def cam_cable_mask(f, wide=4):
    """今の黒いケーブル (cable_366 の線) を写した所 (wide px 広げた)."""
    m = np.zeros((480, 640), np.uint8)
    for nm, Pp, r, kind in CB.all_lines(f["geoms"]):
        if kind == "cam":
            cv2.polylines(m, [FC.project(Pp).astype(np.int32)], False, 1, 2 * wide + 1)
    return m > 0


def fit_ring():
    c18 = np.array(CB.CAM_CABLE[1][1], float)
    F = MaskFit(ring_mask, {f["frame"] for f in FR}, both=True)
    cost = lambda x: F.cost_px([FC.project(np.vstack([CB.world_pt(f["geoms"], "g18", p) for p in ring_pts(f["geoms"], x)[0] + [ring_pts(f["geoms"], x)[0][0]]])) for f, _, _ in F.items])  # noqa: E731
    best_all = None
    rng = np.random.default_rng(0)
    lo = np.r_[c18 - 10, -180, -90, 5.0]
    hi = np.r_[c18 + 10, 180, 90, 8.0]
    for az in range(-180, 180, 45):
        for el in (-60, -20, 20, 60):
            x0 = np.r_[c18, az, el, 6.0]
            c = cost(x0)
            if best_all is None or c < best_all[1]:
                best_all = (x0, c)
    x, best = descend(cost, best_all[0].copy(), [2, 2, 2, 20, 20, 1.0], lo, hi, rounds=4, n_rand=300, rng=rng)
    # 輪がない (0) との比べ: 輪の点を ケーブルの留め位置 1 点に縮めたときの 費用
    res = {"made_by": "so101/sim/look_390/fit_390.py --ring (依頼 390)", "book": "check_363/tune01", "frames": len(F.items),
           "how": "輪 (36 点の円) と 実機の輪らしい画素 (ケーブルらしい画素のうち 留め具の点から 30px 以内で 今の黒いケーブルから 3px より外) を 両向きの距離 (上限 15px) で寄せる. 半径 5〜8mm (片向きでは 輪が縮んでケーブルに重なったので). 出発点は 留め具の点 (cable_fit_366 の g18)・軸 32 通り",
           "geom": "g18", "center_mm": [round(float(v), 2) for v in x[:3]], "axis_az_el_deg": [round(float(x[3]), 1), round(float(x[4]), 1)],
           "axis_g18": [round(float(v), 4) for v in ring_pts(None, x)[1]], "R_mm": round(float(x[5]), 2), "cost_px": round(best, 3)}
    (HERE / "fit" / "ring_390.json").write_text(json.dumps(res, ensure_ascii=False, indent=1))
    print(json.dumps(res, ensure_ascii=False))
    tiles = []
    for f in FR:
        if f["frame"] not in SHOW:
            continue
        im = real(f["frame"])
        px = FC.project(np.vstack([CB.world_pt(f["geoms"], "g18", p) for p in ring_pts(None, x)[0]]))
        cv2.polylines(im, [px.astype(np.int32)], True, (0, 255, 0), 1, cv2.LINE_AA)
        tiles.append(crop_at(im, px.mean(0), 60, 4))
    save_tiles(tiles, "fit_ring_390.png")


def ring_mask(f):
    k = f["frame"]
    c = FC.project(CB.world_pt(f["geoms"], "g18", CB.CAM_CABLE[1][1]))[0]
    near = np.zeros((480, 640), np.uint8)
    cv2.circle(near, (int(c[0]), int(c[1])), 30, 1, -1)
    m = FC.real_cable_mask(real(k), mjlab(k)) & (near > 0) & ~cam_cable_mask(f, 3)
    return m if m.sum() >= 20 else None


# ---- 2 本目の線・輪 (chain) ----
def chain_px(geoms, anchors, rests, outs):
    old = CB.SAG_GRAVITY
    CB.SAG_GRAVITY = 0.3
    try:
        Pp = CB.chain(geoms, anchors, rests, outs, n_sag=8, n_per=3)
    finally:
        CB.SAG_GRAVITY = old
    return FC.project(Pp)


def chain_from_x(x, gs):
    """x = (点 ×3 を 留め位置の数だけ, rest ×(区間), 外向き ×3 ×(区間)) → anchors・rests・outs."""
    n = len(gs)
    anchors = [(g, tuple(x[3 * i:3 * i + 3])) for i, g in enumerate(gs)]
    r = x[3 * n:3 * n + n - 1]
    rests = [None if v <= 0 else float(v) for v in r]
    o = x[4 * n - 1:]
    outs = [(gs[i], tuple(o[3 * i:3 * i + 3])) for i in range(n - 1)]
    return anchors, rests, outs


def fit_chain(name, gs, x0, half, mask_fn, rest_hi=200.0, n_rand=1500, rest_lo=0.0):
    """half: 留め位置を動かす幅 mm (1 つの値か 留め位置ごと). rest_hi・rest_lo: 区間ごとの rest の範囲 (0 = 張る)."""
    F = MaskFit(mask_fn, {f["frame"] for f in FR}, both=True)
    n = len(gs)
    cost = lambda x: F.cost_px([chain_px(f["geoms"], *chain_from_x(x, gs)) for f, _, _ in F.items])  # noqa: E731
    x0 = np.asarray(x0, float)
    lo, hi = x0.copy(), x0.copy()
    hw = np.repeat(np.broadcast_to(np.asarray(half, float), (n,)), 3)
    lo[:3 * n], hi[:3 * n] = x0[:3 * n] - hw, x0[:3 * n] + hw
    lo[3 * n:4 * n - 1], hi[3 * n:4 * n - 1] = rest_lo, rest_hi
    lo[4 * n - 1:], hi[4 * n - 1:] = -1, 1
    step = np.r_[np.full(3 * n, 3.0), np.full(n - 1, 15.0), np.full(3 * (n - 1), 0.3)]
    x, best = descend(cost, x0.copy(), step, lo, hi, rounds=4, n_rand=n_rand, rng=np.random.default_rng(1))
    anchors, rests, outs = chain_from_x(x, gs)
    res = {"made_by": f"so101/sim/look_390/fit_390.py --{name} (依頼 390)", "book": "check_363/tune01", "frames": len(F.items),
           "cost_px_before": round(cost(x0), 3), "cost_px": round(best, 3),
           "anchors": [[g, [round(float(v), 2) for v in p]] for g, p in anchors], "rest_mm": [None if r is None else round(r, 1) for r in rests],
           "out": [[g, [round(float(v), 3) for v in o]] for g, o in outs], "sag_gravity": 0.3}
    (HERE / "fit" / f"{name}_390.json").write_text(json.dumps(res, ensure_ascii=False, indent=1))
    print(json.dumps(res, ensure_ascii=False))
    tiles = []
    for f, m, _ in F.items:
        if f["frame"] not in SHOW:
            continue
        im = real(f["frame"])
        im[m] = (im[m] * 0.4 + np.array([255, 0, 255]) * 0.6).astype(np.uint8)
        px = chain_px(f["geoms"], anchors, rests, outs)
        cv2.polylines(im, [px.astype(np.int32)], False, (0, 255, 0), 1, cv2.LINE_AA)
        tiles.append(crop_at(im, px.mean(0), 110, 2))
    save_tiles(tiles, f"fit_{name}_390.png")


class PairFit(MaskFit):
    """2 本目の線の費用: 線 → 実機 (片向き) + 実機 → (今の黒いケーブル と 2 本目 の近い方). 今のケーブルで説明できる実機の画素には 2 本目を寄せない."""

    def __init__(self, frames):
        super().__init__(lambda f: FC.real_cable_mask(real(f["frame"]), mjlab(f["frame"])), frames, both=False)
        self.cam = []
        for f, m, D in self.items:
            c = np.zeros(m.shape, np.uint8)
            for nm, Pp, r, kind in CB.all_lines(f["geoms"]):
                if kind == "cam":
                    cv2.polylines(c, [FC.dense(FC.project(Pp)).astype(np.int32)], False, 1, 1)
            self.cam.append(c)

    def cost_px(self, pxs):
        tot = []
        for (f, m, D), c, px in zip(self.items, self.cam, pxs):
            px = FC.dense(px)
            ins = (px[:, 0] >= 0) & (px[:, 0] < 639) & (px[:, 1] >= 0) & (px[:, 1] < 479)
            q = px[ins].astype(int)
            t1 = float(D[q[:, 1], q[:, 0]].mean()) if len(q) else CAP
            sim = c.copy()
            cv2.polylines(sim, [px.astype(np.int32)], False, 1, 1)
            Ds = np.minimum(cv2.distanceTransform((1 - sim).astype(np.uint8), cv2.DIST_L2, 3), CAP)
            tot.append(t1 + float(Ds[m].mean()))
        return float(np.mean(tot))


def fit_cable2b():
    """2 本目の線 = 今の黒いケーブルと同じ通り (留め具 g18 → 台座 g3. 依頼 366 の当てはめの値の まわり) を サーボ g20 の差し口から始める."""
    F = PairFit({f["frame"] for f in FR})
    gs = ["g20", "g18", "g3"]
    o3 = CB.CAM_OUT[1][1]
    x0 = np.r_[[-20.4, 14.5, 29.9], CB.CAM_CABLE[1][1], CB.CAM_CABLE[2][1], [40.0, CB.CAM_REST_MM[1]], [0, 0, 1.0], o3]
    n = 3
    lo, hi = x0.copy(), x0.copy()
    lo[:9] -= np.r_[[4] * 3, [10] * 3, [20] * 3]
    hi[:9] += np.r_[[4] * 3, [10] * 3, [20] * 3]
    lo[9:11], hi[9:11] = [0, CB.CAM_REST_MM[1] - 60], [90, CB.CAM_REST_MM[1] + 60]
    lo[11:], hi[11:] = -1, 1
    cost = lambda x: F.cost_px([chain_px(f["geoms"], *chain_from_x(x, gs)) for f, _, _ in F.items])  # noqa: E731
    c_cam_only = float(np.mean([float(np.minimum(cv2.distanceTransform((1 - c).astype(np.uint8), cv2.DIST_L2, 3), CAP)[m].mean())
                                for (f, m, D), c in zip(F.items, F.cam)]))
    step = np.r_[np.full(9, 3.0), [15.0, 20.0], np.full(6, 0.3)]
    x, best = descend(cost, x0.copy(), step, lo, hi, rounds=4, n_rand=600, rng=np.random.default_rng(2))
    anchors, rests, outs = chain_from_x(x, gs)
    res = {"made_by": "so101/sim/look_390/fit_390.py --cable2 (依頼 390)", "book": "check_363/tune01", "frames": len(F.items),
           "how": "費用 = 2 本目 → 実機のケーブルらしい画素 + 実機の画素 → (今の黒いケーブル と 2 本目 の近い方) (両方 上限 15px). 2 本目は 今のケーブルの通り (g18 → g3) の まわり ±10〜20mm で サーボ g20 の差し口から始める",
           "cost_px_start": round(cost(x0), 3), "cost_px": round(best, 3), "real_to_cam_only_px": round(c_cam_only, 3),
           "anchors": [[g, [round(float(v), 2) for v in p]] for g, p in anchors], "rest_mm": [None if r is None else round(r, 1) for r in rests],
           "out": [[g, [round(float(v), 3) for v in o]] for g, o in outs], "sag_gravity": 0.3}
    (HERE / "fit" / "cable2_390.json").write_text(json.dumps(res, ensure_ascii=False, indent=1))
    print(json.dumps(res, ensure_ascii=False))
    tiles = []
    for (f, m, _), c in zip(F.items, F.cam):
        if f["frame"] not in SHOW:
            continue
        im = real(f["frame"])
        im[m] = (im[m] * 0.4 + np.array([255, 0, 255]) * 0.6).astype(np.uint8)
        im[c > 0] = (0, 200, 255)
        px = chain_px(f["geoms"], anchors, rests, outs)
        cv2.polylines(im, [px.astype(np.int32)], False, (0, 255, 0), 1, cv2.LINE_AA)
        tiles.append(crop_at(im, px.mean(0), 110, 2))
    save_tiles(tiles, "fit_cable2_390.png")


def cable2_mask(f):
    k = f["frame"]
    m = FC.real_cable_mask(real(k), mjlab(k)) & ~cam_cable_mask(f, 4)
    n, cc, st, _ = cv2.connectedComponentsWithStats(m.astype(np.uint8), 8)
    keep = np.zeros(n, bool)
    keep[1:] = st[1:, cv2.CC_STAT_AREA] >= 40
    return keep[cc]


def wire_mask(f):
    k = f["frame"]
    img, lab = real(k), mjlab(k)
    A = cv2.cvtColor(img.astype(np.float32) / 255, cv2.COLOR_BGR2LAB)[..., 1]
    arm = np.isin(lab, (2, 3, 7)).astype(np.uint8)
    near = cv2.dilate(arm, cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (91, 91))) > 0
    m = ((A > 10) & near & (lab != 4)).astype(np.uint8)
    n, cc, st, _ = cv2.connectedComponentsWithStats(m, 8)
    keep = np.zeros(n, bool)
    keep[1:] = (st[1:, cv2.CC_STAT_AREA] >= 6) & (st[1:, cv2.CC_STAT_AREA] <= 300)
    return keep[cc]


def wire_mask_near(f):
    """赤い線らしい画素のうち 手首のサーボ g20 の真ん中から 45px 以内 (遠くの赤 (爪の後ろ・肘の線) に引かれないように)."""
    m = wire_mask(f)
    c = FC.project(CB.world_pt(f["geoms"], "g20", (0, 0, 0)))[0]
    near = np.zeros(m.shape, np.uint8)
    cv2.circle(near, (int(c[0]), int(c[1])), 45, 1, -1)
    m = m & (near > 0)
    return m if m.sum() >= 15 else None


def main():
    ap = argparse.ArgumentParser()
    ap.add_argument("--board", action="store_true")
    ap.add_argument("--ring", action="store_true")
    ap.add_argument("--cable2", action="store_true")
    ap.add_argument("--loops", action="store_true")
    a = ap.parse_args()
    if a.board:
        fit_board()
    if a.ring:
        fit_ring()
    if a.cable2:
        fit_cable2b()
    if False:
        # 手首のサーボ g20 の 左の差し口 (grid の点) → 留め具 g18 (黒いケーブルの留め位置の横) → 前腕 g16 → 肘のサーボ g12 (grid の点)
        gs = ["g20", "g18", "g16", "g12"]
        x0 = np.r_[[-20.4, 14.5, 29.9], np.array(CB.CAM_CABLE[1][1]) + [0, 0, 4], [-14.0, -30.0, 0.0], [-18.4, -27.5, -24.1],
                   [40, 0, 0], [0, 0, 1, 0, 0, 1, 0, 0, 1]]  # 留め位置 4 つ・rest 3 つ・外向き 3 つ
        # 下の 2 区間は張る (前腕に沿う. 1 回目は rest を自由にして 外へ大きくふくらんだ). 最初の区間 (サーボの差し口 → 留め具) だけ たるむ
        fit_chain("cable2", gs, x0, [3.0, 6.0, 10.0, 6.0], cable2_mask, rest_hi=np.array([90.0, 0, 0]), rest_lo=np.array([0.0, 0, 0]), n_rand=800)
    if a.loops:
        # 左の輪: g20 の 左の差し口 → g18 (留め具の手前) の 輪. 右の輪は 依頼 366 の wire_wrist (g20 → g22) を当てはめ直す
        w = json.loads((SO101 / "check_366" / "cable_fit_366.json").read_text())["servo_wires"][0]
        x0 = np.r_[w["a"][1], w["b"][1], [w["rest_mm"]], w["out"][1]]
        # 1 回目 (look_390_loopR で使った = fit/loop_right_390.json): fit_chain("loop_right", ["g20", "g22"], x0, 8.0, wire_mask, rest_hi=120.0, n_rand=600)
        # 2 回目 (下. 使っていない): g20 のまわりだけ・rest 45mm 以上
        fit_chain("loop_right2", ["g20", "g22"], x0, 8.0, wire_mask_near, rest_hi=120.0, n_rand=600, rest_lo=45.0)
        # 左の輪 (g20 → g18) も試したが サーボの上を横切る形になり 実機と合わなかった (fit/loop_left_390.json. 使わない)


if __name__ == "__main__":
    main()
