#!/usr/bin/env python3
"""ORT references for the bisection models, with and without board-style input
quantisation, so the board (rv1106) outputs can be compared numerically.

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

from __future__ import annotations

import json
from pathlib import Path

import numpy as np
import onnxruntime as ort

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",
}
# input quantisation exactly as the board tool does it (from the rknn input attr)
IN_SCALE = {"toy_t0": (0.039216, 0), "stage_0": (0.039216, 0),
            "toy_t1": (0.024031, -46)}


def quantise_dequantise(x: np.ndarray, scale: float, zp: int) -> np.ndarray:
    q = np.clip(np.round(x / scale) + zp, -128, 127)
    return (q - zp) * scale


def main() -> None:
    models = {
        "toy_t0": WORK / "output/toy_t0_w42.onnx",
        "toy_t1": WORK / "output/toy_t1_w48.onnx",
        "stage_0": WORK / "output/stages/stage_0.onnx",
    }
    windows = {name: np.fromfile(path, dtype=np.float32).reshape(32, 42, 3)
               for name, path in WINS.items()}

    out: dict[str, dict[str, dict[str, list[float]]]] = {}
    for tag, onnx_path in models.items():
        session = ort.InferenceSession(str(onnx_path), providers=["CPUExecutionProvider"])
        scale, zp = IN_SCALE.get(tag, (0.0, 0))
        out[tag] = {}
        for name, nhwc in windows.items():
            if tag == "toy_t1":
                padded = np.zeros((32, 48, 3), dtype=np.float32)
                padded[:, :42, :] = nhwc
                nhwc_use = padded
            else:
                nhwc_use = nhwc
            nchw = np.ascontiguousarray(nhwc_use.transpose(2, 0, 1))[None]
            raw = session.run(None, {"input": nchw})[0].reshape(-1)
            qdq = quantise_dequantise(nchw, scale, zp)
            quant_in = session.run(None, {"input": qdq})[0].reshape(-1)
            out[tag][name] = {"raw": raw.tolist(), "qdq": quant_in.tolist()}
            print(f"[{tag}/{name}] raw   = {np.round(raw, 4)}")
            print(f"[{tag}/{name}] qdq   = {np.round(quant_in, 4)}")

    ref_path = WORK / "output/stages/ort_refs.json"
    ref_path.write_text(json.dumps(out, indent=1))
    print(f"-> {ref_path}")


if __name__ == "__main__":
    main()
