"""How one decision window becomes one label. **Teams edit this file.**

:func:`decode_trial <challenge.hook.decode_trial>` calls
:func:`decode_single_window` once per window and hands it the model from
:func:`load_decoder <challenge.hook.load_decoder>`, the resolved grid, the
current window, everything before the window, and the labels already emitted.
The return value is one label.

The shipped body is the linear baseline: lagged embedding of the current
window, reconstruction with ``W``, Pearson correlation against every candidate
envelope over the window span, largest wins.
"""

from __future__ import annotations

from typing import Any, Dict, List

import numpy as np

from .window_correlation import window_correlation
from .time_delay_embedding import time_delay_embedding


def decode_single_window(
    model: Dict[str, Any],
    window_index: int,
    starts: np.ndarray,
    fs: float,
    seg_len: int,
    hop_samples: int,
    neural_current: np.ndarray,
    stim_current: np.ndarray,
    neural_past: np.ndarray,
    stim_past: np.ndarray,
    past_labels: List[int],
) -> int:
    """Decode ONE decision window; return one label in ``{0, 1}``.

    Parameters
    ----------
    model : dict
        What :func:`load_decoder <challenge.hook.load_decoder>` returned.
    window_index : int
        0-based index of the current window.
    starts : np.ndarray
        0-based start of every window of the trial; window ``k`` spans
        ``starts[k] : starts[k] + seg_len``. The entries before
        ``window_index`` are the previous windows of the trial.
    fs : float
        Sampling rate of the inputs.
    seg_len, hop_samples : int
        The resolved grid: window length and step, in samples.
    neural_current : np.ndarray
        ``(n_channels, seg_len)`` -- the current window.
    stim_current : np.ndarray
        ``(n_streams, seg_len)`` -- the envelopes over the same span.
    neural_past, stim_past : np.ndarray
        ``(n_channels, starts[window_index])`` / ``(n_streams, ...)`` --
        everything before the current window: every previous window's data.
    past_labels : list of int
        The labels already emitted for the previous windows, in window order
        (empty for window 0).

    A sequential decoder may keep state across the windows of one trial; the
    past arrays and ``past_labels`` carry it in. The state must not survive
    the trial: ``window_index == 0`` is the first window of a trial, and
    :func:`reset_decoder <challenge.hook.reset_decoder>` has run before it.
    A test trial must not carry information into the next trial.

    Returns
    -------
    int
        One label in ``{0, 1}``: a 0-based stream index
        (``attended-speaker-label``). A decoder that returns the attended
        direction declares ``attended-direction-label`` in
        ``submission_metadata.yaml``.
    """
    design = time_delay_embedding(
        neural_current.T, model["lags"], fs, bias=model["bias"]
    )                                        # (seg_len, n_columns)
    reconstruction = design @ model["W"]     # (seg_len,)

    n_streams = stim_current.shape[0]
    corrs = np.empty(n_streams, dtype=float)
    for stream in range(n_streams):
        corrs[stream] = window_correlation(reconstruction, stim_current[stream])

    # Constant candidate envelope -> NaN (0/0). -inf ranks it last; all-NaN
    # resolves to stream 0, as MATLAB's max().
    ranked = np.where(np.isnan(corrs), -np.inf, corrs)
    return int(np.argmax(ranked))
