"""依頼 330 の 1: place1 の実機のお手本の最初のコマ (机側) から, 赤いブロックと白い箱の机の上の位置と大きさを出す.
あわせて, お手本を録ったあとに机側カメラが動いていないかを確かめる. サーボ・カメラは使わない (記録の動画を読むだけ).

- 測ったカメラの値 (KIOXIA so101_calibration/2026-11-27/cameras の camera_desk.json・desk_pose.json・arm_frame_v2.json) を使う.
- 依頼文の決め方 (光線と面の交わり):
    ブロック = 赤い所の重心の画素の光線と机の面 (z=0) の交わり.
    箱 = 箱の外の輪郭の画素の光線と, 上の縁の高さ 45mm の面の交わり (外の輪郭の四隅と重心).
- 形を当てた値 (シーンに使う): 立方体 (中心 x・y・向き・一辺) / 高さ 45mm の箱 (中心 x・y・向き・外の縦横) の 8 隅を写した
  凸包が, 画像の赤い所 / 箱の所と最もよく重なる (IoU) 値. 光線の交わりは高さの分 (ブロックの上の面・箱の側面) ずれるため.
- カメラ・腕が動いたか: 机には縁などの目印が写っていないため, 台に固定された腕と, 動かさない決まりの白い箱で見る.
    腕: 記録のコマの届いた角度 (observation.state) で腕をシムに描き (今日のカメラの値), 台座の置き方 (回る軸まわりの向き・前後・左右)
        を変えて, シムの腕の輪郭が実機の縁に最も合う所を探す (fit_base). お手本 (11-23)・理想の道を実機で流した記録 (11-26)・
        今日の写真 (check_329 の 5 姿勢. 0 に近くなれば測り方が正しい) の 3 つ.
    箱: 同じ測り方で 11-26 の記録と今日の写真 (check_326/pose1/real.png) の箱の位置も出す.

使い方 (conda の lerobot 環境で):
    python so101/sim/measure_scene_330.py   # → so101/check_330/scene_measure_330.json と絵 (scene_measure_real_frame0.png・base_fit_*.png)
"""

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

OUT = HERE.parent / "check_330"
REAL_DS = "so101_redblock_box_teleop_v1"  # KIOXIA datasets/so101_redblock_box_teleop_even_v1 の元 (Mac の写し. 640×480)
REAL_EP = 9  # place1・成功・549 コマ (place1 の 8 本の長さの中央値 551.5 に近く, 依頼 296 で除いたキー姿勢がない)
IDEAL_DS = "so101_redblock_box_ideal_x13_v1"
IDEAL_EP = 0
TODAY_PNG = HERE.parent / "check_326" / "pose1" / "real.png"
CHECK329 = HERE.parent / "check_329"
BOX_H_MM = 45.0  # so101_kinematics.md「白い箱の高さは 45mm」


def nelder_mead(f, x0, step, iters=400, tol=1e-6):
    x0 = np.asarray(x0, float)
    n = len(x0)
    pts = [x0] + [x0 + np.eye(n)[i] * step[i] for i in range(n)]
    vals = [f(p) for p in pts]
    for _ in range(iters):
        o = np.argsort(vals)
        pts, vals = [pts[i] for i in o], [vals[i] for i in o]
        if abs(vals[-1] - vals[0]) < tol:
            break
        c = np.mean(pts[:-1], 0)
        xr = c + (c - pts[-1])
        fr = f(xr)
        if fr < vals[0]:
            xe = c + 2 * (c - pts[-1])
            fe = f(xe)
            pts[-1], vals[-1] = (xe, fe) if fe < fr else (xr, fr)
        elif fr < vals[-2]:
            pts[-1], vals[-1] = xr, fr
        else:
            xc = c + 0.5 * (pts[-1] - c)
            fc = f(xc)
            if fc < vals[-1]:
                pts[-1], vals[-1] = xc, fc
            else:
                pts = [pts[0]] + [pts[0] + 0.5 * (p - pts[0]) for p in pts[1:]]
                vals = [vals[0]] + [f(p) for p in pts[1:]]
    i = int(np.argmin(vals))
    return pts[i], vals[i]


def hull_mask(px, shape):
    m = np.zeros(shape, np.uint8)
    cv2.fillConvexPoly(m, cv2.convexHull(np.round(px).astype(np.int32)), 1)
    return m > 0


def iou(a, b):
    return float((a & b).sum()) / max(1, float((a | b).sum()))


def red_mask(img):
    hsv = cv2.cvtColor(img, cv2.COLOR_BGR2HSV)
    m = (((hsv[..., 0] < 10) | (hsv[..., 0] > 165)) & (hsv[..., 1] > 70) & (hsv[..., 2] > 50)).astype(np.uint8)
    n, lab, st, _ = cv2.connectedComponentsWithStats(m)
    if n < 2:
        return None
    k = 1 + int(np.argmax(st[1:, cv2.CC_STAT_AREA]))
    return lab == k


def box_mask(img, seed_xy):
    """白い箱: 机 (明るい) より暗い所 (箱の中の影・壁・縁の線) を seed のまわりで集め, 穴を埋めた外の輪郭."""
    g = cv2.GaussianBlur(cv2.cvtColor(img, cv2.COLOR_BGR2GRAY), (3, 3), 0)
    desk = np.percentile(g, 75)
    m = (g < desk - 25).astype(np.uint8)
    win = np.zeros_like(m)  # seed のまわり ±85px だけを見る (今日の写真ではボードの黒いマスが箱に接するため)
    x0, y0 = int(seed_xy[0]), int(seed_xy[1])
    win[max(0, y0 - 85):y0 + 85, max(0, x0 - 85):x0 + 85] = 1
    m = cv2.morphologyEx(m * win, cv2.MORPH_CLOSE, np.ones((5, 5), np.uint8))
    n, lab, st, _ = cv2.connectedComponentsWithStats(m)
    # seed のまわり (±80px) に重心がある, いちばん大きいかたまり
    near = [i for i in range(1, n) if abs(st[i, 0] + st[i, 2] / 2 - seed_xy[0]) < 80
            and abs(st[i, 1] + st[i, 3] / 2 - seed_xy[1]) < 80]
    if not near:
        raise RuntimeError("箱の所が見つからない")
    k = max(near, key=lambda i: st[i, cv2.CC_STAT_AREA])
    comp = (lab == k).astype(np.uint8)
    cnts, _ = cv2.findContours(comp, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE)
    hull = cv2.convexHull(max(cnts, key=cv2.contourArea))
    out = np.zeros_like(comp)
    cv2.fillConvexPoly(out, hull, 1)
    return out > 0, float(desk)


def fit_block(img, cam):
    rm = red_mask(img)
    ys, xs = np.nonzero(rm)
    c_px = np.array([xs.mean(), ys.mean()])
    lit = S.ray_plane_z(c_px, cam, 0.0)[0]  # 依頼文の決め方: 机の面との交わり
    rect = cv2.minAreaRect(np.c_[xs, ys].astype(np.float32))

    def cost(p):
        x, y, yaw, s = p
        if not 10 < s < 60:
            return 1.0
        return 1 - iou(hull_mask(S.project_arm(S.box_corners([x, y], yaw, [s, s], 0, s), cam), rm.shape), rm)

    best = None
    for yaw0 in np.arange(0, 90, 15):
        for s0 in (20, 25, 30, 35):
            p, val = nelder_mead(cost, [lit[0], lit[1], yaw0, s0], [3, 3, 8, 3], iters=300)
            if best is None or val < best[1]:
                best = (p, val)
    p, val = best
    x, y, yaw, s = p
    yaw = (yaw + 45) % 90 - 45
    return {"literal_desk_plane_mm": [round(float(lit[0]), 1), round(float(lit[1]), 1)],
            "red_centroid_px": [round(float(c_px[0]), 1), round(float(c_px[1]), 1)],
            "red_px_count": int(rm.sum()), "red_min_area_rect_px": [list(map(float, rect[0])), list(map(float, rect[1])), float(rect[2])],
            "fit": {"xy_mm": [round(float(x), 1), round(float(y), 1)], "yaw_deg": round(float(yaw), 1),
                    "size_mm": round(float(s), 1), "iou": round(1 - float(val), 4)}}, rm


def fit_box(img, cam, seed_xy):
    bm, desk = box_mask(img, seed_xy)
    cnts, _ = cv2.findContours(bm.astype(np.uint8), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE)
    approx = cv2.approxPolyDP(cnts[0], 4, True).reshape(-1, 2).astype(float)
    ys, xs = np.nonzero(bm)
    c_px = np.array([xs.mean(), ys.mean()])
    lit_c = S.ray_plane_z(c_px, cam, BOX_H_MM)[0]
    lit_corners = S.ray_plane_z(approx, cam, BOX_H_MM)

    def cost(p):
        x, y, yaw, w, d = p
        if not (40 < w < 200 and 40 < d < 200):
            return 1.0
        return 1 - iou(hull_mask(S.project_arm(S.box_corners([x, y], yaw, [w, d], 0, BOX_H_MM), cam), bm.shape), bm)

    best = None
    for yaw0 in (-10, 0, 10):
        p, val = nelder_mead(cost, [lit_c[0], lit_c[1], yaw0, 90, 90], [5, 5, 4, 5, 5], iters=500)
        if best is None or val < best[1]:
            best = (p, val)
    p, val = best
    x, y, yaw, w, d = p
    return {"literal_rim_plane_45mm": {"center_mm": [round(float(lit_c[0]), 1), round(float(lit_c[1]), 1)],
                                        "outline_corners_px": approx.round(1).tolist(),
                                        "outline_corners_mm": lit_corners[:, :2].round(1).tolist()},
            "desk_gray": desk, "box_px_count": int(bm.sum()),
            "fit": {"xy_mm": [round(float(x), 1), round(float(y), 1)], "yaw_deg": round(float(yaw), 1),
                    "outer_mm": [round(float(w), 1), round(float(d), 1)], "height_mm": BOX_H_MM,
                    "iou": round(1 - float(val), 4)}}, bm


def fit_base(items, cams, maps, tag):
    """腕の台座の置き方 (回る軸まわりの向き yaw・前後左右 tx・ty mm) を, 記録のコマの腕の輪郭に合わせて出す.
    items = [(届いた角度 6 つ, 机側の絵), ...]. 測りは シムの腕の輪郭の点から実機の縁 (Canny) までの距離 (px, 15 で頭打ち) の平均.
    手首カメラの台座とカメラ (モデルの形が実機と違う) と台座・肩 (絵の下の縁で切れる) は使わない."""
    import mujoco
    scene = {"block": {"xy": [1000, 1000], "yaw": 0, "size": 20},
             "box": {"xy": [1000, -1000], "yaw": 0, "size_xy": [80, 80], "height": 45, "wall": 3}}
    spec = S.build_spec(scene, cams, {"pos_mm": [0, 0, 0], "rotvec": [0, 0, 0]}, {"desk": maps["desk"], "wrist": maps["desk"]})
    m = spec.compile()
    d = mujoco.MjData(m)
    cr = S.Cams(m, {"desk": maps["desk"]})
    use = [m.body(i).name for i in range(1, m.nbody)
           if m.body(i).name not in ("block", "box", "wrist_camera_mount", "wrist_camera", "base", "shoulder")]
    dts = []
    for st, img in items:
        e = cv2.Canny(cv2.GaussianBlur(cv2.cvtColor(img, cv2.COLOR_BGR2GRAY), (5, 5), 0), 20, 60)
        dts.append(cv2.distanceTransform((e == 0).astype(np.uint8), cv2.DIST_L2, 3))

    def cost(p):
        S.set_base_offset(m, *p)
        tot = []
        for (st, _), dt in zip(items, dts):
            S.set_arm_qpos(m, d, dict(zip(S.MOTORS, st)))
            mujoco.mj_forward(m, d)
            arm = cr.seg_bodies(d, "desk", use)
            cn, _ = cv2.findContours(arm.astype(np.uint8), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE)
            if not cn:
                tot.append(15.0)
                continue
            pts = np.vstack([c.reshape(-1, 2) for c in cn])
            pts = pts[(pts[:, 1] < S.H - 3) & (pts[:, 1] > 2) & (pts[:, 0] > 2) & (pts[:, 0] < S.W - 3)]
            tot.append(float(np.mean(np.minimum(dt[pts[:, 1], pts[:, 0]], 15))))
        return float(np.mean(tot))

    grid = [(cost([y, 0, 0]), float(y)) for y in np.arange(-16, 16.1, 2)]
    y0 = min(grid)[1]
    p, val = nelder_mead(cost, [y0, 0, 0], [1.5, 8, 8], iters=150, tol=1e-3)
    p1, val1 = nelder_mead(lambda q: cost([q[0], 0, 0]), [y0], [1.5], iters=60, tol=1e-3)
    zero = cost([0, 0, 0])
    # 絵: 上 = 今日の置き方のまま, 下 = 当てはめた置き方
    rows = []
    for base in ([0, 0, 0], list(p)):
        S.set_base_offset(m, *base)
        row = []
        for st, img in items[:4]:
            S.set_arm_qpos(m, d, dict(zip(S.MOTORS, st)))
            mujoco.mj_forward(m, d)
            arm = cr.seg_bodies(d, "desk", [m.body(i).name for i in range(1, m.nbody) if m.body(i).name not in ("block", "box")])
            cn, _ = cv2.findContours(arm.astype(np.uint8), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE)
            vis = img.copy()
            cv2.drawContours(vis, cn, -1, (255, 0, 0), 1)
            row.append(cv2.resize(vis, (320, 240)))
        rows.append(np.hstack(row))
    cv2.imwrite(str(OUT / f"base_fit_{tag}.png"), np.vstack(rows))
    cr.close()
    return {"frames_used": len(items), "cost_px_today_placement": round(zero, 3),
            "yaw_only": {"yaw_deg": round(float(p1[0]), 2), "cost_px": round(float(val1), 3)},
            "yaw_and_shift": {"yaw_deg": round(float(p[0]), 2), "tx_mm": round(float(p[1]), 1), "ty_mm": round(float(p[2]), 1),
                              "cost_px": round(float(val), 3)},
            "yaw_grid": [[y, round(c, 2)] for c, y in grid]}


H_EDGE = S.H - 3


def draw(img, cam, block, box, rm, bm, path):
    vis = img.copy()
    for mask, col in ((rm, (0, 255, 255)), (bm, (255, 255, 0))):
        cnts, _ = cv2.findContours(mask.astype(np.uint8), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE)
        cv2.drawContours(vis, cnts, -1, col, 1)
    f = block["fit"]
    bc = S.box_corners(f["xy_mm"], f["yaw_deg"], [f["size_mm"]] * 2, 0, f["size_mm"])
    f2 = box["fit"]
    xc = S.box_corners(f2["xy_mm"], f2["yaw_deg"], f2["outer_mm"], 0, BOX_H_MM)
    for c8 in (bc, xc):
        p = S.project_arm(c8, cam)
        for a, b in ((0, 1), (1, 2), (2, 3), (3, 0), (4, 5), (5, 6), (6, 7), (7, 4), (0, 4), (1, 5), (2, 6), (3, 7)):
            cv2.line(vis, tuple(np.round(p[a]).astype(int)), tuple(np.round(p[b]).astype(int)), (0, 0, 255), 1)
    cv2.imwrite(str(path), vis)


def main():
    OUT.mkdir(parents=True, exist_ok=True)
    cams = S.load_cameras()
    cam = cams["desk"]
    maps = {"desk": S.DistortMap(cam["K"], cam["D"])}
    _, st, _ = S.read_episode(REAL_DS, REAL_EP)
    real0 = S.read_frames(REAL_DS, REAL_EP, "desk", [0])[0]
    cv2.imwrite(str(OUT / "real_desk_frame0.png"), real0)
    _, st_i, _ = S.read_episode(IDEAL_DS, IDEAL_EP)
    ideal0 = S.read_frames(IDEAL_DS, IDEAL_EP, "desk", [0])[0]
    today = cv2.imread(str(TODAY_PNG))

    res = {"time": datetime.now().isoformat(timespec="seconds"), "made_by": "so101/sim/measure_scene_330.py (依頼 330)",
           "real_demo": {"dataset": f"~/so101_datasets/{REAL_DS} (KIOXIA datasets/so101_redblock_box_teleop_even_v1 の "
                                    f"raw_episodes/so101_redblock_box_teleop_v1_ep{REAL_EP:03d} の元. 640×480)",
                         "episode": REAL_EP, "place": 1, "frames": int(len(st))},
           "camera_values": str(S.KIOXIA_CAM), "units": "アームの座標 mm (原点 = 台座の回る軸の机の面, +x 前, +y 左, +z 上)"}
    blk, rm = fit_block(real0, cam)
    box, bm = fit_box(real0, cam, seed_xy=(520, 285))
    res["block"], res["box"] = blk, box
    draw(real0, cam, blk, box, rm, bm, OUT / "scene_measure_real_frame0.png")
    # 同じ測り方で 11-26 (理想の道を実機で流した記録) と今日の写真の箱・ブロック
    res["other_days"] = {}
    for tag, img, seed in (("ideal_x13_ep0_20261126", ideal0, (545, 300)), ("today_check326_pose1_20261127", today, (545, 300))):
        o = {}
        try:
            o["box"], bm2 = fit_box(img, cam, seed)
        except RuntimeError as e:
            o["box"] = str(e)
        if red_mask(img) is not None and tag.startswith("ideal"):
            o["block"], _ = fit_block(img, cam)
        res["other_days"][tag] = o
    # カメラ・腕が動いたか: 腕の台座の置き方を記録のコマに合わせる (今日の写真で 0 に近くなることも確かめる)
    def items_of(ds, ep, idx):
        _, sts, _ = S.read_episode(ds, ep)
        fr = S.read_frames(ds, ep, "desk", idx)
        return [(sts[i], fr[i]) for i in idx]
    today_items = []
    for p in ("c0", "L", "cL", "R", "cR"):
        jd = json.loads((CHECK329 / p / "joints.json").read_text())["deg"]
        today_items.append(([jd[k] for k in S.MOTORS], cv2.imread(str(CHECK329 / p / "real.png"))))
    res["base_fit"] = {
        "how": "台座の回る軸まわりの向き (yaw, + = 上から見て左回り) と前後 (tx)・左右 (ty) を, 記録のコマの腕の輪郭に合わせた. "
               "cost_px = シムの腕の輪郭の点から実機の縁までの距離の平均 (px, 15 で頭打ち). 手首カメラの台座・台座・肩は使わない",
        "teleop_ep9_20261123": fit_base(items_of(REAL_DS, REAL_EP, [200, 296, 330, 400, 450]), cams, maps, "teleop_ep9"),
        "ideal_x13_ep0_20261126": fit_base(items_of(IDEAL_DS, IDEAL_EP, [90, 140, 175, 220, 270]), cams, maps, "ideal_x13_ep0"),
        "today_check329_20261127": fit_base(today_items, cams, maps, "today_check329"),
    }
    res["notes"] = {
        "block_size_docs": "SO-101 の資料にブロックの大きさの記載はない (mechArm の頃の記事に 24mm 角・約 3cm 角の両方がある). 画像の当てはめを正にした",
        "box_size_docs": "so101_kinematics.md に高さ 45mm だけ. 縦横は画像の当てはめ (mechArm の頃の記事の 80mm・90mm 角は参考)",
    }
    (OUT / "scene_measure_330.json").write_text(json.dumps(res, ensure_ascii=False, indent=2))
    print(json.dumps(res, ensure_ascii=False, indent=1))


if __name__ == "__main__":
    main()
