#!/usr/bin/env python3
"""分析板端关键点"镜像翻转"现象 (INT8 量化 vs float 同输入)。

方法:
  1) 对每个 patch 求 float(PC) 与板端 21 点的三种拟合残差:
     - direct: 直接比对
     - rigid : 旋转+平移+缩放(不允许镜像)最小二乘拟合(Kabsch)
     - reflect: 镜像(任意轴)+平移+缩放最小二乘拟合(φ 网格搜索)
     若 reflect 残差 << rigid/direct ⇒ 该 patch 输出 = float 输出的"镜像"
  2) 关联图像/模型特征: 模糊度(Laplacian 方差)、手在裁剪中的大小与位置、
     拇指朝向、float presence/handedness、腕-中指角度
  3) 输出: flip_analysis.json + flip_analysis.csv + 代表性对比图

用法:
  ~/.handwash-ref-venv/bin/python tools/analyze_lm_flip.py \
      --patches /tmp/lm_patches_full --board out_board/lm_full_fix1 \
      --out out_pc/lm_full/flip_analysis
"""
import argparse
import csv
import json
import sys
from pathlib import Path

import numpy as np

LM_IN = 224


# ---------------- 拟合 ----------------

def fit_rigid(a, b):
    """旋转+平移(不允许镜像/缩放)最小二乘: b ≈ R·a + t (2D Kabsch)。返回残差(mean/max px)。"""
    ca, cb = a.mean(0), b.mean(0)
    a0, b0 = a - ca, b - cb
    H = b0.T @ a0
    U, S, Vt = np.linalg.svd(H)
    R = U @ Vt
    if np.linalg.det(R) < 0:   # 保向约束
        U[:, -1] *= -1
        R = U @ Vt
    pred = a0 @ R.T + cb
    d = np.linalg.norm(pred - b, axis=1)
    return float(d.mean()), float(d.max())


def _reflection(phi):
    c, s = np.cos(2 * phi), np.sin(2 * phi)
    return np.array([[c, s], [s, -c]])


def fit_reflect(a, b):
    """镜像(任意轴角 φ)+平移, **无缩放**(避免退化解)。返回 (mean, max, phi_deg)。"""
    ca, cb = a.mean(0), b.mean(0)
    a0 = a - ca
    best = None
    for phi in np.linspace(0, np.pi, 361, endpoint=False):
        aa = a0 @ _reflection(phi).T
        d = np.linalg.norm(aa + cb - b, axis=1)
        if best is None or d.mean() < best[0]:
            best = (float(d.mean()), float(d.max()), float(np.degrees(phi)))
    return best


def analyze_patch(a_lm, b_lm):
    a = a_lm.reshape(21, 3)[:, :2].astype(np.float64)
    b = b_lm.reshape(21, 3)[:, :2].astype(np.float64)
    direct = np.linalg.norm(a - b, axis=1)
    r_mean, r_max = fit_rigid(a, b)
    m_mean, m_max, phi = fit_reflect(a, b)
    return {
        "direct_mean": float(direct.mean()), "direct_max": float(direct.max()),
        "rigid_mean": r_mean, "rigid_max": r_max,
        "reflect_mean": m_mean, "reflect_max": m_max, "reflect_phi_deg": phi,
        # 判定: 镜像拟合显著优于保向拟合(刚体), 且镜像残差在合理范围
        "flip": bool(m_mean < 0.6 * r_mean and m_mean < 25.0),
    }


# ---------------- 图像特征 ----------------

def laplacian_var(gray):
    k = np.array([[0, 1, 0], [1, -4, 1], [0, 1, 0]], dtype=np.float32)
    g = gray.astype(np.float32)
    out = np.zeros_like(g)
    for dy in (-1, 0, 1):
        for dx in (-1, 0, 1):
            if dy == 0 and dx == 0:
                continue
            out[1:-1, 1:-1] += k[1 + dy, 1 + dx] * g[1 + dy:g.shape[0] - 1 + dy,
                                                     1 + dx:g.shape[1] - 1 + dx]
    return float(out[1:-1, 1:-1].var())


def image_stats(patch, lm, presence, handedness):
    gray = patch[:, :, 0] * 0.299 + patch[:, :, 1] * 0.587 + patch[:, :, 2] * 0.114
    pts = lm.reshape(21, 3)[:, :2]
    wrist, mid_mcp, thumb_tip, pinky_mcp = pts[0], pts[9], pts[4], pts[17]
    v = mid_mcp - wrist
    hand_angle = float(np.degrees(np.arctan2(v[1], v[0])))
    hand_span = float(np.linalg.norm(pts.max(0) - pts.min(0)))
    # 拇指相对掌心轴的横向偏移(左-/右+)
    axis = v / (np.linalg.norm(v) + 1e-6)
    rel = thumb_tip - wrist
    cross = float(axis[0] * rel[1] - axis[1] * rel[0])
    edge_margin = float(min(pts[:, 0].min(), pts[:, 1].min(),
                            LM_IN - pts[:, 0].max(), LM_IN - pts[:, 1].max()))
    return {
        "blur": laplacian_var(gray),
        "hand_span": hand_span,
        "hand_angle_deg": hand_angle,
        "thumb_cross": cross,
        "points_edge_margin": edge_margin,
        "presence": presence,
        "handedness": handedness,
    }


def main():
    ap = argparse.ArgumentParser()
    ap.add_argument("--patches", required=True)
    ap.add_argument("--board", required=True)
    ap.add_argument("--tlite", default=str(Path.home() /
                    "Desktop/标定/hand_landmarks_detector.tflite"))
    ap.add_argument("--out", required=True)
    ap.add_argument("--render", type=int, default=8, help="输出多少张翻转案例图")
    args = ap.parse_args()

    import ai_edge_litert.interpreter as itp
    from PIL import Image, ImageDraw

    out = Path(args.out)
    out.mkdir(parents=True, exist_ok=True)
    board = Path(args.board)

    it = itp.Interpreter(model_path=args.tlite)
    it.allocate_tensors()
    outs = {o["name"]: o for o in it.get_output_details()}
    ind = it.get_input_details()[0]["index"]

    rows = []
    for fp in sorted(Path(args.patches).glob("patch_*.bin")):
        name = fp.stem
        bpath = board / f"{name}_out0.bin"
        if not bpath.exists():
            continue
        patch = np.fromfile(fp, np.uint8).reshape(LM_IN, LM_IN, 3)
        it.set_tensor(ind, (patch.astype(np.float32) / 255.0)[None])
        it.invoke()
        pc_lm = it.get_tensor(outs["Identity"]["index"])[0]
        pc_pres = float(it.get_tensor(outs["Identity_1"]["index"])[0, 0])
        pc_hand = float(it.get_tensor(outs["Identity_2"]["index"])[0, 0])
        b_lm = np.fromfile(bpath, np.float32)
        b_pres = float(np.fromfile(board / f"{name}_out1.bin", np.float32)[0])

        fit = analyze_patch(pc_lm, b_lm)
        stats = image_stats(patch, pc_lm, pc_pres, pc_hand)
        rows.append({"patch": name, **fit, **stats})

    n = len(rows)
    flips = [r for r in rows if r["flip"]]
    print(f"总计 {n} patch, 镜像拟合判定为翻转: {len(flips)} ({100.0*len(flips)/max(n,1):.1f}%)")
    if flips:
        fm = np.array([r["reflect_mean"] for r in flips])
        dm = np.array([r["direct_mean"] for r in flips])
        print(f"翻转案例: 镜像后残差 mean={fm.mean():.1f}px (max {fm.max():.1f}), "
              f"镜像前 {dm.mean():.1f}px")
        phis = np.array([r["reflect_phi_deg"] for r in flips])
        print(f"镜像轴 φ: 中位 {np.median(phis):.1f}°, 范围 [{phis.min():.0f}, {phis.max():.0f}]°"
              f" (0/180°=竖直轴, 90°=水平轴)")

    # 特征相关性对比
    def stat(key, group):
        v = np.array([r[key] for r in group])
        return f"{v.mean():7.2f} ± {v.std():5.2f}" if len(v) else "无"

    normals = [r for r in rows if not r["flip"]]
    print(f"\n{'特征':22s} {'翻转组':>18s} {'正常组':>18s}")
    for key, label in [("blur", "模糊度(Laplacian var)"), ("hand_span", "手大小(px, 21点范围)"),
                       ("presence", "float presence"), ("handedness", "float handedness"),
                       ("points_edge_margin", "点到裁剪边缘距离(px)"),
                       ("thumb_cross", "拇指横向偏移(±)"),
                       ("hand_angle_deg", "腕→中指轴角度")]:
        print(f"{label:22s} {stat(key, flips):>18s} {stat(key, normals):>18s}")

    # 翻转率按手朝向分桶
    print("\n按拇指方向分桶(thumb_cross 符号: -右手指向左内/ +左手指向右内):")
    for sign, name in [(-1, "负(<-20)"), (1, "正(>20)"), (0, "接近 0")]:
        if sign == 0:
            grp = [r for r in rows if abs(r["thumb_cross"]) <= 20]
        else:
            grp = [r for r in rows if (r["thumb_cross"] > 20) == (sign == 1)
                   and abs(r["thumb_cross"]) > 20]
        nf = sum(1 for r in grp if r["flip"])
        print(f"  {name}: {nf}/{len(grp)}")

    # 保存
    (out / "flip_analysis.json").write_text(json.dumps(
        {"n": n, "n_flip": len(flips), "rows": rows}, indent=1))
    with open(out / "flip_analysis.csv", "w", newline="") as f:
        w = csv.DictWriter(f, fieldnames=list(rows[0].keys()))
        w.writeheader()
        w.writerows(rows)

    # 渲染案例
    if args.render > 0 and flips:
        flips_sorted = sorted(flips, key=lambda r: -r["direct_mean"])[: args.render]
        for r in flips_sorted:
            name = r["patch"]
            patch = np.fromfile(Path(args.patches) / f"{name}.bin", np.uint8).reshape(LM_IN, LM_IN, 3)
            it.set_tensor(ind, (patch.astype(np.float32) / 255.0)[None])
            it.invoke()
            pc_lm = it.get_tensor(outs["Identity"]["index"])[0].reshape(21, 3)[:, :2]
            b_lm = np.fromfile(board / f"{name}_out0.bin", np.float32).reshape(21, 3)[:, :2]
            ref = _reflection(np.radians(r["reflect_phi_deg"]))
            flipped = (ref @ (pc_lm - pc_lm.mean(0)).T).T + pc_lm.mean(0)
            z = 2
            im = Image.fromarray(patch).resize((LM_IN * z, LM_IN * z), Image.NEAREST)
            d = ImageDraw.Draw(im)
            from ref_lm import HAND_CONNECTIONS  # noqa: E402
            def draw(pts, color):
                for a2, b2 in HAND_CONNECTIONS:
                    d.line([pts[a2][0] * z, pts[a2][1] * z, pts[b2][0] * z, pts[b2][1] * z],
                           fill=color, width=2)
                for p in pts:
                    d.ellipse([p[0] * z - 3, p[1] * z - 3, p[0] * z + 3, p[1] * z + 3],
                              outline=color)
            draw(pc_lm, (0, 200, 0))         # 绿 = float
            draw(b_lm, (255, 140, 0))        # 橙 = 板端
            draw(flipped, (80, 160, 255))    # 蓝 = float 的镜像拟合
            im.save(out / f"flip_{name}.png")
    print(f"\n输出: {out}/flip_analysis.json / .csv" + (" + flip_*.png" if args.render else ""))
    return 0


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