"""VLAAI_ws: the weight-shared VLAAI stimulus-reconstruction network, as a single self-contained file.

Depends on PyTorch only (no einops, no pydantic, no SuperHuge package). Module names, parameter names and shapes are
identical to the network the experiments train (`decoders.Net("vlaai_ws", ...)`), so the saved weights in `models/*.pt`
and the `state_dict` of this file are interchangeable (checked: strict load in both directions, equal outputs).

Architecture (defaults = the configuration used in all experiments)
-------------------------------------------------------------------
input  x: (B, T, C)   EEG window, T = fs * window_s samples (160 for 5 s at 32 Hz), C = 58 channels
  1. proj      1x1 convolution C -> K (K = 64); this is the "patch" that makes weight sharing possible
  2. block     ONE block applied nb_blocks (4) times with the SAME weights:
                 for i in range(nb_blocks):
                     if use_skip and i > 0:  h = h + x_proj          # skip from the projected input
                     h = block(h)
               block = extractor -> dropout -> output_context -> linear mix (K -> K, with bias)
                 extractor:      3 x [ZeroPad right (k-1), Conv1d(K, K, k) with max-norm 2, LayerNorm([K, T]), ELU, Dropout]
                                 kernel sizes 3, 7, 11   (the 4th size of kernel_sizes=[3, 7, 11, 15] is never used:
                                 num_kernels=[K] is expanded to num_layers=3 and zip() stops at 3)
                 output_context: ZeroPad LEFT (16), Conv1d(K, K, 17) with max-norm 2, LayerNorm([K, T]), ELU, Dropout
  3. head      linear K -> F (no bias): one output channel per reconstruction target (env, onset, dom)
output y: (B, T, F), or (B, T) when F == 1

What is NOT in the network
--------------------------
* The network is NOT causal inside its window: the extractor pads on the right, so an output sample sees up to
  (2 + 6 + 10) = 18 samples of the future per block, 72 samples (2.25 s at 32 Hz) over the 4 blocks, limited only by
  the end of the window. Causality (the 1-second look-ahead rule) comes from HOW the output is read: `causal_reconstruct` below reads
  only the last hop-sized block that lies `future` samples before the window end, so every output sample uses at most
  `future + hop` = 24 samples (0.75 s at 32 Hz) of future EEG.
* The input length must equal fs * window_s: LayerNorm([K, T]) has a learnable (K, T) affine, so T is fixed by the weights.
* Loss, target construction, evidence (correlation of the reconstruction with each talker), the HMM and the fusion with
  the direct classifier are not here; see decoders.py, common_exp.py, score.py.
* The 10-s direct classifier is this backbone applied to the channel-concatenation [EEG (58), stream A (3), stream B (3)]
  with num_channels = 64, window_s = 10, nb_blocks = 3, followed by a (K -> 1) linear read-out (see direct_classifier.py).

Usage
-----
    model = VLAAIwsDecoder(num_channels=58, n_targets=3)           # 5-s window, 4 blocks, 64 filters, 3 targets
    y = model(torch.randn(8, 160, 58))                              # (8, 160, 3)
    sd = torch.load("models/pretrain_spk_vlaai_ws_s0.pt")           # head has 2 targets (env, onset)
    VLAAIwsDecoder(num_channels=58, n_targets=2).load_state_dict(sd)
    rec = causal_reconstruct(model, eeg_trial)                      # (T_trial, 3), <= 0.75 s look-ahead per sample
"""
from __future__ import annotations

import math
from typing import Sequence

import torch
from torch import nn


class MaxNormConv1d(nn.Module):
    """Conv1d whose filters are renormalised to L2 norm <= max_norm before every forward pass (as in the package).
    Note: like the original, the renormalisation overwrites weight.data in place, also in eval mode."""

    def __init__(self, in_channels: int, out_channels: int, kernel_size: int, max_norm: float | None = 2.0):
        super().__init__()
        self._conv = nn.Conv1d(in_channels, out_channels, kernel_size)
        self._max_norm = max_norm

    def forward(self, x: torch.Tensor) -> torch.Tensor:
        if self._max_norm is not None:
            self._conv.weight.data = torch.renorm(self._conv.weight.data, p=2, dim=0, maxnorm=self._max_norm)
        return self._conv(x)


class ChannelMix(nn.Module):
    """y[b, c, t] = sum_k x[b, k, t] W[k, c] + bias[c]  (an EinMix 'b k t -> b c t'; parameters `weight` (K, C), `bias` (1, C, 1))."""

    def __init__(self, in_features: int, out_features: int):
        super().__init__()
        self.weight = nn.Parameter(torch.empty(in_features, out_features).uniform_(-math.sqrt(3 / in_features), math.sqrt(3 / in_features)))
        self.bias = nn.Parameter(torch.empty(1, out_features, 1).uniform_(-math.sqrt(1 / in_features), math.sqrt(1 / in_features)))

    def forward(self, x: torch.Tensor) -> torch.Tensor:                      # (B, K, T) -> (B, C, T)
        return torch.einsum("bkt,kc->bct", x, self.weight) + self.bias


def _extractor(num_kernels: Sequence[int], kernel_sizes: Sequence[int], in_channels: int, time_dim: int, dropout: float) -> nn.Sequential:
    layers = nn.Sequential()
    for i, (n_out, k) in enumerate(zip(num_kernels, kernel_sizes)):
        layers.append(nn.Sequential(
            nn.ZeroPad1d((0, k - 1)),                                       # right padding: looks k - 1 samples ahead
            MaxNormConv1d(in_channels if i == 0 else num_kernels[i - 1], n_out, k),
            nn.LayerNorm([n_out, time_dim]),
            nn.ELU(),
            nn.Dropout(dropout),
        ))
    return layers


def _output_context(channels: int, kernel_size: int, time_dim: int, dropout: float) -> nn.Sequential:
    return nn.Sequential(
        nn.ZeroPad1d((kernel_size - 1, 0)),                                 # left padding: only looks back
        MaxNormConv1d(channels, channels, kernel_size),
        nn.LayerNorm([channels, time_dim]),
        nn.ELU(),
        nn.Dropout(dropout),
    )


class VLAAIwsBackbone(nn.Module):
    """proj (1x1 conv) + one weight-shared VLAAI block applied nb_blocks times. (B, T, C) -> (B, T, K)."""

    def __init__(self, num_channels: int = 58, fs: int = 32, window_s: float = 5.0, nb_blocks: int = 4,
                 num_kernels: int = 64, kernel_sizes: Sequence[int] = (3, 7, 11), output_context_kernel_size: int = 17,
                 use_skip: bool = True, dropout: float = 0.0):
        super().__init__()
        self.time_dim = int(round(fs * window_s))
        self.nb_blocks, self.use_skip, self.out_features = nb_blocks, use_skip, num_kernels
        self.proj = nn.Conv1d(num_channels, num_kernels, 1)
        self.block = nn.Sequential(
            _extractor([num_kernels] * len(kernel_sizes), kernel_sizes, num_kernels, self.time_dim, dropout),
            nn.Dropout(dropout),
            _output_context(num_kernels, output_context_kernel_size, self.time_dim, dropout),
            ChannelMix(num_kernels, num_kernels),
        )

    def forward(self, x: torch.Tensor) -> torch.Tensor:
        if x.shape[1] != self.time_dim:
            raise ValueError(f"input has {x.shape[1]} samples, the network was built for {self.time_dim}")
        x = self.proj(x.transpose(1, 2))                                    # (B, C, T) -> (B, K, T)
        h = x
        for i in range(self.nb_blocks):
            if self.use_skip and i > 0:
                h = h + x
            h = self.block(h)                                               # the same weights every time
        return h.transpose(1, 2)                                            # (B, T, K)


class LinearHead(nn.Module):
    """y[b, t, f] = sum_k h[b, t, k] W[k, f] (no bias; parameter `weight` (K, F))."""

    def __init__(self, in_features: int, out_features: int):
        super().__init__()
        self.weight = nn.Parameter(torch.empty(in_features, out_features).uniform_(-math.sqrt(3 / in_features), math.sqrt(3 / in_features)))

    def forward(self, h: torch.Tensor) -> torch.Tensor:
        return torch.einsum("btk,kf->btf", h, self.weight)


class VLAAIwsDecoder(nn.Module):
    """Backbone + linear head: the stimulus-reconstruction decoder used in all experiments.

    forward(x): x (B, T, C) float EEG -> (B, T, n_targets), or (B, T) when n_targets == 1.
    """

    def __init__(self, num_channels: int = 58, n_targets: int = 3, **backbone_kwargs):
        super().__init__()
        self.backbone = VLAAIwsBackbone(num_channels=num_channels, **backbone_kwargs)
        self.head = LinearHead(self.backbone.out_features, n_targets)
        self.n_targets = n_targets

    def forward(self, x: torch.Tensor) -> torch.Tensor:
        y = self.head(self.backbone(x))
        return y[..., 0] if self.n_targets == 1 else y


@torch.no_grad()
def causal_reconstruct(model: VLAAIwsDecoder, eeg: torch.Tensor, hop: int = 8, future: int = 16, batch: int = 512) -> torch.Tensor:
    """Reconstruction of a whole trial with at most `future + hop` samples of look-ahead per output sample.

    The trial is zero-padded and cut into windows of T samples every `hop` samples; from each window only the
    block [T - future - hop, T - future) is kept. With T = 160, hop = 8, future = 16 (32 Hz): every output sample sees at
    most 24 samples = 0.75 s of future EEG, and a 1-s evidence window ending at t needs EEG only up to t + 0.5 s.
    eeg: (N, C) -> returns (N, n_targets) (or (N,) for one target).
    """
    T = model.backbone.time_dim
    pos0 = T - future - hop
    n, C = eeg.shape
    dev = next(model.parameters()).device
    x = torch.cat([eeg.new_zeros(pos0, C), eeg, eeg.new_zeros(future + hop, C)]).to(dev, torch.float32)
    starts = torch.arange(0, n, hop)
    out = []
    model.eval()
    for i in range(0, len(starts), batch):
        s = starts[i:i + batch]
        w = torch.stack([x[a:a + T] for a in s.tolist()])                   # (b, T, C)
        out.append(model(w)[:, pos0:pos0 + hop].reshape(-1, *(() if model.n_targets == 1 else (model.n_targets,))))
    return torch.cat(out)[:n].cpu()


if __name__ == "__main__":
    torch.manual_seed(0)
    m = VLAAIwsDecoder(num_channels=58, n_targets=3)
    x = torch.randn(4, 160, 58)
    y = m(x)
    print("parameters:", sum(p.numel() for p in m.parameters()), "| output:", tuple(y.shape))
    rec = causal_reconstruct(m, torch.randn(1000, 58))
    print("causal_reconstruct:", tuple(rec.shape))
    # look-ahead check: perturbing the EEG from sample p on must not change reconstruction samples before p - 24
    e0 = torch.randn(600, 58)
    e1 = e0.clone()
    e1[400:] += 5 * torch.randn(200, 58)
    d = (causal_reconstruct(m, e0) - causal_reconstruct(m, e1)).abs().sum(-1)
    first = int((d > 0).nonzero()[0])
    print(f"first changed output sample {first} for a perturbation starting at 400 -> look-ahead {400 - first} samples (<= 24)")
