"""依頼 335 の確かめ (参考. v2 には使わない): つかんでいる間の実機の手首の絵 (爪の値 9.5〜13.5 のコマの中央値. fit_wrist_grip_335 --cache)
の赤いブロックに, シムのブロック (爪の面に平行・幅 21.7mm・閉じる向きは両方の爪に接する所) を 爪の長さの向き (gripper の z) と
直角の向き (gripper の y) だけ動かして合わせ, v2 の置き方 (依頼 333 の along・机の上の高さ) との差を出す.
カメラの付き方は wrist_grip_335.json の after. 手首カメラと爪は同じ部品なので, 腕の角度のずれに よらない.
読むだけ. 出力: check_335/hold_offset_335.json・hold_offset_335.png

使い方 (conda の lerobot 環境で. simreplay_335.py --run のあと):
    python so101/sim/hold_offset_335.py
"""

import json
import sys
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_335 as G  # noqa: E402
import fit_wrist_grip_335 as F  # noqa: E402
import simreplay_334 as R  # noqa: E402
from measure_scene_330 import hull_mask, iou, nelder_mead, red_mask  # noqa: E402


def main():
    C = dict(np.load(F.CACHE))
    fit = G.load_fit()
    cams = S.load_cameras()
    cam = G.wrist_cam(fit["wrist_cam"]["after"], cams["wrist"]["K"], cams["wrist"]["D"])
    ep = json.loads((G.OUT / "episodes_335.json").read_text())["episodes"]
    pg = np.array([e["block"]["grasp_center_in_gripper_mm"] for e in ep if "grasp_center_in_gripper_mm" in e["block"]])
    p_v2 = np.median(pg, 0)
    s = G.BLOCK_MM
    corners = np.array([[sx, sy, sz] for sx in (-1, 1) for sy in (-1, 1) for sz in (-1, 1)]) * s / 2

    def hull(c):
        px, ok = G.project_wrist(corners + c, cam)
        return hull_mask(px, (S.H, S.W)) if ok.all() else np.zeros((S.H, S.W), bool)

    out = {"made_by": "so101/sim/hold_offset_335.py (依頼 335. 参考)", "v2_grasp_center_in_gripper_mm_median": p_v2.round(2).tolist(),
           "v2_grasp_center_in_gripper_mm_range": [pg.min(0).round(1).tolist(), pg.max(0).round(1).tolist()],
           "axes": "gripper の body の座標: x = 閉じる向き (固定側の爪 -x), z = 爪の付け根の向き (爪の先は z ≈ -98), y = 直角"}
    vis = []
    for tag in ("fit", "chk"):
        im = C[f"med_{tag}_{F.HOLD_BIN}"]
        rm = red_mask(im)
        ys, xs = np.nonzero(rm)
        cen = np.array([xs.mean(), ys.mean()])

        def cost(p):
            return 1 - iou(hull(np.array([p_v2[0], p[0], p[1]])), rm)
        best = min((nelder_mead(cost, [p_v2[1] + dy, p_v2[2] + dz], [3, 3], iters=200, tol=1e-6)
                    for dy in (0, -8, 8) for dz in (0, -10, -20)), key=lambda r: r[1])
        p = np.array([p_v2[0], best[0][0], best[0][1]])
        h0, h1 = hull(p_v2), hull(p)

        def cdist(h):
            yy, xx = np.nonzero(h)
            return round(float(np.hypot(xx.mean() - cen[0], yy.mean() - cen[1])), 1) if len(yy) else None
        out[tag] = {"fit_center_in_gripper_mm": p.round(2).tolist(), "shift_from_v2_mm_y_z": (p - p_v2)[1:].round(2).tolist(),
                    "iou_v2": round(iou(h0, rm), 3), "iou_fit": round(iou(h1, rm), 3),
                    "centroid_px_v2": cdist(h0), "centroid_px_fit": cdist(h1),
                    "block_beyond_jaw_tip_mm": round(float(-98.1 - (p[2] - s / 2)), 1)}
        v = im.copy()
        for h, col in ((rm, (0, 255, 255)), (h0, (255, 0, 0)), (h1, (0, 200, 0))):
            cn, _ = cv2.findContours(h.astype(np.uint8), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE)
            cv2.drawContours(v, cn, -1, col, 2)
        cv2.putText(v, f"{tag}: yellow=real blue=v2 green=fit", (8, 26), cv2.FONT_HERSHEY_SIMPLEX, 0.7, (0, 0, 255), 2)
        vis.append(cv2.resize(v, (480, 360)))
    (G.OUT / "hold_offset_335.json").write_text(json.dumps(out, ensure_ascii=False, indent=1))
    cv2.imwrite(str(G.OUT / "hold_offset_335.png"), np.hstack(vis))
    print(json.dumps(out, ensure_ascii=False, indent=1))


if __name__ == "__main__":
    main()
