#!/usr/bin/env python3
"""生成 RV1106 板端测试输入数据 (宿主机执行: macOS / WSL2, 依赖 ffmpeg + numpy + PIL)

产出 (testdata/ 目录):
  det_in_NNN.bin    hand_detector 输入: 192x192x3 uint8 RGB (letterbox 灰边 114)
  lm_in_NNN.bin     hand_landmarks 输入: 224x224x3 uint8 RGB (整帧缩放, ROI 精确裁剪版后续提供)
  stgcn2d_in.bin    ST-GCN 2D 输入: (32,42,3) float32 NHWC
  stgcn3d_in.bin    ST-GCN 3D 输入: (32,42,4) float32 NHWC
  README.txt        各文件说明

用法:
  python3 tools/gen_test_data.py [视频] [--frames N] [--fps F]
默认: HandWash_001_A_01_G01.mp4, 10 FPS 抽 12 帧
"""
import argparse
import subprocess
import sys
import tempfile
from pathlib import Path

import numpy as np
from PIL import Image

ROOT = Path(__file__).resolve().parent.parent
TESTDATA = ROOT / "testdata"


def ffmpeg_extract(video: Path, fps: int, frames: int, out_dir: Path) -> list:
    """按 fps 抽帧存 PNG, 返回文件列表"""
    pattern = str(out_dir / "frame_%03d.png")
    cmd = [
        "ffmpeg", "-y", "-v", "error",
        "-i", str(video),
        "-vf", f"fps={fps}",
        "-frames:v", str(frames),
        pattern,
    ]
    subprocess.run(cmd, check=True)
    return sorted(out_dir.glob("frame_*.png"))


def letterbox(img: Image.Image, size: int = 192,
              pad_color=(0, 0, 0)) -> Image.Image:
    """保持长宽比缩放 + 居中填充到 size×size

    填充色用黑(与 MediaPipe ImageToTensorCalculator BORDER_ZERO 一致;
    手掌检测模型训练/推理均如此, 灰边会导致边缘响应偏差)。
    """
    w, h = img.size
    scale = min(size / w, size / h)
    nw, nh = round(w * scale), round(h * scale)
    img_r = img.resize((nw, nh), Image.BILINEAR)
    canvas = Image.new("RGB", (size, size), pad_color)
    canvas.paste(img_r, ((size - nw) // 2, (size - nh) // 2))
    return canvas


def write_bin(path: Path, arr: np.ndarray):
    arr.tofile(path)
    print(f"  {path.name}: {arr.shape} {arr.dtype} {path.stat().st_size} bytes")


def main():
    ap = argparse.ArgumentParser()
    ap.add_argument("video", nargs="?", default=str(ROOT / "HandWash_001_A_01_G01.mp4"))
    ap.add_argument("--frames", type=int, default=12, help="抽帧数 (默认 12)")
    ap.add_argument("--fps", type=int, default=10, help="抽帧帧率 (默认 10, 与 ST-GCN 采样一致)")
    args = ap.parse_args()

    TESTDATA.mkdir(exist_ok=True)
    with tempfile.TemporaryDirectory() as td:
        frames = ffmpeg_extract(Path(args.video), args.fps, args.frames, Path(td))
        if not frames:
            print("没有抽到帧", file=sys.stderr)
            return 1
        print(f"抽帧 {len(frames)} 张")

        for i, fp in enumerate(frames):
            img = Image.open(fp).convert("RGB")

            det = letterbox(img, 192)
            write_bin(TESTDATA / f"det_in_{i:03d}.bin", np.asarray(det, dtype=np.uint8))

            lm = img.resize((224, 224), Image.BILINEAR)
            write_bin(TESTDATA / f"lm_in_{i:03d}.bin", np.asarray(lm, dtype=np.uint8))

    # ---- ST-GCN 合成窗口 (无真实骨架数据前的通路测试输入) ----
    # 2D: (T=32, V=42, C=3) x,y,visible; 模拟一只手(槽0)缓慢移动, 槽1 不可见
    T, V = 32, 42
    win2d = np.zeros((T, V, 3), dtype=np.float32)
    for t in range(T):
        cx, cy = 0.3 + 0.01 * t, 0.5 + 0.005 * t
        for v in range(21):  # 槽 0: 21 点围绕中心散开
            win2d[t, v, 0] = cx + 0.02 * (v % 7)
            win2d[t, v, 1] = cy + 0.02 * (v // 7)
            win2d[t, v, 2] = 1.0
    write_bin(TESTDATA / "stgcn2d_in.bin", win2d)

    # 3D: (T=32, V=42, C=4) world x,y,z,visible
    win3d = np.zeros((T, V, 4), dtype=np.float32)
    for t in range(T):
        for v in range(21):
            win3d[t, v, 0] = 0.01 * (v % 7) + 0.001 * t
            win3d[t, v, 1] = 0.01 * (v // 7)
            win3d[t, v, 2] = 0.05 * np.sin(0.2 * t + v * 0.1)
            win3d[t, v, 3] = 1.0
    write_bin(TESTDATA / "stgcn3d_in.bin", win3d)

    readme = TESTDATA / "README.txt"
    readme.write_text(
        "RV1106 板端测试输入数据\n"
        "  det_in_NNN.bin : hand_detector 输入 192x192x3 uint8 RGB (letterbox 黑边, 对齐 MediaPipe BORDER_ZERO)\n"
        "  lm_in_NNN.bin  : hand_landmarks 输入 224x224x3 uint8 RGB (整帧缩放; 精确 ROI 裁剪版后续替换)\n"
        "  stgcn2d_in.bin : ST-GCN 2D 输入 (32,42,3) float32 NHWC 合成数据\n"
        "  stgcn3d_in.bin : ST-GCN 3D 输入 (32,42,4) float32 NHWC 合成数据\n"
        "生成: tools/gen_test_data.py\n"
    )
    print("完成 ->", TESTDATA)
    return 0


if __name__ == "__main__":
    sys.exit(main())
