"""SO-101 のシム (MuJoCo) で, 机側カメラと同じ絵が出るかを確かめる (依頼 326).

1. フォロワーの6つのサーボの Present_Position を1回読んで度に直す (読むだけ).
   robot.connect() は使わない. check_258.open_ro_bus = SerialMotorsBus.connect(handshake=False) で開き,
   sync_read だけ. どの番地にも書かない. 閉じるときも disconnect(disable_torque=False).
   校正は LeRobot の今の場所 (~/.cache/huggingface/lerobot/calibration/robots/so_follower/ptm_follower.json) から読むだけ.
2. 読んだ直後に机側カメラで1枚 (依頼 324 と同じ: 机側だけ apply_and_verify(keys=("desk",)), 640×480・MJPG, 30コマ捨てる) → real.png
3. MuJoCo: TheRobotStudio/SO-ARM100 Simulation/SO101/so101_new_calib.xml.
   関節: LeRobot の度をそのまま rad にして入れる (向きはそのまま). wrist_roll だけ -90° (依頼 299 の so101_fk.ZERO_OFFSET_DEG と同じ).
   爪: LeRobot の 0〜100 を MJCF の gripper の下限〜上限に線形で写す.
4. シーン (アームの座標 = 台座の回る軸の机の面の高さが原点, +x 前, +y 左, +z 上. mm):
   机の面 z=0, A3 の紙と 10×7 マス・38mm のチェッカー模様 (A = arm_frame_v2.json の (213, -100, 0), x・y はアームと同じ向き).
   MJCF の base は回る軸が base の (38.8, 0) mm, 台座の底が base の z=-2.4mm. アームの座標 p → base の座標 p + (38.8, 0, -2.4).
5. カメラ: 位置 = A + desk_pose.json の pose_all_frames_together.cam_pos_mm, 向き = R_cam_in_board (ボードの軸 = アームの軸).
   歪みのない大きめの絵をピンホール (正方の画素・主点は真ん中) で描き, camera_desk.json の K と歪み5つで
   640×480 の各画素がどこを見るかを undistortPointsIter で出して remap する → sim.png (主点のずれ・fx≠fy・歪みを含む).
6. real.png と sim.png を重ねる (overlay.png・side_by_side.png・outline.png). ボードの内側の角 54 点を両方で見つけ,
   同じ角どうしの差 (px) を出す → result.json.

KIOXIA は読むだけ. カメラの固定の値は変えない (-r は使わない).

使い方 (conda の lerobot 環境で):
    python so101/check_326/check_326_sim_view.py              # 読む・撮る・描く・比べる
    python so101/check_326/check_326_sim_view.py --from-saved # 読まず撮らず, joints.json と real.png から描き直す
    python so101/check_326/check_326_sim_view.py --out so101/check_326/pose1  # 出力の置き場所を変える (依頼 327)

依頼 327 から: 肩の回転は読んだまま (+) と符号を逆にした (-) の両方を描く (- は *_pan_neg.png).
outline の輪郭は部分ごとに色を分ける (PARTS).
"""

import argparse
import json
import math
import sys
import time
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(SO101))
sys.path.insert(0, str(SO101 / "check_324"))

KIOXIA_CAM = Path("/Volumes/KIOXIA/r2r2r-data/so101_calibration/2026-11-27/cameras")
CAMERA_JSON = KIOXIA_CAM / "camera_desk.json"
POSE_JSON = KIOXIA_CAM / "desk_pose.json"
ARM_FRAME_JSON = KIOXIA_CAM / "arm_frame_v2.json"  # arm_frame.json (v1) は左右を間違えているので使わない
MODEL_DIR = Path.home() / ".cache/so101_model/SO-ARM100/Simulation/SO101"  # commit 141aea7 (依頼 297 と同じ版)
MJCF = MODEL_DIR / "so101_new_calib.xml"

MOTORS = ["shoulder_pan", "shoulder_lift", "elbow_flex", "wrist_flex", "wrist_roll", "gripper"]
ZERO_OFFSET_DEG = {"wrist_roll": -90.0}  # 依頼 299 (Unity SO101Arm.ZeroOffsetDeg・so101_fk.ZERO_OFFSET_DEG と同じ)
AXIS_IN_BASE_MM = np.array([38.8353, 0.0, 0.0])  # shoulder の body の位置 (回る軸) を base で
BASE_BOTTOM_IN_BASE_MM = -2.4  # base の形の一番下 (台座の底 = 机の面)
PATTERN = (9, 6)
SQUARE_MM = 38.0
SQUARES = (7, 10)  # ボードの x (短い辺) に 7 マス, y (長い辺) に 10 マス
PAPER_MM = (297.0, 420.0)  # A3 (x, y)
PAPER_MARGIN_X_MM = 7.5  # 紙のアーム側の余白 (arm_frame_v2.json の note)
W, H = 640, 480
DISCARD = 30
# outline の部分ごとの色 (BGR). 名前は MJCF の body
PARTS = {"base": ("台座", (0, 255, 255)), "shoulder": ("肩", (0, 165, 255)), "upper_arm": ("上の腕", (0, 255, 0)),
         "lower_arm": ("ひじから先", (255, 255, 0)), "wrist": ("手首", (255, 0, 255)),
         "gripper": ("爪 (固定側)", (0, 0, 255)), "moving_jaw_so101_v1": ("爪 (動く側)", (255, 0, 0))}


# ---- 1・2 読む・撮る ---------------------------------------------------------------------

def read_joints():
    from check_258 import CAL_FOLLOWER, FOLLOWER_PORT, close_ro, open_ro_bus
    cal = json.loads(CAL_FOLLOWER.read_text())
    bus = open_ro_bus(FOLLOWER_PORT, CAL_FOLLOWER)  # handshake なし・書き込みなし
    try:
        t = datetime.now().isoformat(timespec="milliseconds")
        raw = bus.sync_read("Present_Position", normalize=False, num_retry=2)
        norm = bus.sync_read("Present_Position", num_retry=2)
        homing = bus.sync_read("Homing_Offset", normalize=False, num_retry=2)
        torque = bus.sync_read("Torque_Enable", normalize=False, num_retry=2)
    finally:
        close_ro(bus)
    return {
        "time": t, "port": FOLLOWER_PORT, "calibration_file": str(CAL_FOLLOWER),
        "how": "check_258.open_ro_bus (SerialMotorsBus.connect(handshake=False)) で sync_read だけ. 書き込みなし",
        "units": "関節1〜5 は度 (LeRobot の DEGREES: (raw - (range_min+range_max)/2) × 360/4095), 爪は 0〜100",
        "deg": {m: round(float(norm[m]), 3) for m in MOTORS},
        "raw": {m: int(raw[m]) for m in MOTORS},
        "torque_enable_read": {m: int(torque[m]) for m in MOTORS},
        "homing_offset_servo_vs_file": {m: [int(homing[m]), cal[m]["homing_offset"]] for m in MOTORS},
        "homing_match": all(int(homing[m]) == cal[m]["homing_offset"] for m in MOTORS),
    }


def capture_one():
    from camera_lock_259 import apply_and_verify, open_cap, opencv_index
    applied = apply_and_verify(keys=("desk",))
    cap = open_cap(opencv_index("desk"))
    try:
        time.sleep(0.5)
        for _ in range(DISCARD):
            cap.read()
        ok, f = cap.read()
        info = {"time": datetime.now().isoformat(timespec="milliseconds"),
                "width": int(cap.get(cv2.CAP_PROP_FRAME_WIDTH)), "height": int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT)),
                "fps": cap.get(cv2.CAP_PROP_FPS), "discard": DISCARD, "lock_applied": applied}
    finally:
        cap.release()
    if not ok or f is None:
        raise RuntimeError("机側カメラから1枚撮れない")
    return f, info


# ---- 3〜5 シム ---------------------------------------------------------------------------

def to_base(p_mm):
    """アームの座標 (mm) → MJCF の base の座標 (m)."""
    return (np.asarray(p_mm, float) + AXIS_IN_BASE_MM + [0, 0, BASE_BOTTOM_IN_BASE_MM]) / 1000.0


def board_geoms(A):
    """紙と 10×7 マスのチェッカー模様 (黒いマスだけ紙の上に置く)."""
    out = []
    z_paper, z_sq = 0.0003, 0.0006
    pat_x0 = A[0] - SQUARE_MM  # 模様の手前の線
    paper_x0 = pat_x0 - PAPER_MARGIN_X_MM
    pat_yc = A[1] - SQUARE_MM + SQUARES[1] * SQUARE_MM / 2
    pc = to_base([paper_x0 + PAPER_MM[0] / 2, pat_yc, z_paper * 1000])
    out.append(f'<geom type="box" pos="{pc[0]:.6f} {pc[1]:.6f} {pc[2]:.6f}" '
               f'size="{PAPER_MM[0] / 2000:.6f} {PAPER_MM[1] / 2000:.6f} 0.0003" rgba="0.97 0.97 0.97 1"/>')
    for i in range(SQUARES[0]):
        for j in range(SQUARES[1]):
            if (i + j) % 2:
                continue  # A の外側の対角のマス (i=0, j=0) が黒
            c = to_base([A[0] - SQUARE_MM + (i + 0.5) * SQUARE_MM, A[1] - SQUARE_MM + (j + 0.5) * SQUARE_MM,
                         z_sq * 1000])
            out.append(f'<geom type="box" pos="{c[0]:.6f} {c[1]:.6f} {c[2]:.6f}" '
                       f'size="{SQUARE_MM / 2000:.6f} {SQUARE_MM / 2000:.6f} 0.0003" rgba="0.05 0.05 0.05 1"/>')
    return out


def render_size(K, D):
    """640×480 の各画素の見る向き (歪みを外した正規化座標) と, それが入る大きめのピンホールの絵の大きさ."""
    u, v = np.meshgrid(np.arange(W, dtype=np.float64), np.arange(H, dtype=np.float64))
    pts = np.stack([u.ravel(), v.ravel()], 1).reshape(-1, 1, 2)
    crit = (cv2.TERM_CRITERIA_COUNT | cv2.TERM_CRITERIA_EPS, 100, 1e-10)
    n = cv2.undistortPointsIter(pts, K, D, None, None, crit).reshape(-1, 2)
    back, _ = cv2.projectPoints(np.c_[n, np.ones(len(n))], np.zeros(3), np.zeros(3), K, D)
    rt = np.linalg.norm(back.reshape(-1, 2) - pts.reshape(-1, 2), axis=1)
    good = rt < 0.5
    f = float(K[1, 1])
    half_w = int(math.ceil(f * np.abs(n[good, 0]).max())) + 4
    half_h = int(math.ceil(f * np.abs(n[good, 1]).max())) + 4
    return n.reshape(H, W, 2), good.reshape(H, W), f, 2 * half_w, 2 * half_h, float(rt[good].max())


def build_xml(cam_pos_arm, R_cam_arm, A, fovy, rw, rh):
    Rmj = R_cam_arm @ np.diag([1.0, -1.0, -1.0])  # OpenCV (x 右・y 下・z 前) → MuJoCo (x 右・y 上・-z 前)
    cp = to_base(cam_pos_arm)
    xy = " ".join(f"{v:.9f}" for v in np.r_[Rmj[:, 0], Rmj[:, 1]])
    tc = to_base([300, 0, -10])
    return f"""<mujoco model="check_326">
  <include file="{MJCF.name}"/>
  <visual>
    <global offwidth="{rw}" offheight="{rh}"/>
    <quality shadowsize="4096"/>
    <headlight diffuse="0.55 0.55 0.55" ambient="0.35 0.35 0.35" specular="0 0 0"/>
  </visual>
  <worldbody>
    <light pos="{to_base([200, 0, 1500])[0]:.4f} 0 1.5" dir="0 0 -1" directional="true" castshadow="false" diffuse="0.5 0.5 0.5"/>
    <geom name="table" type="box" pos="{tc[0]:.6f} {tc[1]:.6f} {tc[2]:.6f}" size="1.0 1.0 0.01" rgba="0.86 0.85 0.82 1"/>
    {chr(10).join('    ' + g for g in board_geoms(A))}
    <camera name="desk" pos="{cp[0]:.6f} {cp[1]:.6f} {cp[2]:.6f}" xyaxes="{xy}" fovy="{math.degrees(fovy):.9f}"/>
  </worldbody>
</mujoco>"""


def set_joints(m, d, deg):
    import mujoco
    for name in MOTORS[:5]:
        d.qpos[m.joint(name).qposadr[0]] = math.radians(deg[name] + ZERO_OFFSET_DEG.get(name, 0.0))
    jg = m.joint("gripper")
    lo, hi = jg.range
    d.qpos[jg.qposadr[0]] = lo + (hi - lo) * float(deg["gripper"]) / 100.0
    mujoco.mj_forward(m, d)


def render_sim(deg, K, D, cam_pos_arm, R_cam_arm, A, out=HERE):
    import mujoco
    n, good, f, rw, rh, rt = render_size(K, D)
    fovy = 2 * math.atan(rh / 2 / f)
    xml = build_xml(cam_pos_arm, R_cam_arm, A, fovy, rw, rh)
    (out / "scene_326.xml").write_text(xml)
    scene = MODEL_DIR / "scene_check_326.xml"  # MJCF の meshdir (assets) がこの置き場所から引かれるため, 同じ所に置いて読む
    scene.write_text(xml)
    m = mujoco.MjModel.from_xml_path(str(scene))
    d = mujoco.MjData(m)
    set_joints(m, d, deg)
    r = mujoco.Renderer(m, height=rh, width=rw)
    r.update_scene(d, camera="desk")
    pin = r.render()[:, :, ::-1].copy()  # RGB → BGR (Renderer は上の行から返す)
    r.enable_segmentation_rendering()
    r.update_scene(d, camera="desk")
    seg = r.render()
    r.close()
    arm_geoms = {g for g in range(m.ngeom) if m.geom_bodyid[g] != 0}
    is_geom = seg[:, :, 1] == int(mujoco.mjtObj.mjOBJ_GEOM)
    arm = np.isin(seg[:, :, 0], list(arm_geoms)) & is_geom
    part_pin = np.zeros(arm.shape, np.uint8)  # 0 = アームでない, k+1 = PARTS の k 番目の body
    for k, b in enumerate(PARTS):
        gs = [g for g in range(m.ngeom) if m.geom_bodyid[g] == m.body(b).id]
        part_pin[np.isin(seg[:, :, 0], gs) & is_geom] = k + 1
    # ピンホールの絵の主点は真ん中 ((rw-1)/2, (rh-1)/2), 焦点 f (正方の画素)
    mx = (f * n[..., 0] + (rw - 1) / 2).astype(np.float32)
    my = (f * n[..., 1] + (rh - 1) / 2).astype(np.float32)
    sim = cv2.remap(pin, mx, my, cv2.INTER_LINEAR, borderValue=(0, 0, 0))
    arm_mask = cv2.remap(arm.astype(np.uint8) * 255, mx, my, cv2.INTER_NEAREST)
    part = cv2.remap(part_pin, mx, my, cv2.INTER_NEAREST)
    sim[~good] = 0
    arm_mask[~good] = 0
    part[~good] = 0
    tips = {}
    for b in ["gripper", "moving_jaw_so101_v1", "wrist", "lower_arm", "upper_arm", "shoulder"]:
        p_arm = d.xpos[m.body(b).id] * 1000 - AXIS_IN_BASE_MM - [0, 0, BASE_BOTTOM_IN_BASE_MM]
        tips[b] = [round(float(v), 1) for v in p_arm]
    info = {"pinhole_size": [rw, rh], "pinhole_f_px": f, "fovy_deg": math.degrees(fovy),
            "undistort_roundtrip_max_px": rt, "pixels_outside_model": int((~good).sum()),
            "body_pos_arm_frame_mm": tips, "arm_pixels_in_view": int((arm_mask > 0).sum())}
    ys, xs = np.nonzero(arm_mask)
    if len(xs):
        info["arm_bbox_px"] = [int(xs.min()), int(ys.min()), int(xs.max()), int(ys.max())]
    info["part_bbox_px"] = {}
    for k, b in enumerate(PARTS):
        ys, xs = np.nonzero(part == k + 1)
        if len(xs):
            info["part_bbox_px"][b] = [int(xs.min()), int(ys.min()), int(xs.max()), int(ys.max()), int(len(xs))]
    return sim, arm_mask, part, info


def draw_parts(img, part):
    """部分ごとの外の輪郭を PARTS の色で描く."""
    out = img.copy()
    for k, (_, (_, col)) in enumerate(PARTS.items()):
        cnts, _ = cv2.findContours((part == k + 1).astype(np.uint8), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE)
        cv2.drawContours(out, cnts, -1, col, 1)
    return out


# ---- 6 比べる ----------------------------------------------------------------------------

def board_corners_px(img, ref_px=None):
    from check_324_pose import choose_origin, find_corners, grid_for_origin, origin_nearest
    gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
    pts, method = find_corners(gray)
    if pts is None or len(pts) != PATTERN[0] * PATTERN[1]:
        return None, None, method
    if ref_px is None:
        ch, _ = choose_origin(gray, pts)
        r0, c0 = ch["r0"], ch["c0"]
    else:
        r0, c0 = origin_nearest(pts, ref_px)
    g, obj = grid_for_origin(pts, r0, c0, swap=True)  # 依頼 324 と同じ: x = 短い辺
    return g, obj, method


def main():
    ap = argparse.ArgumentParser()
    ap.add_argument("--from-saved", action="store_true", help="サーボを読まずカメラで撮らず, joints.json と real.png から描き直す")
    ap.add_argument("--out", type=Path, default=HERE, help="出力の置き場所 (既定: このファイルの場所)")
    args = ap.parse_args()
    out = args.out.resolve()
    out.mkdir(parents=True, exist_ok=True)

    camj = json.loads(CAMERA_JSON.read_text())
    pose = json.loads(POSE_JSON.read_text())["pose_all_frames_together"]
    armf = json.loads(ARM_FRAME_JSON.read_text())
    K = np.array(camj["camera_matrix"], float)
    D = np.array(camj["dist_coeffs"], float)
    A = np.array(armf["derived_mm"]["origin_A_in_arm_frame"], float)
    R_cam_arm = np.array(pose["R_cam_in_board"], float)  # ボードの x・y = アームの x・y とみなす
    cam_pos_arm = A + np.array(pose["cam_pos_mm"], float)

    if args.from_saved:
        joints = json.loads((out / "joints.json").read_text())
        real = cv2.imread(str(out / "real.png"))
        cap_info = json.loads((out / "result.json").read_text()).get("capture") if (out / "result.json").exists() else None
    else:
        joints = read_joints()
        (out / "joints.json").write_text(json.dumps(joints, ensure_ascii=False, indent=2))
        print("読んだ角度:", joints["deg"])
        real, cap_info = capture_one()
        cv2.imwrite(str(out / "real.png"), real)

    gap = np.full((H, 8, 3), 255, np.uint8)
    pan_neg = {}
    for tag, sign in (("", 1.0), ("_pan_neg", -1.0)):
        deg = dict(joints["deg"], shoulder_pan=sign * joints["deg"]["shoulder_pan"])
        s_img, s_mask, s_part, s_info = render_sim(deg, K, D, cam_pos_arm, R_cam_arm, A, out)
        cv2.imwrite(str(out / f"sim{tag}.png"), s_img)
        cv2.imwrite(str(out / f"overlay{tag}.png"), cv2.addWeighted(real, 0.5, s_img, 0.5, 0))
        cv2.imwrite(str(out / f"side_by_side{tag}.png"), np.hstack([real, gap, s_img]))
        if sign > 0:
            sim, arm_mask, part, sim_info = s_img, s_mask, s_part, s_info
        else:
            cv2.imwrite(str(out / f"outline{tag}.png"), draw_parts(real, s_part))
            pan_neg = {"shoulder_pan_deg": deg["shoulder_pan"], "sim": s_info}

    outline = draw_parts(real, part)

    # ボードの角: 実機で原点 A を選び, シムは A の画素に近い角を原点にして同じ並びにする
    g_real, obj, m_real = board_corners_px(real)
    corners = {"real_method": m_real}
    if g_real is not None:
        g_sim, _, m_sim = board_corners_px(sim, ref_px=g_real[0])
        corners["sim_method"] = m_sim
        # 描いた絵とは別に, 同じ姿勢・K・歪みで角を計算で写した位置 (シムの描き方の確かめ)
        Rbc = R_cam_arm.T
        tvec = -Rbc @ cam_pos_arm
        obj_arm = obj + [A[0], A[1], 0]
        proj, _ = cv2.projectPoints(obj_arm, cv2.Rodrigues(Rbc)[0], tvec, K, D)
        proj = proj.reshape(-1, 2)
        dpr = np.linalg.norm(proj - g_real, axis=1)
        corners["real_vs_projected_px"] = {"mean": float(dpr.mean()), "max": float(dpr.max())}
        if g_sim is not None:
            dv = g_sim - g_real
            dd = np.linalg.norm(dv, axis=1)
            dps = np.linalg.norm(proj - g_sim, axis=1)
            corners.update({
                "n": int(len(dd)), "real_vs_sim_px": {"mean": float(dd.mean()), "max": float(dd.max()),
                                                      "mean_dx": float(dv[:, 0].mean()), "mean_dy": float(dv[:, 1].mean())},
                "sim_vs_projected_px": {"mean": float(dps.mean()), "max": float(dps.max())},
                "A_px": {"real": g_real[0].tolist(), "sim": g_sim[0].tolist()},
            })
            for p, q in zip(g_real, g_sim):
                cv2.circle(outline, tuple(int(round(v)) for v in p), 3, (0, 0, 255), 1)
                cv2.drawMarker(outline, tuple(int(round(v)) for v in q), (255, 0, 0), cv2.MARKER_CROSS, 6, 1)
    cv2.imwrite(str(out / "outline.png"), outline)

    result = {
        "time": datetime.now().isoformat(timespec="seconds"),
        "made_by": "so101/check_326/check_326_sim_view.py (依頼 326)",
        "inputs": {"camera": str(CAMERA_JSON), "pose": str(POSE_JSON) + " pose_all_frames_together",
                   "arm_frame": str(ARM_FRAME_JSON), "model": str(MJCF) + " (SO-ARM100 commit 141aea7)"},
        "joints_deg": joints["deg"], "zero_offset_deg": ZERO_OFFSET_DEG,
        "A_arm_mm": A.tolist(), "camera_pos_arm_mm": cam_pos_arm.tolist(), "R_cam_in_arm": R_cam_arm.tolist(),
        "capture": cap_info, "sim": sim_info, "sim_pan_neg": pan_neg, "board_corners": corners,
        "parts_color_bgr": {b: [name, list(col)] for b, (name, col) in PARTS.items()},
        "images": ["real.png", "sim.png", "overlay.png", "side_by_side.png",
                   "outline.png (実機に シムのアームの部分ごとの輪郭 = parts_color_bgr, 実機の角 = 赤丸, シムの角 = 青の十字)",
                   "sim_pan_neg.png・overlay_pan_neg.png・side_by_side_pan_neg.png・outline_pan_neg.png (肩の回転の符号を逆にした絵)"],
    }
    (out / "result.json").write_text(json.dumps(result, ensure_ascii=False, indent=2))
    print(json.dumps({"joints_deg": joints["deg"], "board_corners": corners,
                      "body_pos_arm_frame_mm": sim_info["body_pos_arm_frame_mm"]}, ensure_ascii=False, indent=2))


if __name__ == "__main__":
    main()
