"""依頼 366: ケーブルの留め位置を 実機の机側の絵に写して 目で合わせるための 重ね絵 (当てはめの本 check_363/tune01).
geom の 座標の軸 (x 赤・y 緑・z 青. 20mm)・名前と, cable_366 の線 (黄) を 実機の絵に重ねる.

使い方 (conda の lerobot 環境で):
    python so101/blender/fit_cable_366.py --frames 0,60,140,180,210,240 [--axes g24,g16] [--ep check_363/tune01] [--out _tmp/cable.jpg]
"""

import argparse
import json
import sys
from pathlib import Path

import cv2
import numpy as np

HERE = Path(__file__).resolve().parent
SO101 = HERE.parent
sys.path.insert(0, str(HERE))
sys.path.insert(0, str(SO101 / "sim"))
sys.path.insert(0, str(SO101 / "check_326"))
import sim_330 as S  # noqa: E402
import check_326_sim_view as V  # noqa: E402
import cable_366 as CB  # noqa: E402

OUT = SO101 / "check_366"
_CAM = None


def cam():
    global _CAM
    if _CAM is None:
        _CAM = S.load_cameras()["desk"]
    return _CAM


def world_to_arm_mm(p):
    return np.asarray(p, float).reshape(-1, 3) * 1000 - V.AXIS_IN_BASE_MM - np.array([0, 0, V.BASE_BOTTOM_IN_BASE_MM])


def project(p_world):
    """world (m) → 机側の実機の絵の画素 (640×480. 歪みあり)."""
    return S.project_arm(world_to_arm_mm(p_world), cam())


def overlay(img, geoms, axes=(), lines=True, color=(0, 255, 255), thick=1):
    im = img.copy()
    for g in axes:
        o = CB.world_pt(geoms, g, (0, 0, 0))
        px = project(np.vstack([o] + [CB.world_pt(geoms, g, e) for e in ((20, 0, 0), (0, 20, 0), (0, 0, 20))]))
        for j, c in enumerate(((0, 0, 255), (0, 200, 0), (255, 0, 0))):
            cv2.line(im, tuple(px[0].astype(int)), tuple(px[j + 1].astype(int)), c, 1, cv2.LINE_AA)
        cv2.putText(im, g, tuple(px[0].astype(int) + 3), cv2.FONT_HERSHEY_SIMPLEX, 0.4, (255, 0, 255), 1, cv2.LINE_AA)
    if lines:
        for nm, P, r, kind in CB.all_lines(geoms):
            px = project(P).astype(np.int32)
            cv2.polylines(im, [px], False, color if kind == "cam" else (255, 0, 255), thick, cv2.LINE_AA)
        for g, p in CB.CAM_CABLE:
            q = project(CB.world_pt(geoms, g, p))[0].astype(int)
            cv2.circle(im, tuple(q), 3, (0, 0, 255), 1)
    return im


# ---- 当てはめ (大まかに. 当てはめの本の机側の絵の ケーブルの画素に 線を寄せる) ----------------------------------

def real_cable_mask(img, lab):
    """実機の机側の絵の ケーブルらしい画素: 細い暗い物 (L の閉じ − L > 12・L < 55) で, 腕から 80px 以内, 赤 (a* > 12) から 3px 以上離れ,
    サーボ・手首カメラ (MuJoCo のラベル 3) と 箱 (5・6) から 3px 以上離れ, 25px 以上つながった所."""
    L = cv2.cvtColor(img.astype(np.float32) / 255, cv2.COLOR_BGR2LAB)[..., 0]
    bh = cv2.morphologyEx(L, cv2.MORPH_CLOSE, cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (13, 13))) - L
    arm = np.isin(lab, (2, 3, 7)).astype(np.uint8)
    near = cv2.dilate(arm, cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (161, 161))) > 0
    excl = cv2.dilate(np.isin(lab, (3, 5, 6)).astype(np.uint8), np.ones((7, 7), np.uint8)) > 0
    A = cv2.cvtColor(img.astype(np.float32) / 255, cv2.COLOR_BGR2LAB)[..., 1]
    red = cv2.dilate((A > 12).astype(np.uint8), np.ones((7, 7), np.uint8)) > 0  # サーボの赤い線 (とブロック) のまわりは除く
    m = ((bh > 12) & (L < 55) & near & ~excl & ~red).astype(np.uint8)
    n, cc, st, _ = cv2.connectedComponentsWithStats(m, 8)
    keep = np.zeros(n, bool)
    keep[1:] = st[1:, cv2.CC_STAT_AREA] >= 25
    return keep[cc]


def real_wire_mask(img, lab):
    """実機の机側の絵の サーボの赤い線らしい画素: 赤み (a* > 12) で 腕から 30px 以内, ブロック (赤の大きな塊 > 250px) を除く."""
    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, (61, 61))) > 0
    m = ((A > 12) & 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] <= 250)
    return keep[cc]


def line_px(P):
    px = project(P)
    ok = (px[:, 0] > -50) & (px[:, 0] < 690) & (px[:, 1] > -50) & (px[:, 1] < 530)
    return px[ok]


def dense(px, step=2.0):
    if len(px) < 2:
        return px
    seg = np.diff(px, axis=0)
    ln = np.hypot(seg[:, 0], seg[:, 1])
    out = [px[0]]
    for i in range(len(seg)):
        n = max(1, int(ln[i] / step))
        out += [px[i] + seg[i] * (j + 1) / n for j in range(n)]
    return np.array(out)


class Fitter:
    CAP = 15.0

    def __init__(self, src, frames, mask=None):
        mask = mask or real_cable_mask
        P = json.loads((src / "poses.json").read_text())
        self.fr = [f for f in P["frames"] if f["frame"] in frames]
        self.D, self.R = [], []
        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), self.CAP))

    def cost(self, verbose=False):
        tot, per = 0.0, []
        for f, D, R in zip(self.fr, self.D, self.R):
            px = dense(line_px(CB.cam_cable(f["geoms"])))
            inside = (px[:, 0] >= 0) & (px[:, 0] < 639) & (px[:, 1] >= 0) & (px[:, 1] < 479)
            q = px[inside].astype(int)
            t1 = float(D[q[:, 1], q[:, 0]].mean()) if len(q) else self.CAP
            sim = np.zeros(R.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), self.CAP)
            t2 = float(Ds[R].mean()) if R.sum() > 30 else 0.0
            per.append((f["frame"], t1, t2))
            tot += t1 + t2
        if verbose:
            return tot / len(self.fr), per
        return tot / len(self.fr)


def get_params():
    x = []
    for g, p in CB.CAM_CABLE:
        x += list(p)
    x += [r if r is not None else 0.0 for r in CB.CAM_REST_MM]
    o = CB.CAM_OUT[-1][1]
    x += list(o) + [CB.SAG_GRAVITY]
    return np.array(x, float)


def set_params(x):
    n = len(CB.CAM_CABLE)
    CB.CAM_CABLE = [(g, tuple(x[3 * i:3 * i + 3])) for i, (g, _) in enumerate(CB.CAM_CABLE)]
    r = x[3 * n:3 * n + n - 1]
    CB.CAM_REST_MM = [None if v <= 0 else float(v) for v in r]
    o = x[4 * n - 1:4 * n + 2]
    CB.CAM_OUT = CB.CAM_OUT[:-1] + [(CB.CAM_OUT[-1][0], tuple(o))]
    CB.SAG_GRAVITY = float(np.clip(x[4 * n + 2], 0, 1))


def mesh_box(g):
    """geom の形の外接の箱 (geom の座標 mm)."""
    geoms = json.loads((SO101 / "check_361" / "scene" / "geoms.json").read_text())
    r = next(r for r in geoms if r["name"] == g)
    v = np.load(SO101 / "check_361" / "scene" / "meshes.npz")[r["mesh"] + "_v"] * 1000
    return v.min(0), v.max(0)


def fit(src, frames, rounds=4, n_rand=1500, seed=0):
    F = Fitter(src, frames)
    x = get_params()
    n = len(CB.CAM_CABLE)
    # 動かす幅 (mm): 差し口 ±1mm・輪の留め具 ±2mm (見て・格子で決めた), 他の留め位置は 形の外接の箱 ±10mm, rest は 0 (張る)〜400mm
    x0 = x.copy()
    lo = x0.copy()
    hi = x0.copy()
    lo[:3], hi[:3] = x0[:3] - 1, x0[:3] + 1
    lo[3:6], hi[3:6] = x0[3:6] - 2, x0[3:6] + 2  # 輪の留め具 (grid_cable_366 で決めた)
    for i, (g, _) in enumerate(CB.CAM_CABLE[2:], 2):
        a, b = mesh_box(g)
        lo[3 * i:3 * i + 3], hi[3 * i:3 * i + 3] = a - 10, b + 10
    lo[3 * n:4 * n - 1], hi[3 * n:4 * n - 1] = 0, 400
    lo[4 * n - 1:4 * n + 2], hi[4 * n - 1:4 * n + 2] = -1, 1
    lo[4 * n + 2], hi[4 * n + 2] = 0, 1
    step = np.where(np.arange(len(x)) < 3 * n, 4.0, 0.0)
    step[3 * n:4 * n - 1] = 40.0
    step[4 * n - 1:] = 0.3
    set_params(x)
    best = F.cost()
    print("start", round(best, 3), flush=True)
    # 無作為に試す (局所の解に落ちないように)
    rng = np.random.default_rng(seed)
    for j in range(n_rand):
        y = lo + rng.random(len(x)) * (hi - lo)
        y[:6] = x0[:6]
        y[3 * n:4 * n - 1] = np.where(rng.random(n - 1) < 0.3, 0.0, y[3 * n:4 * n - 1])
        set_params(y)
        c = F.cost()
        if c < best:
            best, x = c, y
            print("rand", j, round(best, 3), flush=True)
    set_params(x)
    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
                    set_params(y)
                    c = F.cost()
                    if c < best - 1e-4:
                        best, x, improved = c, y, True
                        break
            set_params(x)
        print("round", r, "step", step[:1], round(best, 3), flush=True)
        step = step / 2
    set_params(x)
    return F, best


# サーボの赤い線: grid_cable_366.py --wire の 部品ごとの一番の点 (赤い線の上に写る点) を 隣の部品どうしで結ぶ.
# 手首 (g20 → g22) だけ: 実機の赤い輪と重なった. 爪側 (g24 → g26)・肘 (g14 → g18) は 結ぶと 73mm・229mm の大きな輪になり 実機と合わないので足さない.
# 肩・台座のまわりは 当たりが弱い (11〜15px) ので足さない
WIRE_PAIRS = [("wire_wrist", "g20", "g22")]


def cam_dir(P, g):
    """当てはめの本の コマの平均の 机側カメラへの向き (部品 g の座標. 単位ベクトル)."""
    acc = []
    for f in P["frames"]:
        M = np.asarray(f["geoms"][g]).reshape(4, 4)
        C = np.asarray(f["cams"]["desk"]).reshape(4, 4)[:3, 3]
        v = M[:3, :3].T @ (C - M[:3, 3])
        acc.append(v / np.linalg.norm(v))
    m = np.mean(acc, 0)
    return m / np.linalg.norm(m)


def make_wires(src, rest_k=1.15, rest_add_mm=10.0):
    best = json.loads((OUT / "anchor_grid_wire_366.json").read_text())
    P = json.loads((src / "poses.json").read_text())
    out = []
    for nm, ga, gb in WIRE_PAIRS:
        pa, pb = best[ga][0][0], best[gb][0][0]
        ch = [np.linalg.norm(CB.world_pt(f["geoms"], ga, pa) - CB.world_pt(f["geoms"], gb, pb)) * 1000 for f in P["frames"]]
        d = np.asarray(pa, float)
        out.append({"name": nm, "a": [ga, pa], "b": [gb, pb], "rest_mm": round(float(max(ch) * rest_k + rest_add_mm), 1),
                    "out": [ga, [round(float(v), 3) for v in d / np.linalg.norm(d)]],
                    "grid_px": [best[ga][0][1], best[gb][0][1]], "chord_mm": [round(float(min(ch)), 1), round(float(max(ch)), 1)]})
    # 格子の点は 机側カメラの見る向きに沿った奥行きが決まらない (その向きに動かしても 写る所は同じ). 実機の輪は カメラの側に見えるので
    # 端の点を 当てはめの本の コマの平均の カメラの向き (部品の座標) に沿って 部品の外 (外接の箱 + 3mm) まで出し, ふくらむ向きも その向きにする
    for w in out:
        for key in ("a", "b"):
            g, p0 = w[key]
            u = cam_dir(P, g)
            lo, hi = mesh_box(g)
            p = np.asarray(p0, float)
            corners = np.array([[x, y, z] for x in (lo[0], hi[0]) for y in (lo[1], hi[1]) for z in (lo[2], hi[2])])
            p = p + ((corners @ u).max() + 2.0 - p @ u) * u  # カメラの側の 外接の箱の一番外 + 2mm まで (カメラの向きに沿って)
            w[key] = [g, [round(float(v), 2) for v in p]]
        w["out"] = [w["a"][0], [round(float(v), 3) for v in cam_dir(P, w["a"][0])]]
        w["rest_mm"] = round(float(max(np.linalg.norm(CB.world_pt(f["geoms"], w["a"][0], w["a"][1]) - CB.world_pt(f["geoms"], w["b"][0], w["b"][1])) * 1000
                                       for f in P["frames"]) * rest_k + rest_add_mm), 1)
    f = json.loads(CB.FIT_JSON.read_text())
    f["servo_wires"] = out
    f["servo_wires_how"] = ("端 = grid_cable_366.py --wire の 部品ごとの一番の点. rest = 当てはめの本の中の 2 点の間の一番長い直線 × 1.15 + 10mm. "
                            "端の点は カメラの見る向きに沿って 部品の外へ出した (cam_dir). ふくらむ向き = カメラの側 (と重さ)")
    CB.FIT_JSON.write_text(json.dumps(f, ensure_ascii=False, indent=1))
    CB.load_fit()
    print(json.dumps(out, ensure_ascii=False))


def save_fit(F, best, frames):
    tot, per = F.cost(verbose=True)
    res = {"made_by": "so101/blender/fit_cable_366.py --fit (依頼 366)", "book": "check_363/tune01 (割り振り 1. 比べる 3 本と別)",
           "frames": sorted(frames), "cost_px": round(tot, 3),
           "how": "実機の机側の絵の ケーブルらしい画素 (real_cable_mask) と 写した線の 距離 (上限 15px) を 両向きに足した値を 座標を 1 つずつ動かして下げる (大まかに)",
           "cam_cable": [[g, [round(float(v), 2) for v in p]] for g, p in CB.CAM_CABLE],
           "cam_rest_mm": [None if r is None else round(r, 1) for r in CB.CAM_REST_MM],
           "cam_out": [None if o is None else [o[0], [round(float(v), 3) for v in o[1]]] for o in CB.CAM_OUT],
           "sag_gravity": round(CB.SAG_GRAVITY, 3),
           "servo_wires": json.loads(CB.FIT_JSON.read_text()).get("servo_wires", []) if CB.FIT_JSON.exists() else [],
           "per_frame": [{"frame": k, "sim_to_real_px": round(a, 2), "real_to_sim_px": round(b, 2)} for k, a, b in per]}
    CB.FIT_JSON.parent.mkdir(parents=True, exist_ok=True)
    CB.FIT_JSON.write_text(json.dumps(res, ensure_ascii=False, indent=1))
    print("→", CB.FIT_JSON, res["cost_px"])


def main():
    ap = argparse.ArgumentParser()
    ap.add_argument("--ep", default="check_363/tune01")
    ap.add_argument("--frames", default="0,60,140,180,210,240")
    ap.add_argument("--axes", default="")
    ap.add_argument("--zoom", type=float, default=1.0)
    ap.add_argument("--crop", action="store_true")
    ap.add_argument("--fit", action="store_true")
    ap.add_argument("--fit-frames", default=",".join(str(k) for k in range(0, 251, 10)))
    ap.add_argument("--rounds", type=int, default=4)
    ap.add_argument("--n-rand", type=int, default=1500)
    ap.add_argument("--mask", action="store_true", help="実機のケーブルの画素を緑で重ねる")
    ap.add_argument("--wires", action="store_true", help="サーボの赤い線を cable_fit_366.json に足す")
    ap.add_argument("--out", default="_tmp/cable.jpg")
    a = ap.parse_args()
    src = SO101 / a.ep
    if a.fit:
        frames = {int(x) for x in a.fit_frames.split(",")}
        F, best = fit(src, frames, a.rounds, a.n_rand)
        save_fit(F, best, frames)
    if a.wires:
        make_wires(src)
    P = json.loads((src / "poses.json").read_text())
    want = [int(x) for x in a.frames.split(",")]
    fr = {f["frame"]: f for f in P["frames"]}
    tiles = []
    for k in want:
        img = cv2.imread(str(src / "real" / f"{k:03d}_desk.png"))
        if a.mask:
            lb = cv2.imread(str(src / "lab" / f"{k:03d}_desk.png"), 0)
            img[real_cable_mask(img, lb)] = (0, 160, 0)
            img[real_wire_mask(img, lb)] = (160, 0, 0)
        geoms = fr[k]["geoms"]
        im = overlay(img, geoms, [g for g in a.axes.split(",") if g])
        if a.crop:  # 腕のまわりを切って 高さ 480 に
            o = project(np.vstack([CB.world_pt(geoms, g, (0, 0, 0)) for g in ("g32", "g24", "g16", "g14", "g10")]))
            x0, y0 = np.clip(o.min(0) - 60, 0, None).astype(int)
            x1, y1 = np.minimum(o.max(0) + 60, [640, 480]).astype(int)
            im = im[y0:y1, x0:x1]
            s = 480 / im.shape[0]
            im = cv2.resize(im, (min(int(im.shape[1] * s), 900), 480), interpolation=cv2.INTER_CUBIC)
        cv2.putText(im, f"f{k}", (5, 20), cv2.FONT_HERSHEY_SIMPLEX, 0.6, (0, 0, 255), 2)
        tiles.append(im)
    W = max(t.shape[1] for t in tiles)
    tiles = [cv2.copyMakeBorder(t, 0, 480 - t.shape[0], 0, W - t.shape[1], cv2.BORDER_CONSTANT) for t in tiles]
    while len(tiles) % 3:
        tiles.append(np.zeros_like(tiles[0]))
    big = np.vstack([np.hstack(tiles[i:i + 3]) for i in range(0, len(tiles), 3)])
    if a.zoom != 1.0:
        big = cv2.resize(big, None, fx=a.zoom, fy=a.zoom, interpolation=cv2.INTER_AREA)
    (OUT / Path(a.out).parent).mkdir(parents=True, exist_ok=True)
    cv2.imwrite(str(OUT / a.out), big)
    print(OUT / a.out)


if __name__ == "__main__":
    main()
