#!/usr/bin/env python3
"""ST-GCN++ -> ONNX/RKNN with a u8-friendly input domain (RV1106 work-around).

Findings (2026-09-20): on this RV1106 the ONLY working input path is the
"image-style" one used by the landmark/detector models:

    * input tensor quantised as u8 domain  (attr zp=-128, scale=1/255)
    * bind UINT8 + write physical bytes    u = logical_value * 255
    * the toolkit config uses mean=0 / std=255 (input conversion fused)

Every attempt to feed a plain int8/f32-domain model (attr zp=0/-46/...) failed:
the NPU ignored the input buffer entirely (constant output).

So the feature domain x ([-5, 5], normalised coordinates) is mapped into the
u8 domain:  y = (x + 5) / 10  in [0, 1], and the reconstruction
x = 10*y - 5 is folded into the (already affine) data_bn:
    scale' = 10 * scale_bn ;  shift' = shift_bn - 5 * scale_bn
No extra graph ops are added; |x| > 5 saturates in the u8 data domain, which
reproduces the ±5 input clip that the original ONNX export used to get from an
(explicit) Clip node -- a Clip node that turned out to break the RV1106
compile.

Everything else is identical to export_onnx_v2 (zero Transpose graph).

Usage (2d / 3d):
    /root/mmpose-venv/bin/python make_stgcn_y_rknn.py --tag 2d
    /root/mmpose-venv/bin/python make_stgcn_y_rknn.py --tag 3d
(2D: C=5, 3ch x,y,visible; 3D: C=2, 4ch world xyz,visible)
"""

from __future__ import annotations

import argparse
import sys
from pathlib import Path

import numpy as np
import torch
from torch import nn

REPO = Path("/root/handwash-st-gcn")
sys.path.insert(0, str(REPO / "stgcnpp_window_training" / "scripts"))
sys.path.insert(0, str(Path(__file__).resolve().parent))

from export_onnx_v2 import FRAMES, MODELS, VERTICES, load_model  # noqa: E402

WORK = Path("/root/handwash-st-gcn-rknn")
# feature-domain clip per model (matches the original export_onnx.py CLIPS)
CLIPS = {"2d": 5.0, "3d": 2.0}


class YDomainModel(nn.Module):
    """Wrap the (already data_bn-folded) model for the y = (x+C)/(2C) domain."""

    def __init__(self, base: nn.Module, clip: float) -> None:
        super().__init__()
        self.base = base
        self.clip = float(clip)
        with torch.no_grad():
            scale = base._data_bn_scale
            shift = base._data_bn_shift
            self.base.register_buffer("_y_scale", scale * (2.0 * clip))
            self.base.register_buffer("_y_shift", shift - scale * clip)

    def forward(self, value: torch.Tensor) -> torch.Tensor:  # y domain in [0,1]
        base = self.base
        batch, channels, frames, vertices = value.shape
        s = base._y_scale.reshape(1, channels, 1, vertices)
        h = base._y_shift.reshape(1, channels, 1, vertices)
        v = value * s + h                      # == x * scale_bn + shift_bn
        for block in base.blocks:
            v = block(v)
        return base.head(v)


def main() -> None:
    parser = argparse.ArgumentParser()
    parser.add_argument("--tag", default="2d", choices=["2d", "3d"])
    args = parser.parse_args()

    tag = args.tag
    clip = CLIPS[tag]
    out_dir = WORK / "output"
    channels = MODELS[tag]["input_channels"]
    base = load_model(MODELS[tag]).eval()
    model = YDomainModel(base, clip).eval()

    probe_y = np.random.RandomState(1234).rand(1, channels, FRAMES, VERTICES).astype(np.float32)
    dummy = torch.from_numpy(probe_y)
    onnx_path = out_dir / f"handwash_stgcn_{tag}_y.onnx"
    torch.onnx.export(model, dummy, str(onnx_path), opset_version=12,
                      input_names=["input"], output_names=["logits"],
                      do_constant_folding=True)

    # numeric equivalence with the ORIGINAL feature-domain model
    import onnx
    import onnxruntime as ort
    graph = onnx.load(str(onnx_path))
    transposes = [n.name for n in graph.graph.node if n.op_type == "Transpose"]
    print(f"onnx: {onnx_path.name} nodes={len(graph.graph.node)} Transpose={len(transposes)}")
    with torch.no_grad():
        x = torch.from_numpy(probe_y * (2.0 * clip) - clip)
        ref = base(x).numpy()
    ort_out = ort.InferenceSession(str(onnx_path), providers=["CPUExecutionProvider"]) \
        .run(None, {"input": probe_y})[0]
    delta = float(np.max(np.abs(ort_out - ref)))
    print(f"y-domain ONNX vs feature-domain torch: max|diff| = {delta:.3e}")
    if delta > 1e-4:
        raise SystemExit("y-domain rewrite deviates!")

    # u8-domain calibration set: u = clip((x+C)/(2C), 0, 1) * 255  (physical u8 domain)
    src_dir = WORK / f"calibration/stgcn_{tag}"
    dst_dir = WORK / f"calibration/stgcn_{tag}_y"
    dst_dir.mkdir(parents=True, exist_ok=True)
    lines = []
    for i, src in enumerate([l.strip() for l in (src_dir / "list.txt").read_text().splitlines()
                             if l.strip()]):
        x = np.load(src)                                   # (1,C,32,42) feature domain
        u = np.clip((x + clip) / (2 * clip), 0.0, 1.0) * 255.0
        dst = dst_dir / f"{i:04d}.npy"
        np.save(dst, u.astype(np.float32))
        lines.append(str(dst))
    (dst_dir / "list.txt").write_text("\n".join(lines) + "\n")
    print(f"u8-domain calib: {len(lines)} npy -> {dst_dir}")

    # convert exactly like the (working) landmark models
    from rknn.api import RKNN
    rknn = RKNN(verbose=False)
    try:
        assert rknn.config(target_platform="rv1106", mean_values=[0] * channels,
                           std_values=[255] * channels, quant_img_RGB2BGR=False) == 0
        assert rknn.load_onnx(model=str(onnx_path)) == 0
        assert rknn.build(do_quantization=True, dataset=str(dst_dir / "list.txt")) == 0
        dest = out_dir / f"handwash_stgcn_{tag}_rv1106_y.rknn"
        assert rknn.export_rknn(str(dest)) == 0
    finally:
        rknn.release()
    pump = 255.0 / (2 * clip)
    print(f"    -> {dest.name} ({dest.stat().st_size/1024:.1f} KB)")
    print(f"板端: U8 绑定, 字节 = clamp(round(x*{pump:.2f}+127.5), 0, 255)")


if __name__ == "__main__":
    main()
