"""STQD v2: shared-weight VLAAI EEG backbone + unchanged v1 speech/cross-modal modules.

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
import sys
from pathlib import Path
_DECODER_LODO = Path(__file__).resolve().parents[2] / 'decoder_lodo'
if str(_DECODER_LODO) not in sys.path:
    sys.path.insert(0, str(_DECODER_LODO))
import importlib.util
_cbm_path = _DECODER_LODO / 'decoders.py'
try:
    _old_path = list(sys.path)
    # Ensure decoder_lodo's common_exp/constants win over huyle/v2 shadows.
    sys.path.insert(0, str(_DECODER_LODO))
    _spec = importlib.util.spec_from_file_location('_h276_decoder_lodo_decoders', _cbm_path)
    _cbm_mod = importlib.util.module_from_spec(_spec)
    _spec.loader.exec_module(_cbm_mod)
    _CBraModBackbone = getattr(_cbm_mod, 'CBraModBackbone', None)
    if _CBraModBackbone is None:
        raise AttributeError('CBraModBackbone not found')
    CBRAMOD_AVAILABLE = True
except Exception:  # keep import optional so VLAAI-only runs still work
    _CBraModBackbone = None
    CBRAMOD_AVAILABLE = False
finally:
    sys.path[:] = _old_path
from dataclasses import dataclass
import torch
from torch import nn
from torch.nn import functional as F
from vlaai_ws_model import VLAAIwsBackbone


@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
    backbone: str = "vlaai"           # vlaai / cbramod  (official TUEG weights used as warm start)


VARIANTS = {
    "v2_full": Variant(),
    "v2_cosine": Variant(fusion="cosine"),
    "v2_no_time_bias": Variant(time_bias=False),
    "v2_cbramod_full": Variant(backbone="cbramod"),
    "v2_cbramod_cosine": Variant(backbone="cbramod", 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):
    """VLAAI-WS (3 passes, 10-second input) from the original decoder_lodo source.

    A separate EEG-only backbone, unlike the original direct classifier where EEG
    and two speaker streams are concatenated before the VLAAI input projection.
    Keeps original chronological axis until the identical v1 stride-4 pooling.
    """
    def __init__(self, channels=58, dim=64, stride=4, window=320):
        super().__init__()
        if window != 320 or stride != 4:
            raise ValueError('v2 evaluation fixes window=320 and stride=4')
        self.backbone = VLAAIwsBackbone(
            num_channels=channels, fs=32, window_s=window / 32,
            nb_blocks=3, num_kernels=dim, kernel_sizes=(3, 7, 11),
            output_context_kernel_size=17, use_skip=True, dropout=0.0)
        self.down = nn.AvgPool1d(kernel_size=stride, stride=stride)

    def forward(self, eeg):
        x = self.backbone(eeg)                   # [B, 320, 64]
        return self.down(x.transpose(1, 2)).transpose(1, 2)  # [B, 80, 64]


_FS = 32
_CBRAMOD_WEIGHTS = Path(__file__).resolve().parents[2] / 'external_data' / 'foundation_models' / 'cbramod' / 'pretrained_weights.pth'
_CBRAMOD_SCALE = 0.15


class ColumnReadout(nn.Module):
    # Mirrors decoder_lodo CBraModBackbone.readout; output is W x 64.
    def __init__(self, channels, d_input, step, d=64, r=16):
        super().__init__()
        self.r = nn.Linear(d_input, r)
        self.o = nn.Linear(channels * r, step * d)
        self.step = step
        self.d = d

    def forward(self, tok):
        B, C, N, _ = tok.shape
        return self.o(self.r(tok).permute(0, 2, 1, 3).reshape(B, N, -1)).reshape(B, N * self.step, self.d)


class EEGEncoderCBraMod(nn.Module):
    """CBraMod warm-started on TUEG; all weights remain trainable."""
    def __init__(self, channels=58, dim=64, stride=4, window=320):
        super().__init__()
        if window != 320 or stride != 4:
            raise ValueError('v2 evaluation fixes window=320 and stride=4')
        if channels != 58:
            raise ValueError('CBraMod v2 path is configured for the official 58-channel montage')
        if not Path(_CBRAMOD_WEIGHTS).is_file():
            raise RuntimeError(f'Missing CBraMod weights: {_CBRAMOD_WEIGHTS}')
        _old_path = list(sys.path)
        sys.path.insert(0, str(Path(__file__).resolve().parents[2] / 'decoder_lodo'))
        try:
            import importlib
            spec = importlib.util.spec_from_file_location('_cbm_fm_models', Path(__file__).resolve().parents[2] / 'decoder_lodo' / 'fm_models' / 'cbramod.py')
            mod = importlib.util.module_from_spec(spec)
            spec.loader.exec_module(mod)
            CBraMod = getattr(mod, 'CBraMod')
        finally:
            sys.path[:] = _old_path
        import torch
        self.enc = CBraMod()
        state = torch.load(str(_CBRAMOD_WEIGHTS), map_location='cpu', weights_only=True)
        self.enc.load_state_dict(state)
        self.enc.proj_out = torch.nn.Identity()
        self.out = ColumnReadout(channels, 200, _FS, dim, 16)
        for p in self.parameters():
            p.requires_grad_(True)
        self.down = nn.AvgPool1d(kernel_size=stride, stride=stride)

    def forward(self, eeg):
        B, W, C = eeg.shape
        assert W % _FS == 0
        patches = eeg.transpose(1, 2).reshape(B * C, 1, W // _FS, _FS)[:, 0]
        patches = torch.nn.functional.interpolate(patches, size=200, mode='linear', align_corners=True) * _CBRAMOD_SCALE
        enc_out = self.enc(patches.reshape(B, C, W // _FS, 200))
        x = self.out(enc_out)
        return self.down(x.transpose(1, 2)).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="v2_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
        if getattr(self.variant, "backbone", "vlaai") == "cbramod":
            self.eeg = EEGEncoderCBraMod(channels, width, stride, window)
        else:
            self.eeg = EEGEncoder(channels, width, stride, window)
        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
