#!/usr/bin/env python3
"""Stage-wise bisection of the RV1106 STGCN execution problem.

Builds truncated variants of the (noclip) ST-GCN++: after stage k the feature
tensor is flattened and multiplied by a fixed random projection (D,7) to get
7 logits, so the regular board tooling (test_stgcn_input, 7-element output)
can run each stage model and compare against the exact same reference computed
here with PyTorch.

  stage_0: data_bn affine only            D = 3*32*42
  stage_1: + blocks[0]                    D = 32*32*42
  stage_2: + blocks[1]                    D = 32*32*42
  stage_3: + blocks[2] (stride 2)         D = 64*32*42   (T=32 -> wait: 32/2=16)
  ...
  stage_5: + blocks[4] (= full backbone, no head)

Also converts each stage to rv1106 RKNN and writes ref_logits.json with the
PyTorch projection outputs for win_A / win_B.

Usage: /root/mmpose-venv/bin/python export_stage_models.py
"""

from __future__ import annotations

import json
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"))

# reuse the v2 exporter (installs the no-transpose patches on import)
sys.path.insert(0, str(Path(__file__).resolve().parent))
from export_onnx_v2 import MODELS, load_model  # noqa: E402

WORK = Path("/root/handwash-st-gcn-rknn")
WINS = {
    "winA": WORK / "win_samples/win_HandWash_001_A_02_G_01__000.bin",
    "winB": WORK / "win_samples/win_HandWash_001_A_07_G_01__009.bin",
}
FRAMES = 32
VERTICES = 42
CHANNELS = 3


class StageModel(nn.Module):
    """Run the backbone up to `upto` blocks, then a fixed projection to 7."""

    def __init__(self, base: nn.Module, upto: int, projection: np.ndarray) -> None:
        super().__init__()
        self.base = base
        self.upto = upto
        self.register_buffer("projection", torch.from_numpy(projection))

    def forward(self, value: torch.Tensor) -> torch.Tensor:
        model = self.base
        batch, channels, frames, vertices = value.shape
        scale = model._data_bn_scale.reshape(1, channels, 1, vertices)
        shift = model._data_bn_shift.reshape(1, channels, 1, vertices)
        v = value * scale + shift
        for block in list(model.blocks)[: self.upto]:
            v = block(v)
        flat = v.reshape(batch, -1)
        return torch.matmul(flat, self.projection)


def stage_dims(model: nn.Module, upto: int) -> tuple[int, int, int]:
    """(channels, frames, vertices) of the tensor after `upto` blocks."""
    with torch.no_grad():
        v = torch.zeros(1, CHANNELS, FRAMES, VERTICES)
        v = v * model._data_bn_scale.reshape(1, CHANNELS, 1, VERTICES) + \
            model._data_bn_shift.reshape(1, CHANNELS, 1, VERTICES)
        for block in list(model.blocks)[:upto]:
            v = block(v)
        return v.shape[1], v.shape[2], v.shape[3]


def main() -> None:
    out_dir = WORK / "output/stages"
    out_dir.mkdir(parents=True, exist_ok=True)

    entry = MODELS["2d"]
    base = load_model(entry).eval()

    windows = {name: np.fromfile(path, dtype=np.float32).reshape(1, CHANNELS, FRAMES, VERTICES)
               for name, path in WINS.items()}

    references: dict[str, dict[str, list[float]]] = {}
    rng = np.random.RandomState(42)

    stages = list(range(0, 6))  # 0..5
    for upto in stages:
        c, t, v = stage_dims(base, upto)
        d = c * t * v
        projection = (rng.randn(d, 7) * 0.05).astype(np.float32)
        model = StageModel(base, upto, projection).eval()

        onnx_path = out_dir / f"stage_{upto}.onnx"
        dummy = torch.from_numpy(windows["winA"])
        torch.onnx.export(model, dummy, str(onnx_path), opset_version=12,
                          input_names=["input"], output_names=["logits"],
                          do_constant_folding=True)

        with torch.no_grad():
            refs = {name: model(torch.from_numpy(w)).numpy().reshape(-1).tolist()
                    for name, w in windows.items()}
        references[f"stage_{upto}"] = refs
        print(f"stage_{upto}: after {upto} blocks C={c} T={t} V={v} D={d} "
              f"winA={[round(x, 3) for x in refs['winA']]}")

        # convert to rv1106
        from rknn.api import RKNN

        rknn = RKNN(verbose=False)
        try:
            ret = rknn.config(target_platform="rv1106", mean_values=[[0.0] * CHANNELS],
                              std_values=[[1.0] * CHANNELS],
                              quantized_dtype="asymmetric_quantized-8", optimization_level=3)
            if ret != 0:
                raise SystemExit(f"config failed ({ret})")
            ret = rknn.load_onnx(model=str(onnx_path))
            if ret != 0:
                raise SystemExit(f"load failed ({ret})")
            ret = rknn.build(do_quantization=True,
                             dataset=str(WORK / "calibration/stgcn_2d/list.txt"))
            if ret != 0:
                raise SystemExit(f"build failed ({ret})")
            dest = out_dir / f"stage_{upto}_rv1106.rknn"
            ret = rknn.export_rknn(str(dest))
            if ret != 0:
                raise SystemExit(f"export failed ({ret})")
            print(f"    -> {dest.name} ({dest.stat().st_size / 1024:.1f} KB)")
        finally:
            rknn.release()

    ref_path = out_dir / "ref_logits.json"
    ref_path.write_text(json.dumps(references, indent=1))
    print(f"references -> {ref_path}")


if __name__ == "__main__":
    main()
