"""Prediction pipeline: load trials, call the hook, write label CSVs.

Data handling, the batch loop and the CSV format live here; decoding lives in
:func:`challenge.hook.decode_trial`.
"""

from __future__ import annotations

import argparse
import csv
import os
from typing import Any, Callable, Dict, List, Optional, Tuple, Type

import numpy as np
from torch.utils.data import DataLoader

from .config import (
    LABEL_COLUMNS,
    LABEL_FS,
    PREFERRED_PREFIXES,
    PREDICTION_NAME_FMT,
    RAW_PREFIXES,
    STIM_PREFIX,
)
from .datasets import DLAADDataset, NJUSUSTechDataset, _ChallengeDataset, collate_trials
from .hook import DecoderOutput, load_decoder, decode_trial

_DATASET_REGISTRY: Dict[str, Type[_ChallengeDataset]] = {
    "nju": NJUSUSTechDataset,
    "dlaad": DLAADDataset,
}


def resolve_prefixes(data_dir: str) -> Tuple[str, str]:
    """Return ``(neural_prefix, stim_prefix)`` to read in ``data_dir``.

    ``pre_*`` when any subject has it, otherwise ``dataSub`` / ``dataStim``; same
    rule as ``runPredictions>resolvePrefixes``. ``pre_*`` is the filtered 32 Hz
    copy, ``dataSub*`` the unfiltered one.
    """
    if _has_subject_file(data_dir, PREFERRED_PREFIXES[0]):
        return PREFERRED_PREFIXES
    return RAW_PREFIXES


def _has_subject_file(data_dir: str, prefix: str) -> bool:
    """True when ``<prefix><digits>.mat`` exists, whatever the subject number."""
    try:
        names = os.listdir(data_dir)
    except OSError:
        return False
    for name in names:
        if not (name.startswith(prefix) and name.endswith(".mat")):
            continue
        if name[len(prefix) : -len(".mat")].isdigit():
            return True
    return False


def discover_subjects(data_dir: str, neural_prefix: str) -> List[int]:
    """Subject ids from ``<prefix><digits>.mat``, ascending.

    Raises when the directory is missing or holds no ``<prefix><digits>.mat``.
    """
    if not os.path.isdir(data_dir):
        raise ValueError(
            "%s is not a directory. --data_dir is the dataCND folder of one test "
            "set, e.g. <set>/dataCND." % data_dir
        )
    ids = []
    for name in os.listdir(data_dir):
        if not (name.startswith(neural_prefix) and name.endswith(".mat")):
            continue
        stem = name[len(neural_prefix) : -len(".mat")]
        if not stem.isdigit():
            print("warning: skipping %s (no <prefix><digits>.mat subject id)" % name)
            continue
        ids.append(int(stem))
    if not ids:
        raise ValueError(
            "%s holds no %s<digits>.mat. Expected one per subject."
            % (data_dir, neural_prefix)
        )
    return sorted(ids)


def native_trial_lengths(data_dir: str, subject_id: int) -> List[int]:
    """Per-trial sample count at 128 Hz, read from the native stimulus file.

    Empty list when the native file is absent or at another rate.
    """
    native_file = os.path.join(data_dir, f"{STIM_PREFIX}{subject_id}.mat")
    if not os.path.exists(native_file):
        return []
    import scipy.io as sio

    payload = sio.loadmat(native_file)
    if "stim" not in payload:
        return []
    stim = payload["stim"][0, 0]
    if "fs" not in stim.dtype.names:
        return []
    if float(np.asarray(stim["fs"]).reshape(-1)[0]) != LABEL_FS:
        return []
    data = stim["data"]
    n_trials = data.shape[1]
    return [int(np.asarray(data[0, t]).size) for t in range(n_trials)]


def zero_order_hold(labels: np.ndarray, fs_in: float, fs_out: float, n_out: int) -> np.ndarray:
    """Hold categorical labels onto a finer grid.

    Sample ``j`` of the output takes input sample ``floor(j*fs_in/fs_out)``,
    clamped to the last input sample, exactly as ``exportPredictions>buildGrid``
    does in the training package.
    """
    labels = np.asarray(labels).reshape(-1)
    n_in = labels.size
    n_out = max(1, int(round(n_out)))
    source = np.minimum(
        n_in, np.floor(np.arange(n_out) * fs_in / fs_out).astype(int) + 1
    )
    return labels[source - 1]


def _check_channel_layout(dataset: _ChallengeDataset, neural_prefix: str, model: Dict[str, Any]) -> None:
    """Compare the channels the preprocessing produced with the ones the fit used.

    Channel labels, in order, against ``decoder.channelLabels``.
    """
    model_labels = model.get("channel_labels") or []
    expected = [name.lower() for name in model_labels]
    if not expected:
        return
    checked = set()
    for subject, _ in dataset.records:
        if subject.subject_id in checked:
            continue
        checked.add(subject.subject_id)
        produced = [name.lower() for name in subject.chan_labels]
        if not produced:
            continue
        if len(produced) != len(expected):
            raise ValueError(
                "subject %d: the preprocessing of %s produced %d channels but the "
                "decoder wants %d. Run with the channelSelection the weights were "
                "fitted under."
                % (subject.subject_id, neural_prefix, len(produced), len(expected))
            )
        position = next(
            (i for i, (a, b) in enumerate(zip(produced, expected)) if a != b), None
        )
        if position is not None:
            raise ValueError(
                "subject %d: channel %d is %r but the decoder expects %r. The same "
                "channels in a different order permute the design matrix columns."
                % (
                    subject.subject_id,
                    position,
                    subject.chan_labels[position],
                    model_labels[position],
                )
            )


def _dataset_from_path(data_dir: str) -> Type[_ChallengeDataset]:
    """Pick the dataset class from the last two path components, or stop and ask.

    ``.../nju/dataCND`` and ``.../dlaad/dataCND`` resolve without the flag. Any
    other path stops and asks for ``--dataset``. Both classes load identically.
    """
    trail = "/".join(data_dir.replace("\\", "/").rstrip("/").split("/")[-2:]).lower()
    for name, dataset_class in _DATASET_REGISTRY.items():
        if name in trail:
            return dataset_class
    raise ValueError(
        "--dataset auto could not be resolved from %r: the last two path components "
        "name none of %s. Pass --dataset explicitly, or keep the set name in the "
        "folder path (…/<nju>/dataCND, …/<dlaad>/dataCND)."
        % (data_dir, sorted(_DATASET_REGISTRY))
    )


def run_predictions(
    data_dir: str,
    output_dir: str,
    dataset_name: str = "auto",
    subject_ids: Optional[List[int]] = None,
    batch_size: int = 8,
    decoder: Callable[..., DecoderOutput] = decode_trial,
    preprocessing: Optional[Dict[str, Any]] = None,
    file_prefixes: Optional[Tuple[str, str]] = None,
) -> Dict[int, str]:
    """Run ``decoder`` over every trial and write one CSV per subject.

    Returns a mapping ``subject_id -> csv_path``.
    """
    # The model loads once for the whole run and is passed down.
    model = load_decoder()

    if file_prefixes is None:
        file_prefixes = resolve_prefixes(data_dir)
    neural_prefix, stim_prefix = file_prefixes

    if preprocessing is None:
        # The options the shipped decoder was fitted under.
        preprocessing = model.get("preprocessing") or None

    if subject_ids is None:
        subject_ids = discover_subjects(data_dir, neural_prefix)

    if dataset_name == "auto":
        # The test set is named after its parent (…/nju/dataCND).
        dataset_class = _dataset_from_path(data_dir)
    else:
        dataset_class = _DATASET_REGISTRY.get(dataset_name)
        if dataset_class is None:
            raise ValueError(
                "unknown dataset %r; expected one of %s or 'auto'"
                % (dataset_name, sorted(_DATASET_REGISTRY))
            )
    dataset = dataset_class(
        data_dir,
        subject_ids,
        preprocessing,
        neural_prefix=neural_prefix,
        stim_prefix=stim_prefix,
    )
    loader = DataLoader(
        dataset,
        batch_size=batch_size,
        shuffle=False,
        collate_fn=collate_trials,
    )

    _check_channel_layout(dataset, neural_prefix, model)

    predictions: Dict[Tuple[int, int], np.ndarray] = {}
    # One rate per subject, recorded as the trials are loaded; the CSV step holds each
    # subject onto its own grid.
    subject_fs: Dict[int, float] = {}
    for neural, stim, batch_subject_ids, batch_trial_indices, fs_list, lengths in loader:
        neural_np = neural.numpy()
        stim_np = stim.numpy()
        # One rate per batch.
        batch_rates = {float(rate) for rate in fs_list}
        if len(batch_rates) != 1:
            raise ValueError(
                "one batch holds trials at %s Hz; the hook takes a single rate per "
                "batch. Load one rate per run, or decode these batches separately."
                % sorted(batch_rates)
            )
        batch_labels = decoder(
            model,
            neural_np,
            stim_np,
            float(fs_list[0]),
            [int(length) for length in lengths],
        )
        for index, (subject_id, trial_index) in enumerate(zip(batch_subject_ids, batch_trial_indices)):
            labels = np.asarray(batch_labels[index]).reshape(-1)
            expected = int(lengths[index])
            # One label per sample handed to the hook.
            if labels.size != expected:
                raise ValueError(
                    f"subject {subject_id} trial {trial_index}: hook returned "
                    f"{labels.size} labels for {expected} input samples at "
                    f"{float(fs_list[0]):g} Hz"
                )
            # Labels are 0 or 1.
            if not np.all((labels == 0) | (labels == 1)):
                raise ValueError(
                    f"subject {subject_id} trial {trial_index}: labels must be 0 "
                    f"or 1, got values in [{labels.min():g}, {labels.max():g}]"
                )
            rate = float(fs_list[index])
            if subject_id in subject_fs and subject_fs[subject_id] != rate:
                raise ValueError(
                    f"subject {subject_id} was loaded at both "
                    f"{subject_fs[subject_id]:g} and {rate:g} Hz; one subject has to "
                    f"have one rate for its labels to share one grid"
                )
            subject_fs[subject_id] = rate
            predictions[(subject_id, trial_index)] = labels.astype(np.int64)

    os.makedirs(output_dir, exist_ok=True)
    written: Dict[int, str] = {}
    for subject_id in subject_ids:
        trial_indices_present = sorted(t for (s, t) in predictions if s == subject_id)
        if not trial_indices_present:
            continue
        native_lengths = native_trial_lengths(data_dir, subject_id)
        if subject_id not in subject_fs:
            raise ValueError(
                "subject %d has predictions but no recorded input rate; the loader "
                "and the CSV writer disagree about which trials were decoded"
                % subject_id
            )
        fs_in = subject_fs[subject_id]
        rows: List[Tuple[int, int, int]] = []
        for trial_index in trial_indices_present:
            labels = predictions[(subject_id, trial_index)]
            # Row count: native length when available, otherwise labelFs/fs_in
            # times the decoded length.
            if trial_index < len(native_lengths):
                n_out = native_lengths[trial_index]
            else:
                n_out = max(1, int(round(labels.size * LABEL_FS / fs_in)))
            labels = zero_order_hold(labels, fs_in, LABEL_FS, n_out)
            for time_index, label in enumerate(labels):
                rows.append((time_index, int(label), trial_index))
        csv_path = os.path.join(output_dir, PREDICTION_NAME_FMT.format(subject_id))
        with open(csv_path, "w", newline="") as handle:
            writer = csv.writer(handle, lineterminator="\n")
            writer.writerow(LABEL_COLUMNS)
            writer.writerows(rows)
        written[subject_id] = csv_path
    return written


def main() -> None:
    """Command-line entry point for prediction generation."""
    parser = argparse.ArgumentParser(
        description="Write per-sample label CSVs for one test set."
    )
    parser.add_argument(
        "--data_dir",
        required=True,
        help="<set>/dataCND: the folder holding dataSubN.mat / dataStimN.mat "
        "(128 Hz) and their 32 Hz pre_ copies. Input names carry the subject "
        "number without zero padding (dataSub1.mat)",
    )
    parser.add_argument(
        "--output_dir",
        required=True,
        help="Folder for test_sample_NNN.csv. Use one folder per set "
        "(<out>/nju, <out>/dlaad)",
    )
    parser.add_argument(
        "--dataset",
        default="auto",
        choices=["auto", "nju", "dlaad"],
        help="Reader class. Both classes read the same files in --data_dir. "
        "auto resolves the name from the last two path components",
    )
    parser.add_argument(
        "--subjects", default=None, help="Comma-separated subject ids (default: all)"
    )
    parser.add_argument("--batch_size", type=int, default=8)
    args = parser.parse_args()

    subject_ids = [int(s) for s in args.subjects.split(",")] if args.subjects else None
    written = run_predictions(
        args.data_dir,
        args.output_dir,
        args.dataset,
        subject_ids,
        args.batch_size,
    )
    for subject_id, path in sorted(written.items()):
        print(f"subject {subject_id:03d} -> {path}")


if __name__ == "__main__":
    main()
