#!/usr/bin/env python3
"""Reshape-semantics discriminator toy (random projection version).

toy_r7:  input (1,3,32,42) -> Reshape(1,4032) -> MatMul(P random 4032x7) -> (1,7)

The board writes the window data as NHWC [1,32,42,3]; if the rv1106 flatten
matches ONNX NCHW semantics, the board output equals sum(nchw_flat[i]*P[i]);
if it flattens the *internal NHWC* tensor, it equals sum(nhwc_flat[i]*P[i]).
Both candidates are computed here, so the board output identifies the actual
flatten order.  A matching result also proves end-to-end numeric integrity of
the input path (quantisation + IO binding + matmul).

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

from __future__ import annotations

import json
from pathlib import Path

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

WORK = Path("/root/handwash-st-gcn-rknn")
OUT = WORK / "output/toys2"
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",
}
IN_SCALE = 0.039216
K = 4032
PROJ_SEED = 123


def make_onnx(path: Path, projection: np.ndarray) -> None:
    graph = helper.make_graph(
        [helper.make_node("Reshape", ["input", "shape"], ["flat"]),
         helper.make_node("MatMul", ["flat", "P"], ["logits"])],
        "toy_r7",
        [helper.make_tensor_value_info("input", TensorProto.FLOAT, [1, 3, 32, 42])],
        [helper.make_tensor_value_info("logits", TensorProto.FLOAT, [1, 7])],
        initializer=[
            helper.make_tensor("shape", TensorProto.INT64, [2], [1, K]),
            helper.make_tensor("P", TensorProto.FLOAT, [K, 7], projection.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))


def convert(onnx_path: Path, dest: Path) -> None:
    from rknn.api import RKNN
    rknn = RKNN(verbose=False)
    try:
        assert rknn.config(target_platform="rv1106", mean_values=[[0, 0, 0]],
                           std_values=[[1, 1, 1]],
                           quantized_dtype="asymmetric_quantized-8",
                           optimization_level=3) == 0
        assert rknn.load_onnx(model=str(onnx_path)) == 0
        assert rknn.build(do_quantization=True,
                          dataset=str(WORK / "calibration/stgcn_2d/list.txt")) == 0
        assert rknn.export_rknn(str(dest)) == 0
    finally:
        rknn.release()
    print(f"    -> {dest.name} ({dest.stat().st_size/1024:.1f} KB)")


def main() -> None:
    OUT.mkdir(parents=True, exist_ok=True)
    rng = np.random.RandomState(PROJ_SEED)
    projection = (rng.randn(K, 7) * 0.05).astype(np.float32)
    make_onnx(OUT / "toy_r7.onnx", projection)
    convert(OUT / "toy_r7.onnx", OUT / "toy_r7_rv1106.rknn")

    session = ort.InferenceSession(str(OUT / "toy_r7.onnx"),
                                   providers=["CPUExecutionProvider"])
    refs = {}
    for name, path in WINS.items():
        nhwc = np.fromfile(path, dtype=np.float32).reshape(32, 42, 3)
        # board-style quantisation of the NHWC buffer (this is what the NPU sees)
        qdq_nhwc = np.clip(np.round(nhwc / IN_SCALE), -128, 127) * IN_SCALE  # (32,42,3)
        nchw = np.ascontiguousarray(qdq_nhwc.transpose(2, 0, 1))[None]      # ORT view

        ort_out = session.run(None, {"input": nchw})[0].reshape(-1)
        # candidate A: flatten in NHWC internal order (win-file linear order)
        cand_nhwc = qdq_nhwc.reshape(-1) @ projection
        # candidate B: flatten in NCHW order (ONNX semantics)
        cand_nchw = np.ascontiguousarray(qdq_nhwc.transpose(2, 0, 1)).reshape(-1) @ projection

        refs[name] = {"ort_nchw": ort_out.tolist(),
                      "cand_nhwc_flat": cand_nhwc.tolist(),
                      "cand_nchw_flat": cand_nchw.tolist()}
        print(f"[{name}] ort(nchw)     = {np.round(ort_out, 3)}")
        print(f"[{name}] cand NHWC-flat = {np.round(cand_nhwc, 3)}")
        print(f"[{name}] cand NCHW-flat = {np.round(cand_nchw, 3)}")
        print(f"[{name}] candidates差   = {np.abs(cand_nhwc - cand_nchw).max():.3f}")

    (OUT / "refs_r7.json").write_text(json.dumps(refs, indent=1))
    print(f"-> {OUT/'refs_r7.json'}")


if __name__ == "__main__":
    main()
