"""The causal window-to-sample mapping. Fixed pipeline helper; do not edit."""

from __future__ import annotations

from typing import Optional, Union

import numpy as np


def expand_to_samples(
    window_label: Union[np.ndarray, "list[int]"],
    seg_len: int,
    hop_len: int,
    lookahead: int = 0,
    n_samples: Optional[int] = None,
) -> np.ndarray:
    """Spread per-window decisions onto every sample, causally.

    Python counterpart of ``matlab/expandToSamples.m``. Window ``k`` (1-based)
    spans samples ``(k-1)*hop_len+1`` to ``e_k = (k-1)*hop_len+seg_len``; it
    labels sample ``s`` once ``e_k <= s - 1 + lookahead``; the latest such
    window wins::

        j(s) = floor((s - 1 + lookahead - seg_len) / hop_len) + 1

    clamped to ``[1, n_windows]``: trailing samples take the last window that
    ended. Samples with ``j(s) < 1`` are ``NaN``.

    Parameters
    ----------
    window_label : sequence of int
        One label per decision window, in window order.
    seg_len : int
        Window length in native samples.
    hop_len : int
        Samples between window starts, in native samples.
    lookahead : int, optional
        Extra samples a window may read into the future. ``0`` keeps the
        mapping strictly causal: window ``k`` labels only samples that start
        after window ``k`` has ended.
    n_samples : int, optional
        Trial length. Default: ``(n_windows - 1) * hop_len + seg_len``.

    Returns
    -------
    np.ndarray
        Per-sample label of length ``n_samples``. Samples before the first
        label (``seg_len - lookahead``, 0-based) carry ``NaN``; the caller
        fills them before scoring.
    """
    labels = np.asarray(window_label, dtype=float).reshape(-1)
    n_windows = int(labels.size)
    if n_samples is None:
        n_samples = (n_windows - 1) * hop_len + seg_len
    n_samples = int(n_samples)
    if n_samples < 0:
        raise ValueError("n_samples must not be negative (got %d)" % n_samples)

    sample_index = np.arange(n_samples)
    window_index = (sample_index + lookahead - seg_len) // hop_len + 1
    window_index = np.minimum(window_index, n_windows)

    sample_label = np.full(n_samples, np.nan, dtype=float)
    valid = window_index >= 1
    sample_label[valid] = labels[window_index[valid] - 1]
    return sample_label
