"""依頼 359: SO-101 の新しい決まり (rule_351) の成功 50 本 (~/so101_datasets/so101_redblock_box_ideal_var_v2 の label=success) を,
依頼 355 の最後のシム (level 8. appearance_355.json・joint_offset_342.json・wrist_grip_342.json のまま) で再生し直し,
手首の赤の重心の差の原因を分けるための数字を出す. アームのサーボ・カメラには触らない. 録ったお手本・KIOXIA は読むだけ.

  再生の仕方は 依頼 353・355 (simreplay_353.run_ep) と同じ. 違うのは次だけ:
    台座 = 固定した今の値 (arm_frame_v2.json のまま. ずれ 0). 箱 = check_336/pm1129_box/box_336.json (無ければ am_box). 回ごとに変えない
    見た目の回 (session) = pos1b (机側の明るさが同じ: 新しい 50 本の灰色の中央値 159, pos1b 160, ほかの回 193)
    ブロックの最初の位置・向き:
      plan = 割り振り (check_351/plan_351.json. 14 本目は check_357/plan_357.json) の画素を 机側カメラ (ideal_var/yaw_lib_343.desk_cam.
             録るときと同じ) で高さ 一辺/2 の面に戻した位置, 向き = 割り振りの向き, 一辺 21.7mm
      est  = 最初のコマ (机側) から 今までの決め方 (measure_scene_330.fit_block. 位置・向き・一辺)
    場所 = 割り振りの「場所N から …」の N (つかんだ所の爪の奥行き along は 依頼 333 の場所ごとの値. 今までと同じ)
  毎コマに足して出すもの (手首):
    wrist_hull_cx/cy        シムのブロックの 8 隅を写した凸包の重心 (隠れを入れない形だけの位置)
    wrist_hull0_cx/cy       同じ. 関節のずれを入れない (0) とき (机の上にある間だけ. 比べ)
    implied_x/y_mm          机の上にある間: 実機の手首の赤の重心に 凸包の重心が重なる ブロックの位置 (シムの腕・カメラのまま. 高さ・向き・一辺は置いたまま)
    wrist_roll_deg          実機の手首の回転 (state)

書き出す (check_359/<tag>/. commit しない): ep{割り振りの番号}_frames.csv・ep{..}.json・sim_video/・demo/ (場所ごとに 1 本)

使い方 (conda の lerobot 環境で):
    python so101/sim/simreplay_359.py --scene                       # 本の選び方・ブロックの推定 → check_359/scene_359.json
    python so101/sim/simreplay_359.py --tag plan --place plan --eps 0,1,2
    python so101/sim/simreplay_359.py --tag est --place est --eps all
"""

import argparse
import csv
import json
import math
import re
import sys
from datetime import datetime
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 / "ideal_var"))
import sim_330 as S  # noqa: E402
import sim_331 as T  # noqa: E402
import sim_335 as G  # noqa: E402
import measure_scene_330 as MS  # noqa: E402
import simreplay_334 as R  # noqa: E402
import simreplay_335 as V2  # noqa: E402
import simreplay_342 as R3  # noqa: E402
import simreplay_353 as P3  # noqa: E402
import simreplay_355 as Q5  # noqa: E402
import appearance_337 as A7  # noqa: E402
import appearance_353 as A3  # noqa: E402
import appearance_355 as A5  # noqa: E402

OUT = SO101 / "check_359"
DS = "so101_redblock_box_ideal_var_v2"
PLAN351 = SO101 / "check_351" / "plan_351.json"
PLAN357 = SO101 / "check_357" / "plan_357.json"
BOX_JSON = SO101 / "check_336" / "pm1129_box" / "box_336.json"
BOX_JSON_FALLBACK = SO101 / "check_336" / "am_box" / "box_336.json"
BASE0 = {"yaw_deg": 0.0, "tx_mm": 0.0, "ty_mm": 0.0}  # 台座は固定 (arm_frame_v2 のまま)
SESSION = "pos1b"
LEVEL = 8
BLOCK_MM = 21.7


def pick_episodes():
    """label=success の本 (割り振りの番号ごとに 1 本). 50 本でなければ止める."""
    lab = json.loads((S.DATASETS / DS / "episode_labels.json").read_text())
    ok = [e for e in lab["episodes"] if e["label"] == "success"]
    by = {}
    for e in ok:
        if e["plan_index"] in by:
            raise SystemExit(f"割り振り {e['plan_index']} の成功が 2 本ある ({by[e['plan_index']]['episode_index']}・{e['episode_index']})")
        by[e["plan_index"]] = e
    if len(ok) != 50 or sorted(by) != list(range(50)):
        raise SystemExit(f"成功が 50 本でない ({len(ok)} 本. 割り振り {sorted(by)})")
    return [by[i] for i in range(50)]


def plan_entry(e):
    p351 = json.loads(PLAN351.read_text())["episodes"]
    p357 = json.loads(PLAN357.read_text())["episodes"]
    use357 = "check_357" in str(e.get("plan", ""))
    pe = (p357 if use357 else p351)[e["plan_index"]]
    assert pe["index"] == e["plan_index"]
    if abs(pe["yaw"] - e["yaw_plan"]) > 0.05 or np.hypot(*(np.array(pe["pixel"]) - e["plan_pixel"])) > 0.05:
        raise SystemExit(f"episode {e['episode_index']}: 割り振りの値と台帳の値が違う")
    return pe, ("plan_357" if use357 else "plan_351")


def place_of(where):
    m = re.match(r"場所(\d)", where)
    return int(m.group(1))


def scene_mode():
    import yaw_lib_343 as Y
    OUT.mkdir(parents=True, exist_ok=True)
    eps = pick_episodes()
    cams = S.load_cameras()
    ycam = Y.desk_cam()
    rows = []
    for e in eps:
        pe, src_plan = plan_entry(e)
        xy = Y.pixel_to_desk_mm(ycam, pe["pixel"], z=BLOCK_MM / 2)
        real0 = next(R.iter_frames(DS, e["episode_index"], "desk"))[1]
        blk, _ = MS.fit_block(real0, cams["desk"])
        f = blk["fit"]
        rows.append({"plan_index": e["plan_index"], "episode_index": e["episode_index"], "plan_file": src_plan, "where": pe["where"],
                     "place": place_of(pe["where"]), "frames": e["frames"],
                     "plan": {"xy": [round(float(xy[0]), 1), round(float(xy[1]), 1)], "yaw": pe["yaw"], "size": BLOCK_MM, "pixel": pe["pixel"]},
                     "est": {"xy": f["xy_mm"], "yaw": f["yaw_deg"], "size": f["size_mm"], "iou": f["iou"]},
                     "record_read": {"xy": e["yaw_read"]["xy_mm"], "yaw": e["yaw_read"]["yaw"], "size": e["yaw_read"]["size_mm"],
                                     "pixel": [e["block_pixel"][0], e["block_pixel"][1]]},
                     "roll_grasp_deg": pe.get("roll_grasp_deg"), "yaw_rel_arm_deg": pe.get("yaw_rel_arm_deg"),
                     "arm_dir_deg": pe.get("arm_dir_deg"), "arm_r_mm": pe.get("arm_r_mm"), "rules_used": pe.get("rules_used")})
        r = rows[-1]
        d = np.hypot(*(np.array(r["est"]["xy"]) - r["plan"]["xy"]))
        print(e["plan_index"], e["episode_index"], r["place"], r["plan"], r["est"], f"差 {d:.1f}mm", flush=True)
    box_p = BOX_JSON if BOX_JSON.exists() else BOX_JSON_FALLBACK
    res = {"time": datetime.now().isoformat(timespec="seconds"), "made_by": "so101/sim/simreplay_359.py --scene (依頼 359)",
           "dataset": str(S.DATASETS / DS), "box_json": str(box_p), "base": BASE0, "session": SESSION, "level": LEVEL,
           "episodes": rows}
    (OUT / "scene_359.json").write_text(json.dumps(res, ensure_ascii=False, indent=1))


def load_box():
    p = BOX_JSON if BOX_JSON.exists() else BOX_JSON_FALLBACK
    f = json.loads(p.read_text())["box"]["fit"]
    return {"xy": f["xy_mm"], "yaw": f["yaw_deg"], "size_xy": f["outer_mm"], "height": f["height_mm"], "wall": R.D.BOX_WALL_MM}


def hull_c(px):
    return R3.hull_centroid(px)


def wrist_hull(blk_corners_fn, wcam, gpose):
    px, ok = G.project_wrist(blk_corners_fn, wcam, gpose)
    return hull_c(px) if ok.all() else None


def implied_xy(target, xy0, yaw, s, wcam, gpose):
    """実機の赤の重心 target (画素) に 凸包の重心が重なる 机の上のブロックの位置 (mm). ガウス・ニュートン (数値微分)."""
    xy = np.array(xy0, float)
    for _ in range(8):
        c = wrist_hull(S.box_corners(xy, yaw, [s, s], 0.0, s), wcam, gpose)
        if c is None:
            return None
        r = c - target
        if np.linalg.norm(r) < 0.05:
            break
        J = np.zeros((2, 2))
        for j in range(2):
            d = np.zeros(2)
            d[j] = 0.5
            c2 = wrist_hull(S.box_corners(xy + d, yaw, [s, s], 0.0, s), wcam, gpose)
            if c2 is None:
                return None
            J[:, j] = (c2 - c) / 0.5
        try:
            step = np.linalg.solve(J, r)
        except np.linalg.LinAlgError:
            return None
        xy = xy - np.clip(step, -30, 30)
    c = wrist_hull(S.box_corners(xy, yaw, [s, s], 0.0, s), wcam, gpose)
    if c is None or np.linalg.norm(c - target) > 1.0:
        return None
    return xy


def run_ep(su, row, how, tag, P, video=True):
    out = OUT / tag
    (out / "sim_video").mkdir(parents=True, exist_ok=True)
    (out / "demo").mkdir(parents=True, exist_ok=True)
    i, sep, place = row["plan_index"], row["episode_index"], row["place"]
    _, states, _ = T.read_episode_any(DS, sep)
    b = row[how]
    blk0 = {"xy": b["xy"], "yaw": b["yaw"], "size": b["size"]}
    box, base = su["box"], BASE0
    scene = {"block": dict(blk0), "box": box}
    look = A3.Look(P, LEVEL, SESSION, {})
    with A3.patched(look):
        rp = R3.Replay3(scene, base, su["wrist"], su["maps"], su["cams"], su["gmap"], render=True, joint_off=su["joint_off"])
    rp0 = R3.Replay3(scene, base, su["wrist"], su["maps"], su["cams"], su["gmap"], render=False, joint_off=None)
    lut = A7.geom_labels(rp.m)
    lut[rp.m.geom("table_tex").id] = A7.L_TABLE
    pos, quat, qg, held, binfo = V2.plan_block_v2(rp, states, blk0, su["rels"][place]["along"], box)
    lab_st = R.stages_of(rp, states, pos, binfo, box, blk0["size"])
    want = P3.demo_want(lab_st, binfo["grip"]) if i in su["demo_eps"] else {}
    Kw = su["cams"]["wrist"]["K"]
    wcam = G.wrist_cam(su["wrist"], Kw, su["cams"]["wrist"]["D"])
    cs = binfo["grip"]["cs"] if binfo["grip"] is not None else len(states)
    s = blk0["size"]
    c8_0 = S.box_corners(blk0["xy"], blk0["yaw"], [s, s], 0.0, s)
    wd = R3.Writer(out / "sim_video" / f"ep{i:02d}_desk.mp4") if video else None
    ww = R3.Writer(out / "sim_video" / f"ep{i:02d}_wrist.mp4") if video else None
    frows = []
    for (k, rd), (k2, rw) in zip(R.iter_frames(DS, sep, "desk"), R.iter_frames(DS, sep, "wrist")):
        assert k == k2
        rp.pose_arm(states[k], qg[k])
        rp.set_block(pos[k], quat[k])
        rd_s, labd = look.render(rp.cr, rp.d, "desk", lut)
        rw_s, labw = look.render(rp.cr, rp.d, "wrist", lut)
        if labw is None:
            labw = A7.seg_labels(rp.cr, rp.d, "wrist", lut)
        sd = look.post(rd_s, "desk")
        sw = look.post(rw_s, "wrist", K=Kw, jaw_mask=(labw == A7.L_JAW))
        if video:
            wd.write(sd)
            ww.write(sw)
        gf, gmv = rp.gaps_now()
        met = {"new_episode_index": i, "source_episode": sep, "frame": k, "place": place, "stage": R.STAGES[lab_st[k]][0],
               "held": int(held[k]), "gripper_state": round(float(states[k, 5]), 3), "gripper_q_deg": round(math.degrees(qg[k]), 3),
               "wrist_roll_deg": round(float(states[k, 4]), 2), "wrist_flex_deg": round(float(states[k, 3]), 2),
               "gap_fixed_mm": gf, "gap_moving_mm": gmv, "block_x_mm": pos[k][0], "block_y_mm": pos[k][1], "block_z_mm": pos[k][2]}
        met.update(R.frame_metrics(rd, sd, "desk"))
        met.update(R.frame_metrics(rw, sw, "wrist"))
        # 形だけの位置 (隠れなし)
        gpose = rp.gripper_pose()
        c8 = pos[k] + (P3.CORNERS * s) @ R.quat_to_mat(quat[k]).T
        hc = wrist_hull(c8, wcam, gpose)
        met["wrist_hull_cx"], met["wrist_hull_cy"] = (float(hc[0]), float(hc[1])) if hc is not None else (float("nan"),) * 2
        met["wrist_hull0_cx"] = met["wrist_hull0_cy"] = met["implied_x_mm"] = met["implied_y_mm"] = float("nan")
        if k < cs:
            rp0.pose_arm(states[k], qg[k])
            h0 = wrist_hull(c8_0, wcam, rp0.gripper_pose())
            if h0 is not None:
                met["wrist_hull0_cx"], met["wrist_hull0_cy"] = float(h0[0]), float(h0[1])
            if met["wrist_red_real_px"] >= 300 and not math.isnan(met["wrist_red_real_cx"]):
                xy = implied_xy(np.array([met["wrist_red_real_cx"], met["wrist_red_real_cy"]]), blk0["xy"], blk0["yaw"], s, wcam, gpose)
                if xy is not None:
                    met["implied_x_mm"], met["implied_y_mm"] = float(xy[0]), float(xy[1])
        frows.append(met)
        for nm, kk in want.items():
            if kk == k:
                for cam, re_, si_ in (("desk", rd, sd), ("wrist", rw, sw)):
                    cv2.imwrite(str(out / "demo" / f"ep{i:02d}_{nm}_{cam}_sim.png"), si_)
                    cv2.imwrite(str(out / "demo" / f"ep{i:02d}_{nm}_{cam}_real.png"), re_)
    if video:
        wd.close()
        ww.close()
    rp.cr.close()
    keys = list(dict.fromkeys(kk for r in frows for kk in r))
    with open(out / f"ep{i:02d}_frames.csv", "w", newline="") as fh:
        w = csv.DictWriter(fh, fieldnames=keys)
        w.writeheader()
        for r in frows:
            w.writerow({kk: (round(v, 4) if isinstance(v, float) else v) for kk, v in r.items()})
    (out / f"ep{i:02d}.json").write_text(json.dumps({
        "time": datetime.now().isoformat(timespec="seconds"), "made_by": "so101/sim/simreplay_359.py (依頼 359)", "level": LEVEL,
        "session": SESSION, "how_block": how, "block_init": blk0, "box": box, "base": base, "place": place, "plan_index": i,
        "source_dataset": DS, "source_episode": sep, "frames": len(frows), "demo_frames": want, "block": binfo,
        "stage_frames": {R.STAGES[q][0]: int((lab_st == q).sum()) for q in range(7)}}, ensure_ascii=False, indent=1, default=str))
    print(datetime.now().strftime("%H:%M:%S"), tag, "ep", i, "frames", len(frows), binfo.get("landed"), flush=True)


def setup():
    su = P3.setup()  # 関節のずれ・手首カメラの付き方・爪の換算 (依頼 342)・カメラ
    sc = json.loads((OUT / "scene_359.json").read_text())
    su["box"] = load_box()
    su["scene"] = sc
    first = {}
    for r in sc["episodes"]:
        first.setdefault(r["place"], r["plan_index"])
    su["demo_eps"] = set(first.values())
    return su


def main():
    ap = argparse.ArgumentParser()
    ap.add_argument("--scene", action="store_true")
    ap.add_argument("--tag", default="")
    ap.add_argument("--place", choices=("plan", "est"), default="plan", help="ブロックの最初の置き方")
    ap.add_argument("--eps", default="all", help="割り振りの番号 (例 0,1). all = 50 本")
    ap.add_argument("--no-video", action="store_true")
    a = ap.parse_args()
    if a.scene:
        scene_mode()
        return
    Q5.patch(A5.load355(), {}, {}, extra=False)  # Look を 依頼 355 のもの (level 8) にする. check_355 には書かない
    P3.OUT = OUT
    su = setup()
    P = A3.load_params()
    tag = a.tag or a.place
    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 / tag).mkdir(parents=True, exist_ok=True)
    (OUT / tag / "args.json").write_text(json.dumps({"level": LEVEL, "session": SESSION, "place": a.place, "box": su["box"], "base": BASE0,
                                                     "params355": str(A5.PARAMS355)}, ensure_ascii=False, indent=1))
    for i in eps:
        run_ep(su, rows[i], a.place, tag, P, video=not a.no_video)


if __name__ == "__main__":
    main()
