"""依頼 334: SO-101 の実機のテレオペのお手本 50 本 (teleop_even_v1) の関節の動きを, そのままシムで再生して机側・手首の映像を作る.
計画の段階2. シムの物理でつかめるかは再現しない (依頼 331・333 のサーボ・摩擦の合わせ込みは使わない).
アームのサーボ・カメラには触らない. KIOXIA には書かない (読むだけ). 既存のデータセットは書き換えない.

お手本: KIOXIA datasets/so101_redblock_box_teleop_even_v1 の index.json の 50 本 (並び・場所の印もここから).
  画像・state・action は index.json の sources の元 (Mac ~/so101_datasets の 4 つの LeRobot データセット. 640×480) を読む.
  元の data parquet の SHA-256 が index.json の値と同じことを確かめてから使う (KIOXIA の raw_episodes は 320×240 に縮めた写しのため).
シーン (sim_330.build_spec のまま):
  台座 = お手本 (11-23) のコマに合わせた置き方 (依頼 330 の fit_base). 元の記録 4 つごと: teleop_v1 は check_330/scene_measure_330.json の
       teleop_ep9, pos23・pos45・pos1b は --scene で各 ep0 の 5 コマに合わせた値 (check_334/scene_334.json の base_check).
  箱 = 本ごとに最初のコマ (机側) から依頼 330 の決め方 (measure_scene_330.fit_box) で出した位置・向き・縦横 (高さ 45mm・壁 3mm).
       (記録の回で箱が動いていた: pos45・pos1b は依頼 330 の値から約 30mm. --scene で確かめた) 手首カメラ = check_330/wrist_cam_330.json. カメラの値 = KIOXIA 2026-11-27 (arm_frame_v2).
  ブロック = 本ごとに最初のコマ (机側) から依頼 330 の決め方 (measure_scene_330.fit_block: 立方体の 8 隅を写した形と赤い所の IoU) で出す.
再生 (サーボで動かさない. mj_step しない. mj_forward だけ):
  腕 = 各コマの observation.state をそのまま関節に入れる (sim_330.set_arm_qpos. wrist_roll -90° など依頼 330 と同じ).
  ブロック = 次の 4 つの区切りで置く (物理では動かさない):
    1. 爪が閉じ始める (cs) まで: 最初の位置のまま.
    2. cs → 閉じた (c. state の爪がつかんだ値の帯 GRIP_BAND に入った最初のコマ): 爪の閉じた割合に比べて, 最初の位置から「つかんだ位置」へ動かす
       (実機では動く爪がブロックを固定側へ寄せる). つかんだ位置 = コマ c のシムの爪の先 (gripperframe) + 依頼 333 の手首カメラで出した
       爪に対する位置 (場所ごとの中央値 across・along・向き. check_333/grasp_rel_333.json), 高さ = 机の上.
    3. c → 開いた (r. 帯を出て爪の値が上がったコマ): gripper の body に固定して一緒に動かす.
    4. r から: 真下に落とす (重力 9.8 m/s², 箱の内側なら箱の底, 箱の壁の上なら壁の上, それ以外は机で止める).
撮る: 机側 (歪みあり)・手首 (歪みあり) を 640×480, 元と同じコマ数.
書き出す: ~/so101_datasets/so101_redblock_box_simreplay_v1 (LeRobot v3). 特徴量の名前・形・fps・robot_type は元と同じ.
  画像だけシム, observation.state・action は元のお手本の値そのまま. episode_labels.json に場所・元の印・シムの様子.
差を測る: 同じコマの実機とシムで 明るさ・色 (LAB の平均の差)・SSIM (灰色 320×240)・赤い所の重心 (机側・手首)・
  手首の赤い所の重なり (IoU・面積の比). 段階 (HOME・ブロックの上・つかむ・持ち上げ・箱の上・離す・戻る) を毎コマに付ける.
  SigLIP の特徴の近さは features_334.py (別の仮想環境) で出す.

使い方 (conda の lerobot 環境で):
    python so101/sim/simreplay_334.py --scene        # 本ごとのブロックの最初の位置・箱の確かめ・台座の確かめ → check_334/scene_334.json・block_init_334.csv
    python so101/sim/simreplay_334.py --run          # 再生・撮る・書き出す・差を測る → データセット・check_334/frames_334.csv・episodes_334.json・動画・絵
    python so101/sim/simreplay_334.py --run --dry --eps 0  # 書き出さずに 1 本だけ試す
"""

import argparse
import csv
import hashlib
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 make_sim_demo_330 as D  # noqa: E402
import measure_scene_330 as MS  # noqa: E402

OUT = HERE.parent / "check_334"
EVEN = Path("/Volumes/KIOXIA/r2r2r-data/datasets/so101_redblock_box_teleop_even_v1")
C330 = HERE.parent / "check_330"
C333 = HERE.parent / "check_333"
DS_NAME = "so101_redblock_box_simreplay_v1"
DS_ROOT = S.DATASETS / DS_NAME
REPO_ID = f"local/{DS_NAME}"
BLOCK_MASS_KG = 0.01  # エイイチが測った値. 物理で動かさないので絵には効かない (記録として残す)
GRIP_BAND = (9.5, 13.5)  # つかんだときの爪の値の帯 (ブロックに当たって 11.0〜11.3 で止まる. 空で閉じると 1 前後)
GRIP_MIN_RUN = 15  # 帯に続けて入っているコマ数の下限 (閉じる途中で帯を通り過ぎるコマを除く)
G_MM_S2 = 9800.0
STAGES = [("HOME", "HOME"), ("ABOVE_BLOCK", "ブロックの上"), ("GRASP", "つかむ"), ("LIFT", "持ち上げ"),
          ("ABOVE_BOX", "箱の上"), ("RELEASE", "離す"), ("RETURN", "戻る")]
RELEASE_FRAMES = 15
SHOW_PER_PLACE = 1  # 見比べの動画: 場所ごとに 1 本


# ---- 元のお手本 ------------------------------------------------------------------------------

def even_episodes():
    """index.json の 50 本 (並び = 新しいデータセットのエピソードの並び). 元の parquet の SHA-256 を確かめる."""
    idx = json.loads((EVEN / "index.json").read_text())
    for name, src in idx["sources"].items():
        root = Path(src["path"])
        for rel, sha in src["data_sha256"].items():
            h = hashlib.sha256((root / rel).read_bytes()).hexdigest()
            if h != sha:
                raise SystemExit(f"元のデータ {root / rel} の SHA-256 が index.json と違う")
    return idx


def label_of(src, ep):
    lab = json.loads((S.DATASETS / src / "episode_labels.json").read_text())
    return next(e["label"] for e in lab["episodes"] if e["episode_index"] == ep)


def iter_frames(ds_name, ep, key):
    """エピソードの key のコマを先頭から順に (k, BGR) で出す (全部を一度に持たない)."""
    import av
    root = S.DATASETS / ds_name
    e, st, _ = T.read_episode_any(ds_name, ep)
    p = f"videos/observation.images.{key}"
    fn = root / f"{p}/chunk-{int(e[p + '/chunk_index']):03d}/file-{int(e[p + '/file_index']):03d}.mp4"
    t0 = float(e[p + "/from_timestamp"])
    n = len(st)
    nxt = 0
    with av.open(str(fn)) as c:
        s = c.streams.video[0]
        c.seek(int(max(0.0, t0 - 1.0) / s.time_base), stream=s)
        for fr in c.decode(s):
            k = int(round((float(fr.pts * s.time_base) - t0) * S.FPS))
            if k < nxt:
                continue
            if k != nxt:
                raise RuntimeError(f"{ds_name} ep{ep} {key}: コマ {nxt} が抜けている (次が {k})")
            yield k, fr.to_ndarray(format="bgr24")
            nxt += 1
            if nxt >= n:
                return
    if nxt < n:
        raise RuntimeError(f"{ds_name} ep{ep} {key}: コマが足りない ({nxt}/{n})")


# ---- シーン ----------------------------------------------------------------------------------

def base_scene():
    meas = json.loads((C330 / "scene_measure_330.json").read_text())
    wr = json.loads((C330 / "wrist_cam_330.json").read_text())["fit"]
    x = meas["box"]["fit"]
    box = {"xy": x["xy_mm"], "yaw": x["yaw_deg"], "size_xy": x["outer_mm"], "height": x["height_mm"], "wall": D.BOX_WALL_MM}
    base = meas["base_fit"]["teleop_ep9_20261123"]["yaw_and_shift"]
    return box, base, {"pos_mm": wr["pos_mm"], "rotvec": wr["rotvec"]}


def scene_mode(idx):
    """本ごとのブロックの最初の位置 (依頼 330 の決め方) と, 確かめとして箱の位置・台座の置き方."""
    OUT.mkdir(parents=True, exist_ok=True)
    cams = S.load_cameras()
    cam = cams["desk"]
    maps = {"desk": S.DistortMap(cam["K"], cam["D"])}
    box330, base330, _ = base_scene()
    rows = []
    for i, e in enumerate(idx["episodes"]):
        src, ep = e["source"], e["episode_index"]
        real0 = next(iter_frames(src, ep, "desk"))[1]
        blk, _ = MS.fit_block(real0, cam)
        try:
            bx, _ = MS.fit_box(real0, cam, seed_xy=(520, 285))
            bxf = bx["fit"]
        except RuntimeError as ex:
            bxf = {"error": str(ex)}
        f = blk["fit"]
        rows.append({"new_episode_index": i, "source": src, "source_episode": ep, "place": e["place"],
                     "block_xy_mm": f["xy_mm"], "block_yaw_deg": f["yaw_deg"], "block_size_mm": f["size_mm"], "block_iou": f["iou"],
                     "red_centroid_px": blk["red_centroid_px"], "red_px": blk["red_px_count"],
                     "literal_desk_plane_mm": blk["literal_desk_plane_mm"], "box_fit_frame0": bxf})
        print(i, src[-6:], ep, e["place"], f, flush=True)
    # 台座の置き方の確かめ: 元の 4 つのうち ep9 (依頼 330 で合わせた) 以外の 3 つで 1 本ずつ, 同じ測り方で合わせる
    MS.OUT = OUT  # fit_base の絵の置き場所を check_334 にする
    checks = {}
    for src, ep in (("so101_redblock_box_teleop_v1_pos23", 0), ("so101_redblock_box_teleop_v1_pos45", 0),
                    ("so101_redblock_box_teleop_v1_pos1b", 0)):
        _, st, _ = T.read_episode_any(src, ep)
        n = len(st)
        fi = [int(n * q) for q in (0.35, 0.45, 0.55, 0.65, 0.75)]
        fr = T.read_frames_any(src, ep, "desk", fi)
        checks[f"{src}_ep{ep}"] = MS.fit_base([(st[k], fr[k]) for k in fi], cams, maps, f"{src[-6:]}_ep{ep}")
        print(src, checks[f"{src}_ep{ep}"]["yaw_and_shift"], flush=True)
    sizes = np.array([r["block_size_mm"] for r in rows])
    boxes = np.array([r["box_fit_frame0"]["xy_mm"] for r in rows if "xy_mm" in r["box_fit_frame0"]])
    res = {"time": datetime.now().isoformat(timespec="seconds"), "made_by": "so101/sim/simreplay_334.py --scene (依頼 334)",
           "how": "ブロック = 各本の最初のコマ (机側) の赤い所に, 立方体の 8 隅を写した形を合わせた (measure_scene_330.fit_block). "
                  "箱 = 同じく fit_box (確かめだけ. シムの箱は依頼 330 の値). 台座 = fit_base (確かめだけ. シムは依頼 330 の teleop_ep9)",
           "block_size_mm": {"median": round(float(np.median(sizes)), 1), "min": float(sizes.min()), "max": float(sizes.max())},
           "box_330": box330, "box_frame0_xy_mm": {"median": np.median(boxes, 0).round(1).tolist(),
                                                   "max_dist_from_330_mm": round(float(np.linalg.norm(boxes - box330["xy"], axis=1).max()), 1)},
           "base_330_teleop_ep9": base330, "base_check": checks, "episodes": rows}
    (OUT / "scene_334.json").write_text(json.dumps(res, ensure_ascii=False, indent=1))
    with open(OUT / "block_init_334.csv", "w", newline="") as fh:
        w = csv.writer(fh)
        w.writerow(["new_episode_index", "source", "source_episode", "place", "block_x_mm", "block_y_mm", "block_yaw_deg",
                    "block_size_mm", "iou", "red_cx_px", "red_cy_px", "box_x_mm", "box_y_mm"])
        for r in rows:
            b = r["box_fit_frame0"].get("xy_mm", [None, None])
            w.writerow([r["new_episode_index"], r["source"], r["source_episode"], r["place"], *r["block_xy_mm"], r["block_yaw_deg"],
                        r["block_size_mm"], r["block_iou"], *r["red_centroid_px"], *b])
    print(json.dumps({k: v for k, v in res.items() if k not in ("episodes", "base_check")}, ensure_ascii=False))


def scene_of(sc, i, box330, base330):
    """本 i の箱 (最初のコマから測った値) と台座の置き方 (元の記録ごと)."""
    r = sc["episodes"][i]
    f = r["box_fit_frame0"]
    box = dict(box330) if "xy_mm" not in f else {"xy": f["xy_mm"], "yaw": f["yaw_deg"], "size_xy": f["outer_mm"],
                                                 "height": f["height_mm"], "wall": D.BOX_WALL_MM}
    key = next((k for k in sc["base_check"] if k.startswith(r["source"] + "_ep")), None)
    base = base330 if key is None else sc["base_check"][key]["yaw_and_shift"]
    return box, base


# ---- ブロックの道 --------------------------------------------------------------------------

def grip_events(g):
    """cs (閉じ始め), c (帯に入った), r (帯を出て開いた). 帯に GRIP_MIN_RUN コマ以上続けて入る所のうち最も長い所."""
    inb = (g >= GRIP_BAND[0]) & (g <= GRIP_BAND[1])
    runs, i = [], 0
    while i < len(g):
        if inb[i]:
            j = i
            while j + 1 < len(g) and inb[j + 1]:
                j += 1
            runs.append((i, j))
            i = j + 1
        else:
            i += 1
    runs = [r for r in runs if r[1] - r[0] + 1 >= GRIP_MIN_RUN]
    if not runs:
        return None
    c, e = max(runs, key=lambda r: r[1] - r[0])
    cs = c
    while cs > 0 and g[cs - 1] > g[cs] + 0.05:
        cs -= 1
    r = e + 1 if e + 1 < len(g) else None
    return {"cs": int(cs), "c": int(c), "r": r, "runs": len(runs)}


def yaw_quat(yaw_deg):
    a = math.radians(yaw_deg)
    return np.array([math.cos(a / 2), 0, 0, math.sin(a / 2)])


def mat_to_quat(R):
    import mujoco
    q = np.zeros(4)
    mujoco.mju_mat2Quat(q, np.asarray(R, float).reshape(9))
    return q


def quat_to_mat(q):
    import mujoco
    R = np.zeros(9)
    mujoco.mju_quat2Mat(R, np.asarray(q, float))
    return R.reshape(3, 3)


def floor_z(xy, box, s):
    """真下に落としたときに止まる高さ (ブロックの中心, mm) と, どこで止まったか."""
    a = math.radians(-box["yaw"])
    dx, dy = xy[0] - box["xy"][0], xy[1] - box["xy"][1]
    lx, ly = math.cos(a) * dx - math.sin(a) * dy, math.sin(a) * dx + math.cos(a) * dy
    hx, hy, t = box["size_xy"][0] / 2, box["size_xy"][1] / 2, box["wall"]
    if abs(lx) < hx - t and abs(ly) < hy - t:
        return t + s / 2, "box_floor"
    if abs(lx) < hx + s / 2 and abs(ly) < hy + s / 2:
        return box["height"] + s / 2, "box_rim"
    return s / 2, "table"


class Replay:
    def __init__(self, scene, base, wrist, maps, cams, render=True):
        import mujoco
        self.mj = mujoco
        self.sim = D.Sim(scene, base, wrist, {"block_mass_kg": BLOCK_MASS_KG}, maps, cams)
        self.m, self.d = self.sim.m, self.sim.d
        self.qadr = self.m.joint("block_free").qposadr[0]
        self.gid = self.m.body("gripper").id
        self.cr = S.Cams(self.m, maps) if render else None
        self.scene = scene

    def pose_arm(self, st):
        S.set_arm_qpos(self.m, self.d, dict(zip(S.MOTORS, st)))
        self.mj.mj_forward(self.m, self.d)

    def set_block(self, p_mm, quat):
        self.d.qpos[self.qadr:self.qadr + 3] = (np.asarray(p_mm, float) + D.AXIS_OFF) / 1000
        self.d.qpos[self.qadr + 3:self.qadr + 7] = quat
        self.mj.mj_forward(self.m, self.d)

    def gripper_pose(self):
        return self.d.xpos[self.gid] * 1000 - D.AXIS_OFF, self.d.xmat[self.gid].reshape(3, 3).copy()

    def jaw_dirs(self):
        """依頼 333 (make_sim_demo_333.jaw_dirs) と同じ: 爪の先, 動く爪が閉じる向き a, 直角で腕の外向き b."""
        import make_sim_demo_333 as M3
        return M3.jaw_dirs(self.sim)


def plan_block(rp, states, blk0, rel, box):
    """各コマのブロックの位置 (mm)・向き (quat)・様子. rp = Replay (絵は描かない)."""
    s = blk0["size"]
    p0 = np.array([blk0["xy"][0], blk0["xy"][1], s / 2])
    q0 = yaw_quat(blk0["yaw"])
    n = len(states)
    ev = grip_events(states[:, 5])
    pos = np.repeat(p0[None], n, 0)
    quat = np.repeat(q0[None], n, 0)
    info = {"grip": ev}
    if ev is None:
        info["note"] = "爪がつかんだ値の帯に入らない (つかんでいない). ブロックは最初の位置のまま"
        return pos, quat, info
    cs, c, r = ev["cs"], ev["c"], ev["r"]
    rp.pose_arm(states[c])
    tip, a, b = rp.jaw_dirs()
    xy_g = tip[:2] + rel["across"] * a + rel["along"] * b
    yaw_g = math.degrees(math.atan2(a[1], a[0])) + rel["yaw"]
    dyaw = (yaw_g - blk0["yaw"] + 45) % 90 - 45  # 立方体なので 90° で一回り. 近い向きへ回す
    pg = np.array([xy_g[0], xy_g[1], s / 2])
    g = states[:, 5]
    for i in range(cs, c + 1):
        w = 1.0 if c == cs else float(np.clip((g[cs] - g[i]) / (g[cs] - g[c]), 0, 1))
        pos[i] = p0 + w * (pg - p0)
        quat[i] = yaw_quat(blk0["yaw"] + w * dyaw)
    gp, gR = rp.gripper_pose()
    Rb = quat_to_mat(yaw_quat(blk0["yaw"] + dyaw))
    rel_p = gR.T @ (pg - gp)
    rel_R = gR.T @ Rb
    end = r if r is not None else n
    for i in range(c + 1, end):
        rp.pose_arm(states[i])
        gp, gR = rp.gripper_pose()
        pos[i] = gp + gR @ rel_p
        quat[i] = mat_to_quat(gR @ rel_R)
    info.update({"tip_at_c_mm": tip.round(1).tolist(), "grasp_xy_mm": xy_g.round(1).tolist(),
                 "grasp_yaw_deg": round(float(blk0["yaw"] + dyaw), 1),
                 "slide_mm": round(float(np.linalg.norm(pg[:2] - p0[:2])), 1),
                 "slide_across_along_mm": [round(float((pg[:2] - p0[:2]) @ a), 1), round(float((pg[:2] - p0[:2]) @ b), 1)],
                 "tip_z_at_c_mm": round(float(tip[2]), 1)})
    if r is None:
        info["note"] = "最後まで爪が開かない (ブロックは爪に付いたまま)"
        info["final_mm"] = pos[-1].round(1).tolist()
        info["landed"] = "in_gripper"
        return pos, quat, info
    pr, qr = pos[r - 1].copy(), quat[r - 1].copy()
    zf, where = floor_z(pr[:2], box, s)
    # 落ちるときの向き: 傾きは残すと浮くので, 縦軸まわりの向きだけ残す (落ちたら机・底に平らに置く)
    Rr = quat_to_mat(qr)
    yaw_r = math.degrees(math.atan2(Rr[1, 0], Rr[0, 0]))
    for i in range(r, n):
        t = (i - r + 1) / S.FPS
        z = max(zf, pr[2] - 0.5 * G_MM_S2 * t * t)
        pos[i] = [pr[0], pr[1], z]
        quat[i] = qr if z > zf else yaw_quat(yaw_r)
    info.update({"release_from_mm": pr.round(1).tolist(), "final_mm": pos[-1].round(1).tolist(), "landed": where,
                 "drop_mm": round(float(pr[2] - zf), 1)})
    return pos, quat, info


def stages_of(rp, states, pos, info, box, s):
    """毎コマの段階の番号 (STAGES の順)."""
    n = len(states)
    st = states[:, :5]
    moved = np.where(np.abs(st - st[0]).max(1) > 3.0)[0]
    m0 = int(moved[0]) if len(moved) else n
    lab = np.zeros(n, int)
    ev = info["grip"]
    if ev is None:
        lab[m0:] = 1
        return lab
    cs, c, r = ev["cs"], ev["c"], ev["r"] if ev["r"] is not None else n
    lifted = np.where(pos[c:r, 2] > s / 2 + 5.0)[0]
    lf = c + int(lifted[0]) if len(lifted) else r
    near = math.hypot(*np.array(box["size_xy"]) / 2) + 20.0
    nb = r
    for i in range(lf, r):
        rp.pose_arm(states[i])
        tip = rp.sim.tip_mm()
        if math.hypot(tip[0] - box["xy"][0], tip[1] - box["xy"][1]) < near:
            nb = i
            break
    bounds = [0, min(m0, cs), cs, lf, nb, r, min(n, r + RELEASE_FRAMES), n]
    for k in range(7):
        lab[bounds[k]:max(bounds[k], bounds[k + 1])] = k
    return lab


# ---- 差を測る ------------------------------------------------------------------------------

def ssim_gray(a, b):
    a = cv2.resize(cv2.cvtColor(a, cv2.COLOR_BGR2GRAY), (320, 240)).astype(np.float64)
    b = cv2.resize(cv2.cvtColor(b, cv2.COLOR_BGR2GRAY), (320, 240)).astype(np.float64)
    C1, C2 = (0.01 * 255) ** 2, (0.03 * 255) ** 2
    bl = lambda x: cv2.GaussianBlur(x, (11, 11), 1.5)  # noqa: E731
    ma, mb = bl(a), bl(b)
    va, vb, cab = bl(a * a) - ma * ma, bl(b * b) - mb * mb, bl(a * b) - ma * mb
    s = ((2 * ma * mb + C1) * (2 * cab + C2)) / ((ma * ma + mb * mb + C1) * (va + vb + C2))
    return float(s[5:-5, 5:-5].mean())


def red_mask_all(img):
    """赤い所 (measure_scene_330.red_mask と同じ閾値. いちばん大きいかたまり). 無ければ None."""
    return MS.red_mask(img)


def frame_metrics(real, sim, key):
    lr = cv2.cvtColor(real, cv2.COLOR_BGR2LAB).reshape(-1, 3).astype(np.float64)
    ls = cv2.cvtColor(sim, cv2.COLOR_BGR2LAB).reshape(-1, 3).astype(np.float64)
    out = {f"{key}_L_real": lr[:, 0].mean() * 100 / 255, f"{key}_L_sim": ls[:, 0].mean() * 100 / 255,
           f"{key}_a_diff": (ls[:, 1].mean() - lr[:, 1].mean()), f"{key}_b_diff": (ls[:, 2].mean() - lr[:, 2].mean()),
           f"{key}_absdiff": float(np.abs(real.astype(np.int16) - sim.astype(np.int16)).mean()),
           f"{key}_ssim": ssim_gray(real, sim)}
    out[f"{key}_L_diff"] = out[f"{key}_L_sim"] - out[f"{key}_L_real"]
    mr, ms = red_mask_all(real), red_mask_all(sim)
    for tag, mk in (("real", mr), ("sim", ms)):
        if mk is None or mk.sum() < 30:
            out[f"{key}_red_{tag}_px"] = 0
            out[f"{key}_red_{tag}_cx"] = out[f"{key}_red_{tag}_cy"] = float("nan")
        else:
            ys, xs = np.nonzero(mk)
            out[f"{key}_red_{tag}_px"] = int(mk.sum())
            out[f"{key}_red_{tag}_cx"], out[f"{key}_red_{tag}_cy"] = float(xs.mean()), float(ys.mean())
    if out[f"{key}_red_real_px"] and out[f"{key}_red_sim_px"]:
        out[f"{key}_red_dist_px"] = math.hypot(out[f"{key}_red_sim_cx"] - out[f"{key}_red_real_cx"],
                                               out[f"{key}_red_sim_cy"] - out[f"{key}_red_real_cy"])
        out[f"{key}_red_iou"] = MS.iou(mr, ms)
        out[f"{key}_red_area_ratio"] = out[f"{key}_red_sim_px"] / out[f"{key}_red_real_px"]
    else:
        out[f"{key}_red_dist_px"] = out[f"{key}_red_iou"] = out[f"{key}_red_area_ratio"] = float("nan")
    return out


# ---- 再生・撮る・書き出す --------------------------------------------------------------------

def tile(real, sim, label):
    a = cv2.resize(real, (320, 240))
    b = cv2.resize(sim, (320, 240))
    out = np.hstack([a, b])
    cv2.putText(out, label, (6, 18), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 255, 255), 1, cv2.LINE_AA)
    return out


def run_mode(idx, eps_sel, dry):
    OUT.mkdir(parents=True, exist_ok=True)
    cams = S.load_cameras()
    maps = {k: S.DistortMap(cams[k]["K"], cams[k]["D"]) for k in ("desk", "wrist")}
    box330, base330, wrist = base_scene()
    sc = json.loads((OUT / "scene_334.json").read_text())
    g333 = json.loads((C333 / "grasp_rel_333.json").read_text())["places"]
    import make_sim_demo_333 as M3
    rels = {}
    for p in range(1, 6):
        w = g333[str(p)]["wrist"]
        yr = [e["rel_wrist"]["yaw_rel_deg"] for e in json.loads((C333 / "grasp_rel_333.json").read_text())["episodes"]
              if e["place"] == p and e["label"] == "success" and e["rel_wrist"]]
        rels[p] = {"across": w["across_mm"]["median"], "along": w["along_mm"]["median"], "yaw": M3.yaw90_mean(yr)[0]}
    eps_all = list(enumerate(idx["episodes"]))
    eps = [eps_all[i] for i in eps_sel] if eps_sel else eps_all
    show = {}
    for i, e in eps_all:
        show.setdefault(e["place"], [])
        if len(show[e["place"]]) < SHOW_PER_PLACE:
            show[e["place"]].append(i)
    show_set = {i for v in show.values() for i in v}

    ds = None
    if not dry:
        from lerobot.datasets.lerobot_dataset import LeRobotDataset
        D.check_root(DS_ROOT)
        if DS_ROOT.exists():
            raise SystemExit(f"{DS_ROOT} がすでにある (上書きしない)")
        info = json.loads(D.REAL_INFO.read_text())
        feats = {k: {"dtype": info["features"][k]["dtype"], "shape": tuple(info["features"][k]["shape"]),
                     "names": info["features"][k]["names"]}
                 for k in ("action", "observation.state", "observation.images.wrist", "observation.images.desk")}
        ds = LeRobotDataset.create(repo_id=REPO_ID, fps=info["fps"], features=feats, root=DS_ROOT,
                                   robot_type=info["robot_type"], use_videos=True)

    fcsv = OUT / ("frames_334.csv" if not dry else "frames_334_dry.csv")
    fh = open(fcsv, "w", newline="")
    wr_csv = None
    ep_rows = []
    worst = []  # (score, tag, ep, frame, real desk, sim desk, real wrist, sim wrist)
    for i, e in eps:
        src, sep, place = e["source"], e["episode_index"], e["place"]
        _, states, actions = T.read_episode_any(src, sep)
        b0 = sc["episodes"][i]
        assert b0["source"] == src and b0["source_episode"] == sep
        blk0 = {"xy": b0["block_xy_mm"], "yaw": b0["block_yaw_deg"], "size": b0["block_size_mm"]}
        box, base = scene_of(sc, i, box330, base330)
        scene = {"block": dict(blk0), "box": box}
        rp = Replay(scene, base, wrist, maps, cams, render=True)
        pos, quat, binfo = plan_block(rp, states, blk0, rels[place], box)
        lab = stages_of(rp, states, pos, binfo, box, blk0["size"])
        vw = None
        if i in show_set:
            vw = cv2.VideoWriter(str(OUT / f"compare_334_ep{i:02d}_place{place}.mp4"), cv2.VideoWriter_fourcc(*"mp4v"),
                                 S.FPS, (640, 480))
        n = len(states)
        for (k, rd), (k2, rw) in zip(iter_frames(src, sep, "desk"), iter_frames(src, sep, "wrist")):
            assert k == k2
            rp.pose_arm(states[k])
            rp.set_block(pos[k], quat[k])
            sd = rp.cr.render(rp.d, "desk")
            sw = rp.cr.render(rp.d, "wrist")
            if ds is not None:
                ds.add_frame({"action": np.asarray(actions[k], np.float32), "observation.state": np.asarray(states[k], np.float32),
                              "observation.images.desk": cv2.cvtColor(sd, cv2.COLOR_BGR2RGB),
                              "observation.images.wrist": cv2.cvtColor(sw, cv2.COLOR_BGR2RGB), "task": D.TASK})
            met = {"new_episode_index": i, "frame": k, "place": place, "stage": STAGES[lab[k]][0],
                   "block_x_mm": pos[k][0], "block_y_mm": pos[k][1], "block_z_mm": pos[k][2]}
            met.update(frame_metrics(rd, sd, "desk"))
            met.update(frame_metrics(rw, sw, "wrist"))
            # 手首: シムのブロックのうち爪に隠された割合 (ブロックだけの形 vs 絵の赤い所)
            bm = rp.cr.seg_bodies(rp.d, "wrist", ["block"])
            ms = MS.red_mask(sw)
            met["wrist_sim_block_px"] = int(bm.sum())
            met["wrist_sim_block_hidden"] = (1 - (ms & bm).sum() / bm.sum()) if (bm.sum() > 30 and ms is not None) else float("nan")
            if wr_csv is None:
                wr_csv = csv.DictWriter(fh, fieldnames=list(met.keys()))
                wr_csv.writeheader()
            wr_csv.writerow({kk: (round(v, 4) if isinstance(v, float) else v) for kk, v in met.items()})
            if vw is not None:
                fr = np.vstack([tile(rd, sd, f"ep{i} f{k} {STAGES[lab[k]][0]}  real | sim"),
                                tile(rw, sw, "wrist  real | sim")])
                vw.write(fr)
            for tag, score in (("desk_ssim", -met["desk_ssim"]), ("wrist_ssim", -met["wrist_ssim"]),
                               ("desk_red_dist", met["desk_red_dist_px"]), ("wrist_red_dist", met["wrist_red_dist_px"])):
                if not np.isnan(score) and k % 10 == 0:
                    worst.append((score, tag, i, k, STAGES[lab[k]][0], cv2.resize(rd, (320, 240)), cv2.resize(sd, (320, 240)),
                                  cv2.resize(rw, (320, 240)), cv2.resize(sw, (320, 240))))
            if len(worst) > 400:
                worst = keep_worst(worst)
        if vw is not None:
            vw.release()
        if ds is not None:
            ds.save_episode()
        rp.cr.close()
        in_box = binfo.get("landed") == "box_floor"
        row = {"new_episode_index": i, "source": src, "source_episode": sep, "place": place,
               "label_source": label_of(src, sep), "frames": n, "block_init": blk0, "box": box, "base_offset": base,
               "sim_block_in_box": in_box,
               "block": binfo, "stage_frames": {STAGES[s][0]: int((lab == s).sum()) for s in range(7)}}
        ep_rows.append(row)
        print(i, place, n, binfo.get("landed"), binfo.get("slide_mm"), binfo.get("final_mm"), flush=True)
    fh.close()
    worst = keep_worst(worst)
    montage(worst)
    res = {"time": datetime.now().isoformat(timespec="seconds"), "made_by": "so101/sim/simreplay_334.py --run (依頼 334)",
           "dry": dry, "scene": {"box": "本ごと (最初のコマの机側から fit_box. 大きさ・向きも. 壁 3mm・高さ 45mm)",
                                 "base_offset": "元の記録ごと (teleop_v1 = 依頼 330 の teleop_ep9. ほかは scene_334.json の base_check)",
                                 "wrist_cam": wrist, "block_mass_kg": BLOCK_MASS_KG,
                                 "grip_band": GRIP_BAND, "grip_min_run": GRIP_MIN_RUN, "grasp_rel_333_wrist": rels},
           "episodes": ep_rows}
    (OUT / ("episodes_334.json" if not dry else "episodes_334_dry.json")).write_text(json.dumps(res, ensure_ascii=False, indent=1))
    if ds is not None:
        ds.finalize()
        write_labels(ep_rows, res)
        verify_dataset(eps)


def keep_worst(worst, per_tag=8):
    out = []
    for tag in sorted({w[1] for w in worst}):
        ws = sorted([w for w in worst if w[1] == tag], key=lambda w: -w[0])
        seen, kept = set(), []
        for w in ws:  # 同じ本から 2 枚まで
            if sum(1 for x in kept if x[2] == w[2]) >= 2:
                continue
            kept.append(w)
            if len(kept) >= per_tag:
                break
        out += kept
    return out


def montage(worst):
    for tag in sorted({w[1] for w in worst}):
        rows = []
        for w in [x for x in worst if x[1] == tag]:
            score, _, ep, k, stg, rd, sd, rw, sw = w
            r = np.hstack([rd, sd, rw, sw])
            cv2.putText(r, f"ep{ep} f{k} {stg} {tag}={abs(score):.3f}", (6, 18), cv2.FONT_HERSHEY_SIMPLEX, 0.5,
                        (0, 255, 255), 1, cv2.LINE_AA)
            rows.append(r)
        if rows:
            cv2.imwrite(str(OUT / f"worst_{tag}_334.png"), np.vstack(rows))


def write_labels(ep_rows, res):
    labels = {"dataset": REPO_ID, "made_by": "依頼 334 so101/sim/simreplay_334.py (シムで再生した映像. 人の判定ではない)",
              "source": str(EVEN / "index.json"),
              "note": "画像 (desk・wrist) だけシム. observation.state・action は元のお手本 (index.json の sources) の値そのまま. "
                      "label = 元のお手本の印 (エイイチの判定). sim_block_in_box = シムでブロックが箱の底に落ちたか. "
                      "腕は state をそのまま関節に入れた (サーボ・物理なし). ブロックは爪がつかんだ値の帯の間だけ爪に固定し, 開いたら真下に落とした",
              "episodes": []}
    for r in ep_rows:
        labels["episodes"].append({"episode_index": r["new_episode_index"], "place": r["place"], "label": r["label_source"],
                                   "source_dataset": f"local/{r['source']}", "source_episode_index": r["source_episode"],
                                   "frames": r["frames"], "sim_block_in_box": r["sim_block_in_box"],
                                   "block_init_xy_mm": r["block_init"]["xy"], "block_init_yaw_deg": r["block_init"]["yaw"],
                                   "block_size_mm": r["block_init"]["size"], "landed": r["block"].get("landed")})
    (DS_ROOT / "episode_labels.json").write_text(json.dumps(labels, ensure_ascii=False, indent=1))
    (DS_ROOT / "SIM_NOTES.json").write_text(json.dumps({k: v for k, v in res.items() if k != "episodes"}, ensure_ascii=False, indent=1))


def verify_dataset(eps):
    """読み返して, 本数・コマ数・state・action が元と同じかを確かめる."""
    import pandas as pd
    files = sorted((DS_ROOT / "data").glob("chunk-*/file-*.parquet"))
    df = pd.concat([pd.read_parquet(f) for f in files])
    bad = []
    for i, e in eps:
        _, st, ac = T.read_episode_any(e["source"], e["episode_index"])
        d = df[df["episode_index"] == i].sort_values("frame_index")
        s2, a2 = np.stack(d["observation.state"].to_numpy()), np.stack(d["action"].to_numpy())
        if s2.shape != st.shape or a2.shape != ac.shape or np.abs(s2 - st).max() > 0 or np.abs(a2 - ac).max() > 0:
            bad.append(i)
    info = json.loads((DS_ROOT / "meta" / "info.json").read_text())
    v = {"episodes": info["total_episodes"], "frames": info["total_frames"], "state_action_mismatch": bad}
    (OUT / "dataset_verify_334.json").write_text(json.dumps(v, ensure_ascii=False, indent=1))
    print("verify", v)
    if bad:
        raise SystemExit(f"state・action が元と違う本: {bad}")


def main():
    ap = argparse.ArgumentParser()
    ap.add_argument("--scene", action="store_true")
    ap.add_argument("--run", action="store_true")
    ap.add_argument("--dry", action="store_true", help="--run で書き出さない (試し)")
    ap.add_argument("--eps", default="", help="--run で流す本 (新しい番号. 例 0,10)")
    args = ap.parse_args()
    idx = even_episodes()
    if args.scene:
        scene_mode(idx)
    if args.run:
        sel = [int(x) for x in args.eps.split(",")] if args.eps else []
        if sel and not args.dry:
            raise SystemExit("--eps は --dry のときだけ (書き出すときは 50 本全部)")
        run_mode(idx, sel, args.dry)


if __name__ == "__main__":
    main()
