"""The fixed decode loop: batch handling, the decision grid, per-window slicing and
the causal expansion. Do not edit; the edit points are
:func:`load_decoder <challenge.hook.load_decoder>`,
:func:`reset_decoder <challenge.hook.reset_decoder>` and
:func:`decode_single_window <challenge.hook.decode_single_window>`. The
pipeline loads the model once and passes it in as ``model``.
"""

from __future__ import annotations

import warnings
from typing import Any, Dict, List, Optional, Sequence, Union

import numpy as np

from .. import config
from .decode_single_window import decode_single_window
from .expand_to_samples import expand_to_samples
from .guess_label import guess_label
from .reset_decoder import reset_decoder
from .window_starts import window_starts

DecoderOutput = Union[np.ndarray, List[np.ndarray]]


def decode_trial(
    model: Dict[str, Any],
    neural: np.ndarray,
    stim: np.ndarray,
    fs: float,
    lengths: Optional[Sequence[int]] = None,
) -> DecoderOutput:
    """Decode one trial or a batch of trials.

    ``model`` is what :func:`load_decoder <challenge.hook.load_decoder>`
    returned; the pipeline loads it once and passes it in.

    Per trial: the decision grid is resolved, every window is sliced and
    decoded through :func:`decode_single_window`, and
    :func:`expand_to_samples` spreads the window labels onto samples; one
    label per sample at ``fs``, in input order. Window ``k``'s label is
    assigned to the sample ``window end - 1000 ms``; the latest usable window
    wins, and the hop sets the spacing.

    A label is a 0-based STREAM INDEX in the shipped decoder
    (``attended-speaker-label`` with two streams). A decoder that returns a
    direction declares ``attended-direction-label`` in ``submission_metadata.yaml``.
    More than two streams are rejected.

    The decision grid: ``WINDOW_SECONDS`` (``None`` uses the value in the
    model; a value overrides it with a warning) and ``HOP_SAMPLES`` (1) in
    ``challenge/config.py``.

    Trials decode independently of each other. The model loads once for the
    whole run and :func:`reset_decoder <challenge.hook.reset_decoder>` runs
    before every trial's first window; any state a decoder keeps across the
    windows of one trial is back at its trained initial values there
    (``window_index == 0`` in :func:`decode_single_window`).

    Parameters
    ----------
    model : dict
        What :func:`load_decoder <challenge.hook.load_decoder>` returned.

    neural : np.ndarray
        ``(n_channels, n_samples)`` for one trial, or
        ``(batch, n_channels, n_samples)`` for a padded batch.
    stim : np.ndarray
        ``(n_streams, n_samples)`` or ``(batch, n_streams, n_samples)``
        auditory envelopes aligned to ``neural``.
    fs : float
        Sampling rate of the inputs, after the pipeline's preprocessing.
    lengths : sequence of int, optional
        Sample length of each trial when ``neural`` carries a padded batch.

    Returns
    -------
    np.ndarray or list of np.ndarray
        Per-sample label (0/1) at ``fs``: one label per sample the hook
        received.  A single trial returns one vector; a batch returns a list,
        one vector per trial, in input order.
    """
    # fs must match the model.
    if float(fs) != float(model["fs"]):
        raise ValueError(
            "the model was fitted at %g Hz; the trial arrived at %g Hz. Decode at "
            "preprocessing targetFs." % (model["fs"], fs)
        )

    single_trial = neural.ndim == 2
    neural_batch = neural[np.newaxis, ...] if single_trial else neural
    stim_batch = stim[np.newaxis, ...] if single_trial else stim

    # The streams must fit a 0/1 label, and the channels must match the model.
    if stim_batch.shape[1] > 2:
        raise ValueError(
            "%d candidate streams: a per-sample label of 0/1 can only encode two. Map "
            "your %d-way decision onto the attended side before returning it."
            % (stim_batch.shape[1], stim_batch.shape[1])
        )
    if neural_batch.shape[1] != model["n_channels"]:
        raise ValueError(
            "the model expects %d channels; received %d. Use the preprocessing the "
            "weights were fitted under." % (model["n_channels"], neural_batch.shape[1])
        )

    n_trials = int(neural_batch.shape[0])
    trial_lengths: Sequence[int] = (
        [int(neural_batch.shape[2])] * n_trials if lengths is None else lengths
    )

    # The model records its window in seconds; every step below works in
    # samples. WINDOW_SECONDS in challenge/config.py overrides the model
    # window with a warning; the weights stay valid, the decision grid changes.
    if config.WINDOW_SECONDS is None:
        window_seconds = model["window_seconds"]
    else:
        window_seconds = config.WINDOW_SECONDS
        if window_seconds != model["window_seconds"]:
            warnings.warn(
                "WINDOW_SECONDS %g in challenge/config.py overrides the %g s in "
                "the model; the weights stay valid, the decision grid changes."
                % (window_seconds, model["window_seconds"])
            )
    seg_len = int(round(window_seconds * fs))
    hop_samples = int(config.HOP_SAMPLES)
    expand_lookahead = int(round(config.MAX_LOOKAHEAD_MS / 1000 * fs))

    labels: List[np.ndarray] = []
    for trial_index in range(n_trials):
        model = reset_decoder(model)
        n_samples = int(trial_lengths[trial_index])
        # Padding of a shorter trial stays out of the decoder.
        trial_neural = neural_batch[trial_index, :, :n_samples]
        trial_stim = stim_batch[trial_index, :, :n_samples]
        if trial_stim.shape[1] != n_samples:
            raise ValueError(
                "trial %d: neural has %d samples but stim has %d; they must "
                "cover the same trial." % (trial_index, n_samples, trial_stim.shape[1])
            )

        starts = window_starts(n_samples, seg_len, hop_samples)
        if trial_stim.shape[0] == 0 or starts.size == 0:
            # A trial shorter than one window: every sample takes the same
            # guess label. Keep windows at or below 60 s -- the shortest test
            # trial is 60 s.
            labels.append(
                np.full(n_samples, guess_label(trial_neural), dtype=int)
            )
            continue

        window_labels: List[int] = []
        for k, off in enumerate(starts.tolist()):
            # The current window; everything before it is passed as the past
            # arrays.
            neural_current = trial_neural[:, off:off + seg_len]
            stim_current = trial_stim[:, off:off + seg_len]
            label = decode_single_window(
                model, k, starts, fs, seg_len, hop_samples,
                neural_current, stim_current,
                trial_neural[:, :off], trial_stim[:, :off],
                list(window_labels),
            )
            window_labels.append(label)

        per_sample = expand_to_samples(
            window_labels,
            seg_len,
            hop_samples,
            lookahead=expand_lookahead,
            n_samples=n_samples,
        )
        # The samples before the first label is assigned (window end - 1000 ms)
        # have no decision yet. They take one guess
        # drawn from the trial's own content: deterministic, uniform over
        # {0,1}, and needing no trial identity.
        per_sample[np.isnan(per_sample)] = guess_label(trial_neural)
        labels.append(per_sample.astype(int))

    return labels[0] if single_trial else labels
