#!/usr/bin/env python3
"""v3 "scene3d"(共享场景 4 通道) ST-GCN++ 的 RKNN 校准集生成。

RKNN 的逐张量量化范围由校准集决定,校准必须贴近部署分布 —— 本脚本用**真实
手洗窗口**复刻训练侧 SharedSceneDataset 的特征构造(与训练代码逐行一致):

    coords/宽高(归一化 xy, 板端同此口径) + world_coords(米) + visible
      -> scene = build_shared_scene(coords, world, visible)   # z 域换算
      -> feats = normalise_world(scene, visible)               # (T,42,3)
      -> feats = concat(feats, visible[..., None], 2)          # (T,42,4)
      -> transpose(2,0,1)                                      # (4,32,42)

训练时 `rotate_shared_scene(..., variant=0)` 是恒等(评估/部署同样恒等),这里不旋转。

输出:
    <out>/feat/NNNN.npy  (1,4,32,42) float32 特征域(供自检/对比)
    <out>/u8/NNNN.npy    u8 物理域 = clip((x+C)/(2C),0,1)*255 (RKNN 校准)
    <out>/feat/list.txt / <out>/u8/list.txt

用法(AutoDL 训练机上跑):
    /root/miniconda3/bin/python gen_calib_scene3d.py \
        --manifest training_runs/.../prepared/clean_handwash_train_manifest.csv \
        --out /root/autodl-tmp/calib_scene3d --windows 320 --clip 2.0 --mirror
"""

from __future__ import annotations

import argparse
import csv
import random
from collections import defaultdict
from pathlib import Path

import numpy as np

FRAMES = 32
VERTICES = 42
CHANNELS = 4


# --------------------------------------------------------------------------
# 以下两个函数逐行抄自训练侧
#   stgcnpp_window_training/experiments/handwash_only_global_scene_2d3d_*/
#   scripts/train_handwash_only_global_scene.py
# 与 stgcnpp_window_training/scripts/train_window_stgcnpp.py::normalise_world
# --------------------------------------------------------------------------
def build_shared_scene(coords: np.ndarray, world: np.ndarray,
                       visible: np.ndarray) -> tuple[np.ndarray, np.ndarray]:
    """Embed both hand-local MediaPipe depth fields into one image-anchored scene.

    x/y retain their original joint positions, so the observed hand-to-hand
    relationship is retained.  MediaPipe's local z is translated to each wrist
    and scaled to that hand's image palm length.  Absolute inter-wrist depth is
    unavailable in this data source and is therefore explicitly assumed zero.
    """
    scene = np.zeros_like(world, dtype=np.float32)
    scene[..., :2] = coords[..., :2]
    previous_scale = [1.0, 1.0]
    frame_centres: list[np.ndarray] = []
    for frame in range(len(coords)):
        present = visible[frame].astype(bool)
        for hand in range(2):
            offset = hand * 21
            hand_present = present[offset:offset + 21]
            if not hand_present.any():
                continue
            wrist, middle = offset, offset + 9
            if hand_present[0] and hand_present[9]:
                image_scale = float(np.linalg.norm(coords[frame, middle, :2] -
                                                   coords[frame, wrist, :2]))
                world_scale = float(np.linalg.norm(world[frame, middle] -
                                                   world[frame, wrist]))
                if image_scale > 1e-5 and world_scale > 1e-6:
                    previous_scale[hand] = image_scale / world_scale
            root = wrist if hand_present[0] else offset + int(np.flatnonzero(hand_present)[0])
            scene[frame, offset:offset + 21, 2] = (
                world[frame, offset:offset + 21, 2] - world[frame, root, 2]
            ) * previous_scale[hand]
        wrists = [joint for joint in (0, 21) if present[joint]]
        if wrists:
            frame_centres.append(coords[frame, wrists, :2].mean(axis=0))
        elif present.any():
            frame_centres.append(coords[frame, np.flatnonzero(present), :2].mean(axis=0))
    if not frame_centres:
        return scene, np.zeros(3, dtype=np.float32)
    xy = np.median(np.stack(frame_centres), axis=0)
    return scene, np.asarray((xy[0], xy[1], 0.0), dtype=np.float32)


def normalise_world(coords: np.ndarray, visible: np.ndarray) -> np.ndarray:
    """Centre direct MediaPipe world landmarks and scale by 3D palm length."""
    result = np.zeros((len(coords), 42, 3), dtype=np.float32)
    previous_scale = 1.0
    for frame in range(len(coords)):
        present = visible[frame].astype(bool)
        if not present.any():
            continue
        wrists = [node for node in (0, 21) if present[node]]
        origin = np.mean(coords[frame, wrists], axis=0) if wrists else \
            np.mean(coords[frame, present], axis=0)
        scales = [
            np.linalg.norm(coords[frame, middle] - coords[frame, wrist])
            for wrist, middle in ((0, 9), (21, 30)) if present[wrist] and present[middle]
        ]
        scale = float(np.median(scales)) if scales else previous_scale
        if not np.isfinite(scale) or scale < 1e-4:
            scale = previous_scale
        result[frame, present] = (coords[frame, present] - origin) / max(scale, 1e-4)
        previous_scale = scale
    return result


def mirror(features: np.ndarray) -> np.ndarray:
    """Reflect the x channel and swap the two fixed MediaPipe hand slots."""
    output = features.copy()
    output[..., 0] *= -1.0
    return np.concatenate((output[:, 21:], output[:, :21]), axis=1)


def window_features(path: str, start: int, end: int) -> np.ndarray:
    with np.load(path, allow_pickle=False) as data:
        coords = data["coords"].astype(np.float32)
        world = data["world_coords"].astype(np.float32)
        visible = data["visible"].astype(np.uint8)
    scene, _ = build_shared_scene(coords, world, visible)     # 整段(与训练一致)
    sl = slice(start, end)
    normalised = normalise_world(scene[sl], visible[sl])      # 窗口内归一化
    feats = np.concatenate((normalised, visible[sl][..., None]), axis=2)
    return feats.transpose(2, 0, 1).copy()                    # (4,32,42)


def main() -> None:
    parser = argparse.ArgumentParser()
    parser.add_argument("--manifest", type=Path, required=True)
    parser.add_argument("--out", type=Path, required=True)
    parser.add_argument("--windows", type=int, default=320)
    parser.add_argument("--clip", type=float, default=2.0)
    parser.add_argument("--mirror", action="store_true", help="追加镜像副本")
    parser.add_argument("--seed", type=int, default=20260922)
    args = parser.parse_args()

    rows = [r for r in csv.DictReader(args.manifest.open())
            if int(r["window_end_frame_exclusive"]) - int(r["window_start_frame"]) == FRAMES]
    if not rows:
        raise SystemExit("manifest 里没有 32 帧窗口")
    by_label: dict[str, list[dict]] = defaultdict(list)
    for r in rows:
        by_label[r["label"]].append(r)
    rng = random.Random(args.seed)
    for values in by_label.values():
        rng.shuffle(values)

    # 按类别轮流取样, 保证 7 个步骤都进入校准集
    labels = sorted(by_label)
    picked: list[dict] = []
    index = {label: 0 for label in labels}
    while len(picked) < min(args.windows, len(rows)):
        for label in labels:
            values, cursor = by_label[label], index[label]
            if cursor >= len(values) or len(picked) >= args.windows:
                continue
            picked.append(values[cursor])
            index[label] = cursor + 1

    feat_dir, u8_dir = args.out / "feat", args.out / "u8"
    feat_dir.mkdir(parents=True, exist_ok=True)
    u8_dir.mkdir(parents=True, exist_ok=True)
    feat_list, u8_list = [], []
    mags = []
    for i, row in enumerate(picked):
        start = int(row["window_start_frame"])
        end = int(row["window_end_frame_exclusive"])
        feats = window_features(row["skeleton_path"], start, end)
        variants = [feats] + ([mirror(feats)] if args.mirror else [])
        for variant in variants:
            x = variant[None].astype(np.float32)              # (1,4,32,42)
            idx = len(feat_list)
            np.save(feat_dir / f"{idx:04d}.npy", x)
            feat_list.append(str(feat_dir / f"{idx:04d}.npy"))
            u = np.clip((x + args.clip) / (2 * args.clip), 0.0, 1.0) * 255.0
            np.save(u8_dir / f"{idx:04d}.npy", u.astype(np.float32))
            u8_list.append(str(u8_dir / f"{idx:04d}.npy"))
            mags.append(np.abs(x[:, :3]).ravel())
    (feat_dir / "list.txt").write_text("\n".join(feat_list) + "\n")
    (u8_dir / "list.txt").write_text("\n".join(u8_list) + "\n")

    mags = np.concatenate(mags)
    print(f"窗口 {len(picked)} → 样本 {len(feat_list)} (含镜像={args.mirror})")
    print(f"|xyz| 分位数: p50={np.percentile(mags,50):.3f} p99={np.percentile(mags,99):.3f} "
          f"p99.9={np.percentile(mags,99.9):.3f} max={mags.max():.3f}")
    print(f"clip=C={args.clip} 时饱和比例: {100*np.mean(mags > args.clip):.3f}%")
    print(f"输出: {feat_dir} / {u8_dir}")


if __name__ == "__main__":
    main()
