"""STQD v1: separate time-preserving EEG/speech encoders and speaker-conditioned EEG retrieval.

Input: eeg [B,320,58], speech [B,320,2,3] (env,onset,dom).
Output: signed logit [B], positive => column zero attended.
No dataset/subject/trial labels enter the model.
"""
from __future__ import annotations
from dataclasses import dataclass
import torch
from torch import nn
from torch.nn import functional as F


@dataclass(frozen=True)
class Variant:
    features: str = "all"             # all / env / env_onset / env_dom
    stems: str = "separate"           # separate / joint
    fusion: str = "cross"             # cross / cosine
    query: str = "temporal"           # temporal / global
    time_bias: bool = True


VARIANTS = {
    "stqd_full": Variant(),
    "stqd_joint_stem": Variant(stems="joint"),
    "stqd_env": Variant(features="env"),
    "stqd_env_onset": Variant(features="env_onset"),
    "stqd_env_dom": Variant(features="env_dom"),
    "stqd_no_time_bias": Variant(time_bias=False),
    "stqd_global_query": Variant(query="global"),
    "stqd_cosine": Variant(fusion="cosine"),
}


class TemporalBlock(nn.Module):
    def __init__(self, dim: int, dilation: int):
        super().__init__()
        self.net = nn.Sequential(
            nn.Conv1d(dim, dim, 5, padding=2 * dilation, dilation=dilation),
            nn.GroupNorm(8, dim), nn.GELU(),
            nn.Conv1d(dim, dim, 1), nn.GroupNorm(8, dim),
        )
        self.scale = nn.Parameter(torch.tensor(.1))

    def forward(self, x):
        return F.gelu(x + self.scale * self.net(x))


class EEGEncoder(nn.Module):
    def __init__(self, channels=58, dim=64, stride=4):
        super().__init__()
        self.inp = nn.Sequential(nn.Conv1d(channels, dim, 1), nn.GroupNorm(8, dim), nn.GELU())
        self.blocks = nn.Sequential(*(TemporalBlock(dim, d) for d in (1, 4, 16)))
        self.down = nn.AvgPool1d(kernel_size=stride, stride=stride)

    def forward(self, eeg):
        x = self.down(self.blocks(self.inp(eeg.transpose(1, 2))))
        return x.transpose(1, 2)


class SpeechEncoder(nn.Module):
    def __init__(self, dim=64, stride=4, features="all", stems="separate"):
        super().__init__()
        if features not in {"all", "env", "env_onset", "env_dom"}:
            raise ValueError(features)
        if stems not in {"separate", "joint"}:
            raise ValueError(stems)
        self.features, self.stems = features, stems
        self.mask = tuple(i for i, allowed in enumerate((True, features in ("all", "env_onset"), features in ("all", "env_dom"))) if allowed)
        if stems == "separate":
            # Stems have fixed width even when a feature is ablated, so parameters need not grow across variants.
            self.parts = nn.ModuleList([nn.Sequential(nn.Conv1d(1, 24 if i < 2 else 16, 7, padding=3),
                                                       nn.GELU()) for i in range(3)])
            self.mix = nn.Conv1d(64, dim, 1)
        else:
            self.joint = nn.Sequential(nn.Conv1d(len(self.mask), dim, 7, padding=3), nn.GELU())
        self.blocks = nn.Sequential(*(TemporalBlock(dim, d) for d in (1, 4, 16)))
        self.down = nn.AvgPool1d(kernel_size=stride, stride=stride)

    def forward(self, s):
        # s [B,T,2,3]; the exact same weights process each candidate, preserving swap equivariance.
        b, t, n, f = s.shape
        if n != 2 or f != 3:
            raise ValueError(f"speech must be [B,T,2,3], got {tuple(s.shape)}")
        x = s.permute(0, 2, 3, 1).reshape(b * n, f, t)
        if self.stems == "separate":
            z = [self.parts[i](x[:, i:i+1]) if i in self.mask
                 else torch.zeros((b*n, 24 if i < 2 else 16, t), device=x.device, dtype=x.dtype)
                 for i in range(3)]
            x = self.mix(torch.cat(z, dim=1))
        else:
            x = self.joint(x[:, self.mask])
        x = self.down(self.blocks(x)).transpose(1, 2)
        return x.reshape(b, n, x.shape[1], x.shape[2])


class SpeakerCrossAttention(nn.Module):
    def __init__(self, dim=64, heads=4, dropout=0., time_bias=True, sampling_hz=8.):
        super().__init__()
        assert dim % heads == 0
        self.heads, self.dhead = heads, dim // heads
        self.time_bias = time_bias
        self.q = nn.Linear(dim, dim)
        self.k = nn.Linear(dim, dim)
        self.v = nn.Linear(dim, dim)
        self.out = nn.Linear(dim, dim)
        self.norm = nn.LayerNorm(dim)
        self.dropout = nn.Dropout(dropout)
        self.ff = nn.Sequential(nn.LayerNorm(dim), nn.Linear(dim, dim*2), nn.GELU(), nn.Linear(dim*2, dim))
        self.sampling_hz = sampling_hz

    def forward(self, queries, memory, query_positions=None):
        # queries [B,2,Lq,D], memory [B,Le,D] -> [B,2,Lq,D]
        b, speakers, lq, d = queries.shape
        le = memory.shape[1]
        q = self.q(queries).reshape(b, speakers, lq, self.heads, self.dhead).permute(0,1,3,2,4)
        k = self.k(memory).reshape(b, le, self.heads, self.dhead).permute(0,2,1,3)
        v = self.v(memory).reshape(b, le, self.heads, self.dhead).permute(0,2,1,3)
        scores = torch.einsum("bnhqd,bhkd->bnhqk", q, k) * (self.dhead ** -.5)
        if self.time_bias:
            if query_positions is None:
                query_positions = torch.arange(lq, device=scores.device)
            eeg_positions = torch.arange(le, device=scores.device)
            lag_s = (eeg_positions[None, :] - query_positions[:, None]) / self.sampling_hz
            # Soft physiologically motivated prior: EEG response may follow stimulus by a few 100ms.
            # This is NOT a hard causal mask. Input-window boundaries enforce the future budget.
            scores = scores - .5 * ((lag_s - .20) / .55).square()[None,None,None]
        w = self.dropout(scores.softmax(dim=-1))
        h = torch.einsum("bnhqk,bhkd->bnhqd", w, v)
        h = h.permute(0,1,3,2,4).reshape(b, speakers, lq, d)
        h = self.norm(queries + self.out(h))
        return h + self.ff(h)


class STQDNet(nn.Module):
    def __init__(self, variant="stqd_full", channels=58, width=64, heads=4, window=320, stride=4,
                 target_index=None):
        super().__init__()
        if variant not in VARIANTS:
            raise ValueError(f"Unknown variant {variant}; allowed {sorted(VARIANTS)}")
        if window % stride:
            raise ValueError("window must be divisible by stride")
        self.variant_name = variant
        self.variant = VARIANTS[variant]
        self.window, self.stride = window, stride
        self.readout = (window - 32 if target_index is None else target_index) // stride
        self.eeg = EEGEncoder(channels, width, stride)
        self.speech = SpeechEncoder(width, stride, self.variant.features, self.variant.stems)
        self.fusion = self.variant.fusion
        if self.fusion == "cross":
            self.cross = SpeakerCrossAttention(width, heads, time_bias=self.variant.time_bias,
                                               sampling_hz=32 / stride)
            self.head = nn.Sequential(nn.LayerNorm(width), nn.Linear(width, width), nn.GELU(), nn.Linear(width, 1))
        else:
            self.eeg_projection = nn.Linear(width, width)
            self.speech_projection = nn.Linear(width, width)
            self.temperature = nn.Parameter(torch.tensor(1.0))

    def forward(self, E, S, feat=False):
        if E.ndim != 3 or E.shape[1:] != (self.window, 58):
            raise ValueError(f"expected EEG [B,{self.window},58], got {tuple(E.shape)}")
        if S.ndim != 4 or S.shape[1:] != (self.window, 2, 3):
            raise ValueError(f"expected speech [B,{self.window},2,3], got {tuple(S.shape)}")
        # Matches original classifier normalization: each feature standardized per window and candidate.
        S = (S - S.mean(dim=1, keepdim=True)) / (S.std(dim=1, keepdim=True) + 1e-6)
        memory = self.eeg(E)
        candidate = self.speech(S)
        if self.variant.query == "global":
            q = candidate.mean(dim=2, keepdim=True)
            qpos = torch.tensor([self.readout], device=E.device)
            pick = 0
        else:
            q, qpos, pick = candidate, None, self.readout
        if self.fusion == "cross":
            z = self.cross(q, memory, query_positions=qpos)
            scores = self.head(z[:, :, pick]).squeeze(-1)
        else:
            e = F.normalize(self.eeg_projection(memory[:, self.readout]), dim=-1)
            s = F.normalize(self.speech_projection(q[:, :, pick]), dim=-1)
            scores = torch.einsum("bd,bnd->bn", e, s) * self.temperature.exp()
        # Explicit exact column-swap antisymmetry: same encoder and head for both candidates.
        logit = scores[:, 0] - scores[:, 1]
        return (logit, memory) if feat else logit
