#!/usr/bin/env python3
"""Create two minimal toy ONNX graphs + RKNN(rv1106) builds to bisect the
"STGCN NPU ignores its input on RV1106" issue.

T0: input (1,3,32,42) -> Reshape(1,4032) -> MatMul(4032x7) -> logits(1,7)
    same geometry as the STGCN model; device input [1,32,42,3] has w_stride=48
    padding (42 -> 48, align 16)
T1: input (1,3,32,48) -> Reshape(1,4608) -> MatMul(4608x7) -> logits(1,7)
    W=48 aligns to 16 -> w_stride=48 == W -> NO padding

If T0 output is input-independent while T1 varies, the input padding
(w_stride > W) is the culprit.  If both vary, the STGCN graph itself is.
Both use the real STGCN calibration data (T1 padded 42->48) so the input
scale/zp are realistic.

Usage: /root/mmpose-venv/bin/python make_toys.py --output-dir output
"""

from __future__ import annotations

import argparse
from pathlib import Path

import numpy as np
import onnx
from onnx import TensorProto, helper

WORK = Path("/root/handwash-st-gcn-rknn")
FRAMES = 32
OUT_DIM = 7
CALIB_SRC = WORK / "calibration/stgcn_2d"
CALIB_N = 64


def make_toy_onnx(path: Path, width: int, seed: int) -> None:
    rng = np.random.RandomState(seed)
    k = 3 * FRAMES * width
    weights = (rng.randn(k, OUT_DIM) * 0.05).astype(np.float32)
    nodes = [
        helper.make_node("Reshape", ["input", "shape"], ["flat"], name="reshape"),
        helper.make_node("MatMul", ["flat", "W"], ["logits"], name="matmul"),
    ]
    graph = helper.make_graph(
        nodes,
        f"toy{width}",
        [helper.make_tensor_value_info("input", TensorProto.FLOAT, [1, 3, FRAMES, width])],
        [helper.make_tensor_value_info("logits", TensorProto.FLOAT, [1, OUT_DIM])],
        initializer=[
            helper.make_tensor("shape", TensorProto.INT64, [2], [1, k]),
            helper.make_tensor("W", TensorProto.FLOAT, [k, OUT_DIM], weights.flatten()),
        ],
    )
    model = helper.make_model(graph, opset_imports=[helper.make_opsetid("", 12)])
    model.ir_version = 8
    onnx.checker.check_model(model)
    onnx.save(model, str(path))
    print(f"    {path.name}: input (1,3,{FRAMES},{width}) -> MatMul({k}x{OUT_DIM})")


def make_calib_padded(dst_dir: Path) -> Path:
    dst_dir.mkdir(parents=True, exist_ok=True)
    sources = [line.strip() for line in (CALIB_SRC / "list.txt").read_text().splitlines()
               if line.strip()][:CALIB_N]
    lines = []
    for i, src in enumerate(sources):
        data = np.load(src)  # (1,3,32,42)
        padded = np.zeros((1, 3, FRAMES, 48), dtype=data.dtype)
        padded[:, :, :, :42] = data
        dst = dst_dir / f"{i:04d}.npy"
        np.save(dst, padded)
        lines.append(str(dst))
    listing = dst_dir / "list.txt"
    listing.write_text("\n".join(lines) + "\n")
    print(f"    calib: {len(lines)} npy (42->48 padded) -> {listing}")
    return listing


def convert(onnx_path: Path, calib: Path, destination: Path) -> None:
    from rknn.api import RKNN

    rknn = RKNN(verbose=False)
    try:
        ret = rknn.config(target_platform="rv1106", mean_values=[[0.0, 0.0, 0.0]],
                          std_values=[[1.0, 1.0, 1.0]],
                          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(calib))
        if ret != 0:
            raise SystemExit(f"build failed ({ret})")
        ret = rknn.export_rknn(str(destination))
        if ret != 0:
            raise SystemExit(f"export failed ({ret})")
    finally:
        rknn.release()
    print(f"    {destination.name} ({destination.stat().st_size / 1024:.1f} KB)")


def main() -> None:
    parser = argparse.ArgumentParser()
    parser.add_argument("--output-dir", type=Path, default=WORK / "output")
    args = parser.parse_args()
    args.output_dir.mkdir(parents=True, exist_ok=True)

    t0_onnx = args.output_dir / "toy_t0_w42.onnx"
    t1_onnx = args.output_dir / "toy_t1_w48.onnx"
    make_toy_onnx(t0_onnx, 42, seed=0)
    make_toy_onnx(t1_onnx, 48, seed=1)

    print("==> convert T0 (w_stride padded, like STGCN)")
    convert(t0_onnx, CALIB_SRC / "list.txt", args.output_dir / "toy_t0_w42_rv1106.rknn")
    print("==> convert T1 (aligned width, no padding)")
    make_calib_padded(WORK / "calibration/toy_t1")
    convert(t1_onnx, WORK / "calibration/toy_t1/list.txt",
            args.output_dir / "toy_t1_w48_rv1106.rknn")
    print("done")


if __name__ == "__main__":
    main()
