"""How the model is loaded, once per run. **Teams edit this file.**

Replace :func:`load_decoder` with your own loader: build whatever object your
decoder needs (network weights, a checkpoint, the shipped linear model) and
return it. The pipeline calls this function once per run and passes the
returned object to :func:`decode_trial <challenge.hook.decode_trial>`, which
resets it once per trial (:func:`reset_decoder
<challenge.hook.reset_decoder>`) and hands it to
:func:`decode_single_window <challenge.hook.decode_single_window>`.

The shipped body loads the decoder file named in ``challenge/config.py``
(``DECODER_REL_PATH``) and validates it. Keep one property in any
replacement:

* load once -- the function caches, and repeated calls return the same object.
"""

from __future__ import annotations

import os
from typing import Any, Dict, List, TypedDict

import numpy as np

from ..config import DECODER_REL_PATH


class DecoderModel(TypedDict):
    """The model mapping :func:`load_decoder` returns.

    The shipped keys; a replacement loader returns whatever its decoder needs.

    ==================  =====================================================
    ``W``               ``(n_channels * n_lags (+1 if bias),)`` backward
                        decoder, channel-major, lags in the order
                        :func:`~challenge.hook.time_delay_embedding` emits
                        them
    ``lags``            ``[start, end]`` lag window in seconds
    ``bias``            whether the design matrix carries a constant column
    ``fs``              sampling rate the lags are quantised on
    ``window_seconds``  decision window length
    ``n_channels``      number of channels the design matrix was built for
    ``channel_labels``  cellstr, one per design-matrix column group; the
                        pipeline compares it with the channels the
                        preprocessing produced
    ``preprocessing``   ``loadSubject`` options the weights were fitted under;
                        the pipeline applies them before the hook is called
                        (optional; absent falls back to the loadSubject defaults)
    ==================  =====================================================
    """

    W: np.ndarray
    lags: np.ndarray
    bias: bool
    fs: float
    window_seconds: float
    n_channels: int
    channel_labels: List[str]
    preprocessing: Dict[str, Any]


_MODEL_CACHE: Dict[str, Any] | None = None


def load_decoder() -> Dict[str, Any]:
    """Load ``matlab/reference_decoder.mat`` once and unwrap it.

    Raises with the field name when the file is incomplete, and with the
    expected layout when ``W`` does not match ``Leeg``/``bias``/``channelLabels``.
    """
    global _MODEL_CACHE
    if _MODEL_CACHE is None:
        import scipy.io as sio

        decoder_path = os.path.join(
            os.path.dirname(os.path.dirname(os.path.dirname(
                os.path.abspath(__file__)))),
            DECODER_REL_PATH,
        )
        payload = sio.loadmat(decoder_path)

        required = (
            "W", "Leeg", "bias", "fs", "windowSeconds", "hopSeconds", "channelLabels",
        )
        missing = [name for name in required if name not in payload]
        if missing:
            raise ValueError(
                "%s is missing %s. Write a complete file with matlab/packDecoder.m, "
                "or refit the baseline with matlab/makeReference.m."
                % (decoder_path, ", ".join(missing))
            )

        def scalar(name: str) -> Any:
            return np.asarray(payload[name]).reshape(-1)[0]

        weights = np.asarray(payload["W"], dtype=float)
        if weights.ndim != 2 or weights.shape[1] != 1:
            raise ValueError(
                "%s: model.W is %s; the test-phase format holds one column (one attended "
                "envelope). Reduce a multi-target fit to one before scoring it."
                % (decoder_path, "x".join(str(size) for size in weights.shape))
            )
        fs = float(scalar("fs"))
        lags = np.asarray(payload["Leeg"], dtype=float).reshape(-1)
        has_bias = bool(scalar("bias"))
        n_lags = _n_lags(lags, fs)
        # The bias term adds one row to W, not one channel; it comes off before
        # the row count is divided by the lag count. MATLAB's checkDecoder()
        # computes the same expected size, bias included.
        n_channels, spare = divmod(int(weights.shape[0]) - int(has_bias), n_lags)
        if spare != 0 or n_channels < 1:
            raise ValueError(
                "%s: model.W has %d rows. With %d lags and bias=%s, the row count "
                "minus the bias row has to be a whole number of channels "
                "(%d rows per channel); it is not. Re-pack W, Leeg and "
                "channelLabels from one fit."
                % (decoder_path, weights.shape[0], n_lags, has_bias, n_lags)
            )
        _MODEL_CACHE = {
            "W": weights.reshape(-1),
            "lags": lags,
            "bias": has_bias,
            "fs": fs,
            "window_seconds": float(scalar("windowSeconds")),
            "n_channels": n_channels,
            "channel_labels": _cellstr(payload.get("channelLabels")),
            "preprocessing": _preprocessing_options(payload),
        }
    return _MODEL_CACHE


def _n_lags(lags: np.ndarray, fs: float) -> int:
    return int(np.ceil(lags[1] * fs)) - int(np.floor(lags[0] * fs)) + 1


def _preprocessing_options(payload: Dict[str, Any]) -> Dict[str, Any]:
    """The loadSubject() options the weights were fitted under."""
    if "preprocessing" not in payload:
        return {}
    block = payload["preprocessing"]
    if getattr(block, "size", 0) == 0:
        return {}
    block = block[0, 0]
    options: Dict[str, Any] = {}
    for name in block.dtype.names:
        value = block[name]
        if name in ("channelSelection",):
            items: List[str] = []
            for item in np.asarray(value).reshape(-1):
                while isinstance(item, np.ndarray):
                    if item.size == 0:
                        item = ""
                        break
                    item = item.reshape(-1)[0]
                items.append(str(item))
            options[name] = items
        elif name == "targetFs":
            array = np.asarray(value).reshape(-1)
            options[name] = None if array.size == 0 else float(array[0])
        else:
            array = np.asarray(value).reshape(-1)
            options[name] = None if array.size == 0 else str(array[0])
    return options


def _cellstr(value: Any) -> List[str]:
    """Flatten a MATLAB cellstr / char array as scipy hands it back."""
    if value is None:
        return []
    array = np.asarray(value)
    if array.size == 0:
        return []
    if array.dtype.kind in "US":
        return [str(item) for item in array.reshape(-1)]
    out = []
    for item in array.reshape(-1):
        while isinstance(item, np.ndarray):
            if item.size == 0:
                item = ""
                break
            item = item.reshape(-1)[0]
        out.append(str(item))
    return out
