#!/usr/bin/env python3
"""生成板端端到端测试输入: PNG 帧 → NV12(720x480, Y + 交错 UV, BT.601 limited)

输出文件按 run 序号命名(lm_in_000..N-1), 同时写 manifest.txt 记录 run 序号 → 原帧号,
供对比脚本映射(与 ref_lm.py --indices 配合)。

用法:
  python3 tools/gen_lm_inputs.py --frames testdata/lm_frames_001 \
      --indices 0,1,3,4 --out testdata/lm_run1/nv12
"""
import argparse
from pathlib import Path

import numpy as np


def rgb_to_nv12(rgb: np.ndarray) -> bytes:
    """RGB888 (H,W,3) uint8 → NV12 bytes (Y 平面 + 交错 UV), BT.601 limited range。"""
    r = rgb[:, :, 0].astype(np.float32)
    g = rgb[:, :, 1].astype(np.float32)
    b = rgb[:, :, 2].astype(np.float32)
    y = 16 + 0.257 * r + 0.504 * g + 0.098 * b
    u = 128 - 0.148 * r - 0.291 * g + 0.439 * b
    v = 128 + 0.439 * r - 0.368 * g - 0.071 * b
    y = np.clip(y, 0, 255).astype(np.uint8)
    # 2x2 平均降采样
    h, w = y.shape
    u = np.clip(u, 0, 255)[: h // 2 * 2, : w // 2 * 2].reshape(h // 2, 2, w // 2, 2).mean(
        axis=(1, 3))
    v = np.clip(v, 0, 255)[: h // 2 * 2, : w // 2 * 2].reshape(h // 2, 2, w // 2, 2).mean(
        axis=(1, 3))
    uv = np.empty((h // 2, w // 2, 2), dtype=np.uint8)
    uv[:, :, 0] = np.round(u).astype(np.uint8)
    uv[:, :, 1] = np.round(v).astype(np.uint8)
    return y.tobytes() + uv.tobytes()


def main():
    ap = argparse.ArgumentParser()
    ap.add_argument("--frames", required=True, help="PNG 帧目录(f_%03d.png, 1 基)")
    ap.add_argument("--indices", required=True, help="帧号列表(逗号分隔, 0 基, 与 ref_lm.py 一致)")
    ap.add_argument("--out", required=True)
    args = ap.parse_args()

    from PIL import Image
    out = Path(args.out)
    out.mkdir(parents=True, exist_ok=True)
    src = Path(args.frames)
    idx_list = [int(x) for x in args.indices.split(",") if x.strip() != ""]

    lines = []
    for run, idx in enumerate(idx_list):
        fp = src / f"f_{idx + 1:03d}.png"        # 文件从 1 开始编号
        img = np.asarray(Image.open(fp).convert("RGB"))
        nv12 = rgb_to_nv12(img)
        name = f"lm_in_{run:03d}.nv12"
        (out / name).write_bytes(nv12)
        lines.append(f"{run} {idx}")
        print(f"{name}  <- frame {idx}  ({img.shape[1]}x{img.shape[0]}, {len(nv12)} bytes)")
    (out / "manifest.txt").write_text("# run_idx frame_idx\n" + "\n".join(lines) + "\n")
    print(f"完成: {len(idx_list)} 帧 → {out}/ (manifest.txt 已写)")

if __name__ == "__main__":
    main()
