"""依頼 445: 描き足しの下ごしらえ (numpy・cv2 だけ).
1. 手首カメラの裏の絵: エイイチが撮った基板の写真 (check_369/photos/arm_IMG_0597.jpg. 裏から見た 黒い基板・金色の縁・4 隅の白いナット・白い差し込み)
   の基板の 4 隅 (写真の画素. 目で読んだ) を 正方形に写し直して tex/board_back_445.png (1024×1024. sRGB のまま) にする.
   絵の右 = 基板の e1・絵の下 = e2 (cable_366.cam_board_frame. 裏から見ると 右 = e1・下 = e2 で 差し込み (e2 の側) が下に来る).
2. 関節のねじ: サーボ (sts3215_03a_v1) のホーン (形の座標で y > 16.3mm・中心 (x 0, z 11.74) から 10.5mm 以内. 直径 20mm の円板) の
   4 つの穴 (中心から (±5, ±5)mm) の上に ねじの頭を置く. ホーンに付く部品 (子) の面の上 (穴の線から 2mm 以内の 子の形の点の いちばん外) に置き,
   子の座標で持つ (関節が回ると 子と一緒に回る). 子と向きは HOME のコマ (check_361/ep03 の 0 コマ) で決めた
   (このコマでは 実機の机側の絵の 爪のホーンの 4 本のねじと 形の穴が同じ所に写る).

使い方: python3 so101/sim/look_445/prep_445.py   → tex/board_back_445.png・prep_445.json
"""
import json
from pathlib import Path

import cv2
import numpy as np

HERE = Path(__file__).resolve().parent
SO101 = HERE.parent.parent
PHOTO = SO101 / "check_369" / "photos" / "arm_IMG_0597.jpg"
CORNERS = [(493, 131), (1087, 91), (1127, 660), (660, 800)]  # 左上・右上・右下・左下 (写真 4032 ではなく 1512×2016 の画素. 格子を重ねて目で読んだ)
HORN_C = np.array([0.0, 19.83, 11.74])  # ホーンの上の面の中心 (形の座標 mm)
HORN_AX = np.array([0.0, 1.0, 0.0])
HOLES = [(5.0, 5.0), (5.0, -5.0), (-5.0, 5.0), (-5.0, -5.0)]  # (x, z − 11.74) mm
CHILD = {"g4": "g10", "g6": "g14", "g12": "g16", "g20": "g24", "g26": "g34"}  # ホーンに付く部品 (HOME のコマで ホーンの軸の 9mm 以内に 形の点が多いもの)


def board_texture(n=1024):
    im = cv2.imread(str(PHOTO))
    H = cv2.getPerspectiveTransform(np.float32(CORNERS), np.float32([(0, 0), (n - 1, 0), (n - 1, n - 1), (0, n - 1)]))
    tex = cv2.warpPerspective(im, H, (n, n), flags=cv2.INTER_AREA, borderMode=cv2.BORDER_REPLICATE)
    (HERE / "tex").mkdir(exist_ok=True)
    cv2.imwrite(str(HERE / "tex" / "board_back_445.png"), tex)
    lin = (tex.astype(np.float32) / 255) ** 2.2
    return {"path": "sim/look_445/tex/board_back_445.png", "photo": str(PHOTO.relative_to(SO101)), "corners_px": CORNERS, "size": n,
            "median_linear_bgr": [round(float(v), 4) for v in np.median(lin.reshape(-1, 3), 0)]}


def screws():
    G = json.loads((SO101 / "check_361" / "scene" / "geoms.json").read_text())
    M = np.load(SO101 / "check_361" / "scene" / "meshes.npz")
    fr = json.loads((SO101 / "check_361" / "ep03" / "poses.json").read_text())["frames"][0]
    T = {k: np.asarray(v, float).reshape(4, 4) for k, v in fr["geoms"].items()}
    mesh = {r["name"]: r["mesh"] for r in G if r["type"] == "mesh"}
    out = []
    for s, ch in CHILD.items():
        Ts, Tc = T[s], T[ch]
        vc = M[mesh[ch] + "_v"].astype(float)  # 子の形 (m. 子の座標)
        wc = vc @ Tc[:3, :3].T + Tc[:3, 3]
        ax = Ts[:3, :3] @ HORN_AX
        for hx, hz in HOLES:
            p = Ts[:3, :3] @ ((HORN_C + [hx, 0, hz]) / 1000) + Ts[:3, 3]  # 穴の上の面 (world)
            d = wc - p
            t = d @ ax
            rad = np.linalg.norm(d - np.outer(t, ax), axis=1)
            m = (rad < 0.002) & (t > -0.001) & (t < 0.015)
            top = float(t[m].max()) if m.any() else 0.0
            q = p + max(top, 0.0) * ax  # 頭の座る所 (world)
            Ti = np.linalg.inv(Tc)
            out.append({"servo": s, "geom": ch, "hole_mm": [hx, hz], "seat_mm": round(max(top, 0.0) * 1000, 2), "child_pts": int(m.sum()),
                        "pos_mm": [round(float(v) * 1000, 3) for v in (Ti[:3, :3] @ q + Ti[:3, 3])],
                        "axis": [round(float(v), 5) for v in (Ti[:3, :3] @ ax)]})
    return out


def main():
    res = {"made_by": "so101/sim/look_445/prep_445.py (依頼 445)", "board_texture": board_texture(), "screws": screws()}
    (HERE / "prep_445.json").write_text(json.dumps(res, ensure_ascii=False, indent=1))
    for s in res["screws"]:
        print(s["servo"], s["geom"], s["hole_mm"], "seat", s["seat_mm"], "pts", s["child_pts"])
    print(res["board_texture"])


if __name__ == "__main__":
    main()
