#!/usr/bin/env python3
"""Simulate the "rv1106 reads the INT8 input buffer as unsigned bytes" hypothesis.

The board writes signed int8 bytes q (two's complement).  If the NPU interprets
each byte as an unsigned value (official RV1106 demos only ever use UINT8
inputs), the effective feature values become (q & 0xFF) * scale instead of
q * scale -- a sign-dependent offset of +256*scale for every negative q.

This script computes the toy_r7 output under all four combinations:
  {signed, unsigned} interpretation x {NHWC, NCHW} flatten order
so they can be compared against the board output.

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

from __future__ import annotations

import json
from pathlib import Path

import numpy as np

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",
}
IN_SCALE = 0.039216
P = (np.random.RandomState(123).randn(4032, 7) * 0.05).astype(np.float32)

# board S0 outputs for comparison
BOARD = {
    "winA": [8.4892, 4.7229, -6.7555, 2.9892, 8.4892, 8.3098, 5.5000],
    "winB": [8.4892, 8.4892, -6.4566, 1.6739, -1.7935, 8.4892, 1.0761],
}

out = {}
for name, path in WINS.items():
    nhwc = np.fromfile(path, dtype=np.float32).reshape(32, 42, 3)
    q = np.clip(np.round(nhwc / IN_SCALE), -128, 127).astype(np.int64)
    cands = {}
    for interp, values in (("signed", q * IN_SCALE), ("unsigned", (q % 256) * IN_SCALE)):
        for layout in ("nhwc", "nchw"):
            flat = values.reshape(-1) if layout == "nhwc" else values.transpose(2, 0, 1).reshape(-1)
            cands[f"{interp}_{layout}"] = (flat.astype(np.float32) @ P).tolist()
    out[name] = cands
    print(f"== {name}")
    board = np.array(BOARD[name])
    for key, val in cands.items():
        delta = np.abs(np.array(val) - board).max()
        print(f"   {key:16s} = {np.round(val, 3)}   |diff to board|={delta:8.3f}")

Path(WORK / "output/toys2/sim_unsigned.json").write_text(json.dumps(out, indent=1))
