"""依頼 369: 爪の中のブロックの付く位置を c = b (依頼 362 のつかむ所の計算) + 全部の本に共通の along 1 つ にして,
依頼 367 の置き方 (箱 = box_365.json・見た目 level 9 = level 8 + light_367.json の光・回 v2・ブロック 推定置き) で再生する.
比べのため 同じ置き方で b (along 0) も出せる (--grasp b).
アームのサーボ・カメラには触らない. 既にある sim/ のファイルは書き換えない (読み込んで使うだけ. 出力先は 実行の中だけ check_369 にする).

  along の向き・足し方は diag_369.c_pose と同じ (腕の外向き b_dir に along. 閉じる向きは 固定側の爪に触れる所に寄せ直す)

書き出す (check_369/<tag>/. commit しない): ep{割り振りの番号}_frames.csv・ep{..}.json・sim_video/・demo/・args.json

使い方 (conda の lerobot 環境で):
    python so101/sim/simreplay_369.py --tag c_lv9 --grasp c --along -2.3 --eps all
    python so101/sim/simreplay_369.py --tag b_lv9 --grasp b --eps all
"""

import argparse
import json
import sys
from pathlib import Path

HERE = Path(__file__).resolve().parent
SO101 = HERE.parent
sys.path.insert(0, str(HERE))
import appearance_355 as A5  # noqa: E402
import simreplay_335 as V2  # noqa: E402
import simreplay_353 as P3  # noqa: E402
import simreplay_362 as Y2  # noqa: E402
import simreplay_367 as Y7  # noqa: E402
import sim_335 as G  # noqa: E402
import diag_369 as D9  # noqa: E402

OUT = SO101 / "check_369"


def patch_c(along_c):
    """simreplay_362.plan_block_362 を この実行の中だけ c にする (rel_yz = b の gripper の y・z を受け, along_c を足す)."""
    def plan_block_c(rp, states, blk0, box, along=None, rel_yz=None):
        if rel_yz is None:
            return V2.plan_block_v2(rp, states, blk0, along, box)
        orig = G.grasp_block_pose

        def gbp(jaws, gp, gR, tip, b_dir, along_, size, q_open):
            return D9.c_pose(jaws, gp, gR, (float(rel_yz[0]), float(rel_yz[1])), b_dir, float(along_c), size)
        G.grasp_block_pose = gbp
        try:
            return V2.plan_block_v2(rp, states, blk0, along, box)
        finally:
            G.grasp_block_pose = orig
    Y2.plan_block_362 = plan_block_c


def main():
    ap = argparse.ArgumentParser()
    ap.add_argument("--tag", required=True)
    ap.add_argument("--grasp", choices=("b", "c"), required=True)
    ap.add_argument("--along", type=float, default=0.0, help="--grasp c の 共通の along (mm)")
    ap.add_argument("--level", type=int, choices=(8, 9), default=9)
    ap.add_argument("--eps", default="all")
    ap.add_argument("--no-video", action="store_true")
    a = ap.parse_args()
    su, P, lo = Y7.prepare(a.level)
    P3.OUT = OUT
    Y2.OUT = OUT
    Y7.OUT = OUT
    along_c = a.along if a.grasp == "c" else 0.0
    if a.grasp == "c":
        patch_c(along_c)
    rows = {r["plan_index"]: r for r in su["scene"]["episodes"]}
    eps = sorted(rows) if a.eps == "all" else [int(x) for x in a.eps.split(",")]
    out = OUT / a.tag
    out.mkdir(parents=True, exist_ok=True)
    (out / "args.json").write_text(json.dumps({
        "level": a.level, "render_level": Y2.LEVEL, "light_over": lo, "light_file": str(Y7.LIGHT367) if a.level >= 9 else None,
        "look": "v2", "grasp": a.grasp, "along_c_mm": along_c, "along_dir": "腕の外向き b_dir (依頼 362 の a と同じ向き). b の位置に足す",
        "box": su["box"], "box_file": str(Y7.BOX365), "base": Y2.Z.BASE0, "block": "est",
        "params355": str(A5.PARAMS355), "params362": str(Y2.PARAMS362), "grasp_map": su["pg"].desc}, ensure_ascii=False, indent=1))
    ns = argparse.Namespace(tag=a.tag, grasp="b", along="")
    for i in eps:
        Y2.run_ep(su, rows[i], ns, P, "v2", video=not a.no_video)
        f = out / f"ep{i:02d}.json"
        j = json.loads(f.read_text())
        j["grasp"]["how"] = a.grasp
        j["grasp"]["along_c_mm"] = along_c
        j["made_by"] = "so101/sim/simreplay_369.py (依頼 369. 中身は simreplay_362.run_ep)"
        f.write_text(json.dumps(j, ensure_ascii=False, indent=1, default=str))


if __name__ == "__main__":
    main()
