"""The lagged design matrix of the shipped linear baseline.

Fixed pipeline helper; do not edit. It serves the shipped body of
``decode_single_window``; a replacement decoder brings its own frontend.
"""

from __future__ import annotations

from typing import Sequence, Union

import numpy as np


def time_delay_embedding(
    signal: np.ndarray,
    lags: Union[Sequence[float], np.ndarray],
    fs: float,
    bias: bool = True,
) -> np.ndarray:
    """Time-delay embedding of a multi-channel signal.

    Python counterpart of MATLAB ``timeDelayEmbedding.m``, column for column.

    Parameters
    ----------
    signal : np.ndarray
        ``(n_samples, n_channels)``.  Time first, channels second -- the
        MATLAB function's orientation.
    lags : sequence or ndarray of 2 floats
        ``[start, end]`` lag window in seconds.  Positive lags are future
        samples, negative lags are past samples.
    fs : float
        Sampling rate.
    bias : bool, optional
        Append a constant column of ones. The default matches
        ``timeDelayEmbedding.m``; pass ``False`` for a decoder fitted without one.

    Lags reaching outside the signal read as zeros.

    Returns
    -------
    np.ndarray
        ``(n_samples, n_channels * n_lags (+1))``.  Columns are CHANNEL-MAJOR,
        and inside one channel the lags run from the END of the window down to
        its start, the order ``toeplitz`` produces.  ``W``
        is indexed by this order.
    """
    lag_array = tuple(np.asarray(lags, dtype=float).reshape(-1))
    if len(lag_array) != 2:
        raise ValueError("lags must be [start, end] in seconds (got %r)" % (lags,))
    if lag_array[0] > lag_array[1]:
        raise ValueError("lags must satisfy start <= end (got %r)" % (lags,))

    lag_start = int(np.floor(lag_array[0] * fs))
    lag_end = int(np.ceil(lag_array[1] * fs))
    lag_samples = list(range(lag_end, lag_start - 1, -1))   # descending, as toeplitz

    n_samples, n_channels = signal.shape
    n_columns = len(lag_samples) * n_channels + int(bool(bias))
    design = np.zeros((n_samples, n_columns), dtype=float)

    for channel in range(n_channels):
        column = signal[:, channel]
        offset = channel * len(lag_samples)
        for position, lag in enumerate(lag_samples):
            target = design[:, offset + position]
            if lag >= 0:
                if lag < n_samples:
                    target[: n_samples - lag] = column[lag:]
            else:
                if -lag < n_samples:
                    target[-lag:] = column[: n_samples + lag]

    if bias:
        design[:, -1] = 1.0
    return design
