"""Per-trial datasets and batch collation used by the prediction pipeline.

Each dataset yields one trial as
``(neural, stim, subject_id, trial_index, fs)``.  The identifiers let the pipeline
map predictions back to the correct row; the hook receives the signals only.

Every trial is loaded through ``load_subject`` with the preprocessing the
decoder was fitted under.
"""

from __future__ import annotations

from typing import Any, Dict, List, Optional, Sequence, Tuple

import torch
from torch.utils.data import Dataset

from .config import NEURAL_PREFIX, STIM_PREFIX
from .io_cnd import SubjectData, load_subject

TrialItem = Tuple[torch.Tensor, torch.Tensor, int, int, float]
CollatedBatch = Tuple[
    torch.Tensor, torch.Tensor, List[int], List[int], List[float], torch.Tensor
]


class _ChallengeDataset(Dataset[TrialItem]):
    """Load every trial of the requested subjects once, in recording order."""

    def __init__(
        self,
        data_dir: str,
        subject_ids: Sequence[int],
        preprocessing: Optional[Dict[str, Any]] = None,
        neural_prefix: str = NEURAL_PREFIX,
        stim_prefix: str = STIM_PREFIX,
    ) -> None:
        self.records: List[Tuple[SubjectData, int]] = []
        for subject_id in subject_ids:
            subject = load_subject(
                data_dir,
                subject_id,
                preprocessing,
                neural_prefix=neural_prefix,
                stim_prefix=stim_prefix,
            )
            for trial_index in range(len(subject.neural)):
                self.records.append((subject, trial_index))

    def __len__(self) -> int:
        return len(self.records)

    def __getitem__(self, index: int) -> TrialItem:
        subject, trial_index = self.records[index]
        neural = torch.as_tensor(subject.neural[trial_index], dtype=torch.float64)
        stim = torch.as_tensor(subject.stim[trial_index], dtype=torch.float64)
        return neural, stim, subject.subject_id, trial_index, subject.fs


class NJUSUSTechDataset(_ChallengeDataset):
    """NJUSUSTech2026 test set."""


class DLAADDataset(_ChallengeDataset):
    """DLAAD test set."""


def collate_trials(batch: List[TrialItem]) -> CollatedBatch:
    """Stack a batch, padding trials to the longest one.

    Returns
    -------
    neural : torch.Tensor
        ``(batch, n_channels, max_samples)``.
    stim : torch.Tensor
        ``(batch, n_streams, max_samples)``.
    subject_ids : list of int
    trial_indices : list of int
    fs_list : list of float
    lengths : torch.Tensor
        ``(batch,)`` sample length of each trial before padding.
    """
    neural, stim, subject_ids, trial_indices, fs_list = zip(*batch)
    channels = neural[0].shape[0]
    streams = stim[0].shape[0]
    lengths = torch.tensor([item.shape[1] for item in neural], dtype=torch.long)
    max_samples = int(lengths.max())

    dtype = neural[0].dtype
    neural_padded = torch.zeros(len(batch), channels, max_samples, dtype=dtype)
    stim_padded = torch.zeros(len(batch), streams, max_samples, dtype=dtype)
    for index, item in enumerate(neural):
        neural_padded[index, :, : item.shape[1]] = item
    for index, item in enumerate(stim):
        stim_padded[index, :, : item.shape[1]] = item

    return (
        neural_padded,
        stim_padded,
        list(subject_ids),
        list(trial_indices),
        list(fs_list),
        lengths,
    )
