#!/usr/bin/env python3
"""端到端左右对比渲染: 左 = PC(MediaPipe tflite 参考), 右 = 板端(RV1106 RKNN)。

输入:
  --pc     PC 输出目录(ref_lm.py: pc_results.json + frame_%03d.png)
  --board  板端 CSV(test_landmarker --e2e 输出)
  --manifest nv12 目录的 manifest.txt(run idx -> 原帧号)
产出:
  compare/compare_f%03d.png  左右并排图(绿=PC, 橙=板端)
  compare/lm_delta.csv       逐帧逐点像素距离(原图坐标)
用法:
  ~/.handwash-ref-venv/bin/python tools/render_lm_compare.py \
      --pc out_pc/lm_run1 --board out_board/lm_run1/lm_board.csv \
      --manifest out_pc/lm_run1/nv12/manifest.txt --out out_pc/lm_run1/compare
"""
import argparse
import csv
import json
import sys
from pathlib import Path

import numpy as np

sys.path.insert(0, str(Path(__file__).resolve().parent))
from ref_lm import HAND_CONNECTIONS  # noqa: E402

GREEN = (0, 220, 0)
ORANGE = (255, 140, 0)


def draw_skeleton(img, pts, color, conf=None):
    from PIL import ImageDraw
    d = ImageDraw.Draw(img)
    for a, b in HAND_CONNECTIONS:
        d.line([pts[a][0], pts[a][1], pts[b][0], pts[b][1]], fill=color, width=2)
    for i, p in enumerate(pts):
        r = 3 if i in (0, 9, 20) else 2
        d.ellipse([p[0] - r, p[1] - r, p[0] + r, p[1] + r], fill=(255, 255, 255),
                  outline=color)


def load_board_csv(path):
    rows = {}
    with open(path) as f:
        for row in csv.DictReader(f):
            fidx = int(row["frame"])
            pts = [(float(row[f"x{k}"]), float(row[f"y{k}"])) for k in range(21)]
            rows.setdefault(fidx, []).append({
                "pts": pts, "presence": float(row["presence"]),
                "handedness": float(row["handedness"]), "side": row["side"],
                "score": float(row["det_score"]),
                "box": [float(row["det_x1"]), float(row["det_y1"]), float(row["det_x2"]),
                        float(row["det_y2"])],
            })
    return rows


def main():
    ap = argparse.ArgumentParser()
    ap.add_argument("--pc", required=True)
    ap.add_argument("--board", required=True)
    ap.add_argument("--manifest", required=True)
    ap.add_argument("--out", required=True)
    ap.add_argument("--pres-thresh", type=float, default=0.5,
                    help="PC 端 presence 阈值(低于则标注 LOW)")
    args = ap.parse_args()

    from PIL import Image, ImageDraw

    pc_dir = Path(args.pc)
    out_dir = Path(args.out)
    out_dir.mkdir(parents=True, exist_ok=True)

    pc_results = {e["frame"]: e for e in json.load(open(pc_dir / "pc_results.json"))}
    board = load_board_csv(args.board)

    manifest = {}
    for line in Path(args.manifest).read_text().splitlines():
        if line.startswith("#") or not line.strip():
            continue
        run, frame = line.split()
        manifest[int(run)] = int(frame)

    delta_rows = []
    for run in sorted(manifest):
        fidx = manifest[run]
        fp = pc_dir / f"frame_{fidx:03d}.png"
        if not fp.exists():
            print(f"缺帧文件: {fp}")
            continue
        frame = Image.open(fp).convert("RGB")
        w, h = frame.size

        # --- 左: PC ---
        left = frame.copy()
        dl = ImageDraw.Draw(left)
        pc_hands = pc_results.get(fidx, {}).get("hands", [])
        for i, hand in enumerate(pc_hands):
            pts = [(p[0], p[1]) for p in hand["landmarks_px"]]
            ok = hand["presence"] >= args.pres_thresh
            draw_skeleton(left, pts, GREEN)
            label = f"PC #{i} {hand['side']} p={hand['presence']:.2f}" + ("" if ok else " LOW")
            dl.text((pts[0][0] + 5, pts[0][1] - 14 - 12 * i), label, fill=GREEN)

        # --- 右: 板端 ---
        right = frame.copy()
        dr = ImageDraw.Draw(right)
        b_hands = board.get(run, [])
        for i, hand in enumerate(b_hands):
            draw_skeleton(right, hand["pts"], ORANGE)
            bx = hand["box"]
            dr.rectangle(bx, outline=(255, 255, 255), width=1)
            label = f"RKNN #{i} {hand['side']} p={hand['presence']:.2f} det={hand['score']:.2f}"
            dr.text((hand["pts"][0][0] + 5, hand["pts"][0][1] - 14 - 12 * i), label, fill=ORANGE)
        if not b_hands:
            dr.text((10, 10), "RKNN: no hand detected", fill=ORANGE)

        # --- 数值差异 ---
        if pc_hands and b_hands:
            n = min(len(pc_hands), len(b_hands))
            for hi in range(n):
                a = np.array([p[:2] for p in pc_hands[hi]["landmarks_px"]])
                b = np.array(b_hands[hi]["pts"])
                dist = np.linalg.norm(a - b, axis=1)
                delta_rows.append({
                    "run": run, "frame": fidx, "hand": hi,
                    "mean_px": float(dist.mean()), "max_px": float(dist.max()),
                    "wrist_px": float(dist[0]), "mid_px": float(dist[9]),
                    "pc_pres": pc_hands[hi]["presence"], "board_pres": b_hands[hi]["presence"],
                    "pc_side": pc_hands[hi]["side"], "board_side": b_hands[hi]["side"],
                })

        # --- 拼图 ---
        gap = 10
        head = 26
        combo = Image.new("RGB", (w * 2 + gap, h + head), (24, 24, 24))
        combo.paste(left, (0, head))
        combo.paste(right, (w + gap, head))
        dc = ImageDraw.Draw(combo)
        dc.text((8, 6), f"PC / MediaPipe tflite   frame {fidx} (run {run})", fill=(200, 200, 200))
        dc.text((w + gap + 8, 6), "RV1106 RKNN (board)", fill=(200, 200, 200))
        combo.save(out_dir / f"compare_f{fidx:03d}.png")

    if delta_rows:
        with open(out_dir / "lm_delta.csv", "w", newline="") as f:
            wr = csv.DictWriter(f, fieldnames=list(delta_rows[0].keys()))
            wr.writeheader()
            wr.writerows(delta_rows)
        means = [r["mean_px"] for r in delta_rows]
        maxes = [r["max_px"] for r in delta_rows]
        print(f"端到端 {len(delta_rows)} 手对比: 平均点到点误差 mean={np.mean(means):.1f}px "
              f"(最差帧平均 {np.max(means):.1f}px), 单点最大 {np.max(maxes):.1f}px")
        for r in delta_rows:
            print(f"  frame {r['frame']:3d}: mean={r['mean_px']:6.1f} max={r['max_px']:6.1f} "
                  f"wrist={r['wrist_px']:5.1f} mid={r['mid_px']:5.1f} | "
                  f"PC {r['pc_side']}({r['pc_pres']:.2f}) vs RK {r['board_side']}({r['board_pres']:.2f})")
    print(f"对比图: {out_dir}/compare_f*.png")
    return 0


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