"""依頼 366: 絵.
- 段階ごとの並べ (figs_364 と同じ形・同じコマ (check_361/figs/frames.json)). 左から 実機・依頼 364 (光)・依頼 366 (S123). 行 = 3 本 × (机側・手首)
  → check_366/figs/stage_<段階>.png
- 腕の寄り (机側. 腕のまわりを切って 2 倍): 左から 実機・364・S0・S1・S12・S123 → figs/arm_<本>.png (段階ごとのコマ)
- ケーブルの重なり (机側): 実機のケーブルの画素 (緑)・シムのケーブル (赤紫)・重なり (白) を 実機の絵に → figs/cable_<本>.png

使い方 (conda の lerobot 環境で): python so101/blender/figs_366.py [--light FA]
"""

import argparse
import json
import sys
from pathlib import Path

import cv2
import numpy as np

HERE = Path(__file__).resolve().parent
SO101 = HERE.parent
sys.path.insert(0, str(HERE))
import post_361 as P1  # noqa: E402
import post_366 as M  # noqa: E402
import fit_cable_366 as FC  # noqa: E402

OUT = SO101 / "check_366"
C361, C364 = SO101 / "check_361", SO101 / "check_364"


def put(img, s):
    cv2.putText(img, s, (6, 20), cv2.FONT_HERSHEY_SIMPLEX, 0.55, (0, 0, 0), 3, cv2.LINE_AA)
    cv2.putText(img, s, (6, 20), cv2.FONT_HERSHEY_SIMPLEX, 0.55, (255, 255, 255), 1, cv2.LINE_AA)
    return img


def main():
    ap = argparse.ArgumentParser()
    ap.add_argument("--light", default="FA")
    a = ap.parse_args()
    L = a.light
    sfx = "" if L == "FA" else f"_{L}"
    (OUT / "figs").mkdir(parents=True, exist_ok=True)
    picked = json.loads((C361 / "figs" / "frames.json").read_text())
    d364 = lambda ep: C364 / ep / f"blf_{L}_s32"  # noqa: E731
    dv = lambda v: (lambda ep: OUT / ep / f"blf_{v}{sfx}_s32")  # noqa: E731
    cols = [("real", lambda ep: C361 / ep / "real"), (f"364 {L}", d364), ("366 S123", dv("S123"))]
    for st, eps in picked.items():
        rows = []
        for ep, k in eps.items():
            for cam in ("desk", "wrist"):
                tiles = []
                for nm, d in cols:
                    im = cv2.resize(cv2.imread(str(d(ep) / f"{k:03d}_{cam}.png")), (320, 240), interpolation=cv2.INTER_AREA)
                    tiles.append(put(im, f"{nm}  {ep} f{k} {cam}"))
                rows.append(np.hstack(tiles))
        cv2.imwrite(str(OUT / "figs" / f"stage_{st}{sfx}.png"), np.vstack(rows))
    # 腕の寄り・ケーブルの重なり
    po = P1.Post()
    cols6 = [("real", lambda ep: C361 / ep / "real"), (f"364 {L}", d364)] + [(v, dv(v)) for v in ("S0", "S1", "S12", "S123")]
    for ep in ("ep00", "ep05", "ep03"):
        rows, crows = [], []
        for st, eps in picked.items():
            k = eps[ep]
            lab, part = M.lab366(po, ep, k, "desk")
            arm = np.isin(lab, M.ARM) | (lab == 10)
            ys, xs = np.nonzero(arm)
            cx, cy = int(np.median(xs)), int(np.median(ys))
            x0, y0 = int(np.clip(cx - 110, 0, 640 - 220)), int(np.clip(cy - 90, 0, 480 - 180))
            tiles = []
            for nm, d in cols6:
                im = cv2.imread(str(d(ep) / f"{k:03d}_desk.png"))[y0:y0 + 180, x0:x0 + 220]
                tiles.append(put(cv2.resize(im, None, fx=2, fy=2, interpolation=cv2.INTER_CUBIC), f"{nm} f{k}"))
            rows.append(np.hstack(tiles))
            real = cv2.imread(str(C361 / ep / "real" / f"{k:03d}_desk.png"))
            rc = FC.real_cable_mask(real, cv2.imread(str(C361 / ep / "lab" / f"{k:03d}_desk.png"), 0))
            sc = (part == M.P_CABLE) & (lab == 10)
            o = (real * 0.6).astype(np.uint8)
            o[rc] = (0, 220, 0)
            o[sc] = (220, 0, 220)
            o[rc & sc] = (255, 255, 255)
            crows.append(put(o, f"{ep} f{k} green=real cable, magenta=sim, white=both"))
        cv2.imwrite(str(OUT / "figs" / f"arm_{ep}{sfx}.png"), np.vstack(rows))
        cv2.imwrite(str(OUT / "figs" / f"cable_{ep}{sfx}.png"), np.vstack([np.hstack(crows[:2]), np.hstack(crows[2:4])]))
    (OUT / "figs" / "frames.json").write_text(json.dumps(picked, indent=1))


if __name__ == "__main__":
    main()
