"""依頼 331: 実機に合わせたサーボのシム (so101_redblock_box_sim_v2) を, 実機と並べて見比べる (依頼 330 の compare_330 と同じ形).
サーボ・カメラは使わない (記録とデータセットを読むだけ).

読むもの: 実機のお手本 (teleop_v1 ep9)・同じ理想の道を実機で流した記録 (ideal_x13_v1 ep0)・シム v2 ep0・(並べる用) シム v1 ep0
出すもの (so101/check_331/): compare_real_sim.mp4・compare_ideal_replay_sim.mp4・compare_keyframes.png (行 = 依頼 330 の 6 行 +
    シム v1 の机側・手首)・compare_stats_331.json

使い方 (conda の lerobot 環境で):
    python so101/sim/compare_331.py
"""

import json
import sys
from datetime import datetime
from pathlib import Path

import cv2

HERE = Path(__file__).resolve().parent
sys.path.insert(0, str(HERE))
import sim_330 as S  # noqa: E402
from compare_330 import KEYS, all_frames, label, match_frames, stats, write_video  # noqa: E402
from make_sim_demo_330 import PATH_JSON  # noqa: E402
from measure_scene_330 import IDEAL_DS, IDEAL_EP, REAL_DS, REAL_EP  # noqa: E402

OUT = HERE.parent / "check_331"
DS_V2 = "so101_redblock_box_sim_v2"
DS_V1 = "so101_redblock_box_sim_v1"


def main():
    import numpy as np
    pj = json.loads(PATH_JSON.read_text())
    real = all_frames(REAL_DS, REAL_EP)
    ideal = all_frames(IDEAL_DS, IDEAL_EP)
    sim = all_frames(DS_V2, 0)
    sim1 = all_frames(DS_V1, 0)
    n1 = write_video(OUT / "compare_real_sim.mp4", real, sim, ("real teleop ep9", "sim v2"))
    n2 = write_video(OUT / "compare_ideal_replay_sim.mp4", ideal, sim, ("real ideal-path replay", "sim v2"))

    _, _, act_real = S.read_episode(REAL_DS, REAL_EP)
    kf = {k["name"]: k for k in pj["keyframes"]}
    path_idx = [kf[n]["frame"] for n, _ in KEYS]
    real_idx = match_frames(act_real, [kf[n]["pose"] for n, _ in KEYS])
    rows = []
    for title, src, idx in (("teleop desk", real, [k for k, _ in real_idx]), ("ideal replay desk", ideal, path_idx),
                            ("sim v2 desk", sim, path_idx), ("sim v1 desk", sim1, path_idx),
                            ("teleop wrist", real, [k for k, _ in real_idx]), ("ideal replay wrist", ideal, path_idx),
                            ("sim v2 wrist", sim, path_idx), ("sim v1 wrist", sim1, path_idx)):
        key = "desk" if "desk" in title else "wrist"
        row = []
        for (n, _), i in zip(KEYS, idx):
            img = src[key][min(i, len(src[key]) - 1)]
            row.append(cv2.resize(label(img, f"{title} {n} f{i}"), (320, 240)))
        rows.append(np.hstack(row))
    cv2.imwrite(str(OUT / "compare_keyframes.png"), np.vstack(rows))

    st = {}
    for name, src, i in (("teleop_frame0", real, 0), ("ideal_replay_frame0", ideal, 0), ("sim_v2_frame0", sim, 0),
                         ("teleop_ABOVE_BLOCK", real, real_idx[0][0]), ("ideal_replay_ABOVE_BLOCK", ideal, path_idx[0]),
                         ("sim_v2_ABOVE_BLOCK", sim, path_idx[0])):
        st[name] = {k: stats(src[k][i], k) for k in ("desk", "wrist")}
    res = {"time": datetime.now().isoformat(timespec="seconds"), "made_by": "so101/sim/compare_331.py (依頼 331)",
           "real": f"{REAL_DS} ep{REAL_EP} ({len(real['desk'])} コマ)", "ideal_replay": f"{IDEAL_DS} ep{IDEAL_EP} ({len(ideal['desk'])} コマ)",
           "sim": f"{DS_V2} ep0 ({len(sim['desk'])} コマ)", "video_frames": {"compare_real_sim.mp4": n1, "compare_ideal_replay_sim.mp4": n2},
           "keyframes": {n: {"path_frame": p, "teleop_frame": r[0]} for (n, _), p, r in zip(KEYS, path_idx, real_idx)},
           "stats": st}
    (OUT / "compare_stats_331.json").write_text(json.dumps(res, ensure_ascii=False, indent=2))
    print(json.dumps(res, ensure_ascii=False, indent=1))


if __name__ == "__main__":
    main()
