"""依頼 445: 黒いケーブル (輪・うねり) と サーボの撚った線の 通り道を 当てはめの本 (check_363/tune01. 比べる 3 本と別. 依頼 366 と同じ) の
実機の机側の絵に寄せる. 測り方は 依頼 366 の fit_cable_366.Fitter と同じ: 実機のケーブルらしい画素 (real_cable_mask) と 写した線の
距離 (上限 15px) を 両向きに足した値 (シム → 実機 + 実機 → シム) を 値を 1 つずつ動かして下げる (始めに 無作為に試す).
サーボの線は real_wire_mask (腕のそばの赤い画素) に寄せる (実機 → シム は 手首のサーボ g20・g22 から 60px 以内の赤だけ).

使い方 (conda の lerobot 環境で): python so101/sim/look_445/fit_445.py --cam --wire   → fit_445.json・figs/fit_445_<cam|wire>.jpg
"""
import argparse
import copy
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"))
sys.path.insert(0, str(HERE))
import fit_cable_366 as FC  # noqa: E402
import cable_366 as CB  # noqa: E402
import cable_445 as C5  # noqa: E402

SRC = SO101 / "check_363" / "tune01"
FRAMES = list(range(0, 251, 10))
CAP = 15.0
CB.load_fit()
L393 = json.loads((HERE.parent / "look_393" / "look_393_A.json").read_text())

# 黒いケーブルの出発点: 366 の 3 つの留め位置 (差し込み g32・輪の留め具 g18・台座 g3) に 腕に沿う 2 つ (前腕 g16・上腕 g14) を足す
CAM0 = {
    "anchors": [["g32", L393["cable"]["cam_cable"][0][1]], ["g18", L393["cable"]["cam_cable"][1][1]], ["g16", [0.0, 0.0, 0.0]],
                ["g14", [0.0, 0.0, 0.0]], ["g3", L393["cable"]["cam_cable"][2][1]]],
    "rest_mm": [69.5, 80.0, 80.0, 150.0],
    "out": [["g18", [1.0, 0.0, 0.0]], ["g16", [1.0, 0.0, 0.0]], ["g14", [1.0, 0.0, 0.0]], ["g14", [1.0, 0.0, 0.0]]],
    "gravity": 0.0, "loop_at": 1, "loop_r_mm": 0.0, "loop_u": [1.0, 0.0, 0.0], "loop_v": [0.0, 1.0, 0.0],
    "radius_mm": L393["cable"]["cam_radius_mm"], "n_pts": 160,
}
W366 = L393["cable"]["servo_wires"][0]
WIRE0 = {"name": "wire_wrist", "a": W366["a"], "b": W366["b"], "rest_mm": W366["rest_mm"], "out": W366["out"], "gravity": 0.0}


class Data:
    def __init__(self, mask):
        P = json.loads((SRC / "poses.json").read_text())
        self.fr = [f for f in P["frames"] if f["frame"] in FRAMES]
        self.R, self.D = [], []
        for f in self.fr:
            k = f["frame"]
            img = cv2.imread(str(SRC / "real" / f"{k:03d}_desk.png"))
            lab = cv2.imread(str(SRC / "lab" / f"{k:03d}_desk.png"), 0)
            m = mask(img, lab)
            self.R.append(m)
            self.D.append(np.minimum(cv2.distanceTransform((~m).astype(np.uint8), cv2.DIST_L2, 3), CAP))


def two_way(px_list, D, R, near=None):
    """写した線 (画素の並びの list) と 実機の画素の 両向きの距離 (366 の Fitter.cost と同じ)."""
    sim = np.zeros(R.shape, np.uint8)
    t1, n1 = 0.0, 0
    for px in px_list:
        px = FC.dense(px)
        ok = (px[:, 0] >= 0) & (px[:, 0] < 639) & (px[:, 1] >= 0) & (px[:, 1] < 479)
        q = px[ok].astype(int)
        t1 += float(D[q[:, 1], q[:, 0]].sum())
        n1 += len(q)
        cv2.polylines(sim, [px.astype(np.int32)], False, 1, 1)
    t1 = t1 / n1 if n1 else CAP
    Rm = R if near is None else (R & near)
    Ds = np.minimum(cv2.distanceTransform((1 - sim).astype(np.uint8), cv2.DIST_L2, 3), CAP)
    t2 = float(Ds[Rm].mean()) if Rm.sum() > 30 else 0.0
    return t1, t2


# ---- 黒いケーブル -----------------------------------------------------------------
def cam_vec(c):
    x = []
    for _, p in c["anchors"]:
        x += list(p)
    x += list(c["rest_mm"])
    for _, o in c["out"]:
        x += list(o)
    return np.array(x, float)


def cam_set(c, x):
    c = copy.deepcopy(c)
    n = len(c["anchors"])
    for i in range(n):
        c["anchors"][i][1] = [float(v) for v in x[3 * i:3 * i + 3]]
    c["rest_mm"] = [float(v) for v in x[3 * n:4 * n - 1]]
    for i in range(n - 1):
        c["out"][i][1] = [float(v) for v in x[4 * n - 1 + 3 * i:4 * n + 2 + 3 * i]]
    return c


def cam_cost(Dt, c, verbose=False):
    tot, per = 0.0, []
    for f, D, R in zip(Dt.fr, Dt.D, Dt.R):
        t1, t2 = two_way([FC.line_px(C5.cam_line(f["geoms"], c))], D, R)
        tot += t1 + t2
        per.append((f["frame"], round(t1, 2), round(t2, 2)))
    return (tot / len(Dt.fr), per) if verbose else tot / len(Dt.fr)


def search(cost, x0, lo, hi, step, n_rand, rounds, fixed=(), seed=0):
    rng = np.random.default_rng(seed)
    x, best = x0.copy(), cost(x0)
    print("start", round(best, 3), flush=True)
    for j in range(n_rand):
        y = lo + rng.random(len(x)) * (hi - lo)
        y[list(fixed)] = x0[list(fixed)]
        c = cost(y)
        if c < best:
            best, x = c, y
            print("rand", j, round(best, 3), flush=True)
    for r in range(rounds):
        improved = True
        while improved:
            improved = False
            for i in range(len(x)):
                if step[i] == 0:
                    continue
                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
                    c = cost(y)
                    if c < best - 1e-4:
                        best, x, improved = c, y, True
                        break
        print("round", r, round(best, 3), flush=True)
        step = step / 2
    return x, best


def fit_cam(n_rand, rounds):
    Dt = Data(FC.real_cable_mask)
    c0 = copy.deepcopy(CAM0)
    n = len(c0["anchors"])
    x0 = cam_vec(c0)
    lo, hi = x0.copy(), x0.copy()
    lo[0:3], hi[0:3] = x0[0:3] - 1, x0[0:3] + 1        # 差し込み (366 のまま ±1mm)
    lo[3:6], hi[3:6] = x0[3:6] - 2, x0[3:6] + 2        # 輪の留め具 (366 のまま ±2mm)
    for i in (2, 3):                                   # 腕に沿う留め位置: 形の外接の箱 ±12mm
        a, b = FC.mesh_box(c0["anchors"][i][0])
        lo[3 * i:3 * i + 3], hi[3 * i:3 * i + 3] = a - 12, b + 12
        x0[3 * i:3 * i + 3] = (a + b) / 2
    lo[12:15], hi[12:15] = x0[12:15] - 10, x0[12:15] + 10  # 台座 (366 ±10mm)
    lo[3 * n:4 * n - 1], hi[3 * n:4 * n - 1] = 0, 300
    lo[4 * n - 1:], hi[4 * n - 1:] = -1, 1
    step = np.r_[np.full(3 * n, 4.0), np.full(n - 1, 30.0), np.full(3 * (n - 1), 0.3)]
    fixed = list(range(6))
    x, best = search(lambda y: cam_cost(Dt, cam_set(c0, y)), x0, lo, hi, step, n_rand, rounds, fixed)
    c = cam_set(c0, x)
    base = cam_cost(Dt, {**c, "anchors": [c["anchors"][0], c["anchors"][1], c["anchors"][4]], "rest_mm": L393["cable"]["cam_rest_mm"],
                         "out": [None, ["g16", L393["cable"]["cam_out"][1][1]]], "loop_r_mm": 0.0})
    # 輪: 留め具 g18 の所に 半径 r の 1 回り. 輪の面は g18 の座標の 2 つの軸 (符号も) から 一番合うもの
    axes = [[1, 0, 0], [0, 1, 0], [0, 0, 1], [-1, 0, 0], [0, -1, 0], [0, 0, -1]]
    loop = []
    for r in (0.0, 3.0, 4.0, 5.0, 6.0, 8.0):
        for u in axes:
            for v in axes:
                if np.abs(np.dot(u, v)) > 0 or (r == 0 and (u, v) != (axes[0], axes[1])):
                    continue
                cc = {**c, "loop_r_mm": r, "loop_u": u, "loop_v": v}
                loop.append((cam_cost(Dt, cc), r, u, v))
    loop.sort(key=lambda t: t[0])
    c.update({"loop_r_mm": loop[0][1], "loop_u": loop[0][2], "loop_v": loop[0][3]})
    tot, per = cam_cost(Dt, c, verbose=True)
    print("cam 366", round(base, 3), "→ 445", round(tot, 3), "loop", loop[0][1:], flush=True)
    return c, {"cost_366_px": round(base, 3), "cost_445_no_loop_px": round(best, 3), "cost_445_px": round(tot, 3),
               "loop_tries": [[round(t[0], 3), t[1], t[2], t[3]] for t in loop[:8]], "per_frame": per}


# ---- サーボの線 -------------------------------------------------------------------
def wire_vec(w):
    return np.array(list(w["a"][1]) + list(w["b"][1]) + [w["rest_mm"]] + list(w["out"][1]), float)


def wire_set(w, x):
    w = copy.deepcopy(w)
    w["a"][1], w["b"][1] = [float(v) for v in x[0:3]], [float(v) for v in x[3:6]]
    w["rest_mm"] = float(x[6])
    w["out"][1] = [float(v) for v in x[7:10]]
    return w


def wire_cost(Dt, w, verbose=False):
    tot, per = 0.0, []
    for f, D, R in zip(Dt.fr, Dt.D, Dt.R):
        g = f["geoms"]
        ctr = FC.project(np.vstack([CB.world_pt(g, "g20", (0, 0, 0)), CB.world_pt(g, "g22", (0, 0, 0))]))
        near = np.zeros(R.shape, np.uint8)
        for p in ctr:
            cv2.circle(near, tuple(int(v) for v in p), 60, 1, -1)
        _, C = C5.wire_lines(g, w, 0.0, 10.0, 60)
        t1, t2 = two_way([FC.line_px(C)], D, R, near > 0)
        tot += t1 + t2
        per.append((f["frame"], round(t1, 2), round(t2, 2)))
    return (tot / len(Dt.fr), per) if verbose else tot / len(Dt.fr)


def fit_wire(n_rand, rounds):
    Dt = Data(FC.real_wire_mask)
    w0 = copy.deepcopy(WIRE0)
    x0 = wire_vec(w0)
    lo = np.r_[x0[0:6] - 8, 25.0, -1, -1, -1]
    hi = np.r_[x0[0:6] + 8, 120.0, 1, 1, 1]
    step = np.r_[np.full(6, 3.0), 15.0, np.full(3, 0.3)]
    base = wire_cost(Dt, w0)
    x, best = search(lambda y: wire_cost(Dt, wire_set(w0, y)), x0, lo, hi, step, n_rand, rounds)
    w = wire_set(w0, x)
    tot, per = wire_cost(Dt, w, verbose=True)
    print("wire 366", round(base, 3), "→ 445", round(tot, 3), flush=True)
    return w, {"cost_366_px": round(base, 3), "cost_445_px": round(tot, 3), "per_frame": per}


def figure(cam, wire, name, frames=(40, 80, 140, 200, 230)):
    P = json.loads((SRC / "poses.json").read_text())
    fr = {f["frame"]: f for f in P["frames"]}
    tiles = []
    for k in frames:
        img = cv2.imread(str(SRC / "real" / f"{k:03d}_desk.png"))
        lab = cv2.imread(str(SRC / "lab" / f"{k:03d}_desk.png"), 0)
        img[FC.real_cable_mask(img, lab)] = (0, 160, 0)
        img[FC.real_wire_mask(img, lab)] = (160, 0, 0)
        g = fr[k]["geoms"]
        cv2.polylines(img, [FC.line_px(CB.cam_cable(g)).astype(np.int32)], False, (0, 200, 255), 1, cv2.LINE_AA)  # 366 (橙)
        if cam:
            cv2.polylines(img, [FC.line_px(C5.cam_line(g, cam)).astype(np.int32)], False, (255, 0, 255), 1, cv2.LINE_AA)  # 445 (赤紫)
        if wire:
            for P_ in C5.wire_lines(g, wire, 0.5, 8.0, 60)[0]:
                cv2.polylines(img, [FC.line_px(P_).astype(np.int32)], False, (0, 0, 255), 1, cv2.LINE_AA)
        cv2.putText(img, f"f{k}", (5, 20), cv2.FONT_HERSHEY_SIMPLEX, 0.6, (0, 0, 255), 2)
        tiles.append(img)
    while len(tiles) % 3:
        tiles.append(np.zeros_like(tiles[0]))
    (HERE / "figs").mkdir(exist_ok=True)
    cv2.imwrite(str(HERE / "figs" / f"fit_445_{name}.jpg"), np.vstack([np.hstack(tiles[i:i + 3]) for i in range(0, len(tiles), 3)]))


def main():
    ap = argparse.ArgumentParser()
    ap.add_argument("--cam", action="store_true")
    ap.add_argument("--wire", action="store_true")
    ap.add_argument("--n-rand", type=int, default=1500)
    ap.add_argument("--rounds", type=int, default=4)
    a = ap.parse_args()
    p = HERE / "fit_445.json"
    res = json.loads(p.read_text()) if p.exists() else {}
    res["made_by"] = "so101/sim/look_445/fit_445.py (依頼 445)"
    res["book"] = "check_363/tune01 (割り振り 1. 比べる 3 本と別). コマ 0〜250 の 10 コマおき"
    if a.cam:
        c, info = fit_cam(a.n_rand, a.rounds)
        res["cam"], res["cam_info"] = c, info
    if a.wire:
        w, info = fit_wire(a.n_rand, a.rounds)
        res["wire"], res["wire_info"] = w, info
    p.write_text(json.dumps(res, ensure_ascii=False, indent=1))
    figure(res.get("cam"), res.get("wire"), "both")


if __name__ == "__main__":
    main()
