from __future__ import annotations

import importlib
import importlib.metadata
import math
from dataclasses import dataclass

import torch
import torch.nn as nn
import torch.nn.functional as F


def _zero_last(module: nn.Module):
    last = None
    for m in module.modules():
        if isinstance(m, nn.Linear):
            last = m
    if last is not None:
        nn.init.zeros_(last.weight)
        if last.bias is not None:
            nn.init.zeros_(last.bias)


def mlp(in_dim: int, hidden: int, out_dim: int, dropout: float = 0.0, final_norm: bool = True) -> nn.Sequential:
    layers = [
        nn.Linear(in_dim, hidden), nn.LayerNorm(hidden), nn.GELU(), nn.Dropout(dropout),
        nn.Linear(hidden, out_dim),
    ]
    if final_norm:
        layers += [nn.LayerNorm(out_dim), nn.GELU()]
    return nn.Sequential(*layers)


def safe_logit(p: torch.Tensor) -> torch.Tensor:
    p = p.clamp(1e-5, 1.0 - 1e-5)
    return torch.log(p) - torch.log1p(-p)


class TimeContextEncoder(nn.Module):
    """Continuous/extrapolatable target-semester context.

    No learned semester lookup table is used. Future folds therefore have a
    naturally defined representation.
    """
    def __init__(self, out_dim: int = 16):
        super().__init__()
        self.out_dim = int(out_dim)
        self.net = mlp(7, 32, self.out_dim, 0.05)

    def raw_features(self, semester_ordinal: torch.Tensor, semester_z: torch.Tensor) -> torch.Tensor:
        t = semester_ordinal.float()
        z = semester_z.float()
        features = [z]
        for period in (3.0, 6.0, 12.0):
            phase = torch.remainder(t, period)
            angle = (2.0 * math.pi / period) * phase
            features.extend([torch.sin(angle), torch.cos(angle)])
        return torch.stack(features, dim=1)

    def forward(self, semester_ordinal: torch.Tensor, semester_z: torch.Tensor) -> tuple[torch.Tensor, torch.Tensor]:
        raw = self.raw_features(semester_ordinal, semester_z)
        return self.net(raw), raw


class PiecewiseLinearTokenizer(nn.Module):
    """Self-contained train-knot piecewise-linear numerical embedding.

    For feature j the basis is [x_j, ReLU(x_j-k_1), ..., ReLU(x_j-k_K)].
    Binary/constant features have no active hinge knots. Each feature has its
    own learned projection into token_dim dimensions.
    """
    def __init__(self, knots, knot_mask, token_dim: int = 4):
        super().__init__()
        knots = torch.as_tensor(knots, dtype=torch.float32)
        knot_mask = torch.as_tensor(knot_mask, dtype=torch.bool)
        if knots.shape != knot_mask.shape:
            raise ValueError("knots/mask shape mismatch")
        self.n_features = int(knots.shape[0])
        self.n_knots = int(knots.shape[1])
        self.token_dim = int(token_dim)
        safe_knots = torch.nan_to_num(knots, nan=0.0)
        self.register_buffer("knots", safe_knots)
        self.register_buffer("knot_mask", knot_mask)
        self.weight = nn.Parameter(torch.empty(self.n_features, 1 + self.n_knots, self.token_dim))
        self.bias = nn.Parameter(torch.zeros(self.n_features, self.token_dim))
        nn.init.normal_(self.weight, std=0.06)

    def forward(self, x: torch.Tensor) -> torch.Tensor:
        x = torch.nan_to_num(x.float()).clamp(-10.0, 10.0)
        if x.ndim != 2 or x.shape[1] != self.n_features:
            raise ValueError(f"Expected [B,{self.n_features}] current features; got {tuple(x.shape)}")
        hinges = F.relu(x[:, :, None] - self.knots[None, :, :])
        hinges = hinges * self.knot_mask[None, :, :].float()
        basis = torch.cat([x[:, :, None], hinges], dim=2)
        tokens = torch.einsum("bfk,fkd->bfd", basis, self.weight) + self.bias[None, :, :]
        return tokens


class _LowRankComponent(nn.Module):
    def __init__(self, context_dim: int, n_features: int, rank: int, hidden: int = 32):
        super().__init__()
        self.rank = int(rank)
        self.coeff = nn.Sequential(
            nn.Linear(context_dim, hidden), nn.GELU(), nn.Linear(hidden, 3 * self.rank)
        )
        # Non-zero basis + exactly-zero coefficient head gives identity at step 0
        # while preserving a gradient path into the coefficient network.
        self.basis = nn.Parameter(torch.empty(3, self.rank, n_features))
        nn.init.normal_(self.basis, std=0.02)
        _zero_last(self.coeff)

    def forward(self, context: torch.Tensor) -> torch.Tensor:
        a = self.coeff(context).view(len(context), 3, self.rank)
        return torch.einsum("bcr,crf->bcf", a, self.basis)


class FeatureAwareModulator(nn.Module):
    """Low-rank faculty + time + faculty×time feature-wise modulation."""
    def __init__(self, faculty_dim: int, time_dim: int, n_features: int, rank: int = 8):
        super().__init__()
        self.n_features = int(n_features)
        self.faculty = _LowRankComponent(faculty_dim, n_features, rank)
        self.time = _LowRankComponent(time_dim, n_features, rank)
        self.interaction = _LowRankComponent(faculty_dim, n_features, rank)
        self.ft_fac = nn.Linear(faculty_dim, faculty_dim, bias=False)
        self.ft_time = nn.Linear(time_dim, faculty_dim, bias=False)

    def raw_components(self, faculty: torch.Tensor, time: torch.Tensor):
        interaction_ctx = torch.tanh(self.ft_fac(faculty)) * torch.tanh(self.ft_time(time))
        return {
            "faculty": self.faculty(faculty),
            "time": self.time(time),
            "interaction": self.interaction(interaction_ctx),
        }

    def parameters_for(self, faculty: torch.Tensor, time: torch.Tensor,
                       use_faculty: bool, use_time: bool, use_interaction: bool):
        parts = self.raw_components(faculty, time)
        raw = torch.zeros_like(parts["faculty"])
        if use_faculty:
            raw = raw + parts["faculty"]
        if use_time:
            raw = raw + parts["time"]
        if use_interaction:
            raw = raw + parts["interaction"]
        # Bounded transforms: exact identity when raw==0.
        gamma = 1.0 + 0.50 * torch.tanh(raw[:, 0])
        beta = 0.25 * torch.tanh(raw[:, 1])
        lam = 0.25 * torch.tanh(raw[:, 2])
        return gamma, beta, lam, parts

    def forward(self, tokens: torch.Tensor, faculty: torch.Tensor, time: torch.Tensor,
                use_faculty: bool, use_time: bool, use_interaction: bool):
        gamma, beta, lam, parts = self.parameters_for(faculty, time, use_faculty, use_time, use_interaction)
        out = gamma[:, :, None] * tokens + beta[:, :, None] + lam[:, :, None] * torch.tanh(tokens)
        return out, (gamma, beta, lam), parts


class SparseFeatureGraph(nn.Module):
    """Global learned sparse feature relation graph (T2G-inspired, not T2G-Former)."""
    def __init__(self, n_features: int, token_dim: int, identity_dim: int = 16, neighbors: int = 8):
        super().__init__()
        self.n_features = int(n_features)
        self.neighbors = min(int(neighbors), max(1, self.n_features - 1))
        self.identity = nn.Parameter(torch.randn(self.n_features, identity_dim) * 0.05)
        self.q = nn.Linear(identity_dim, identity_dim, bias=False)
        self.k = nn.Linear(identity_dim, identity_dim, bias=False)
        self.value = nn.Linear(token_dim, token_dim, bias=False)
        self.norm = nn.LayerNorm(token_dim)
        self.rho_raw = nn.Parameter(torch.tensor(math.log(.1 / .9), dtype=torch.float32))

    def adjacency(self):
        q = self.q(self.identity)
        k = self.k(self.identity)
        logits = (q @ k.T) / math.sqrt(q.shape[-1])
        logits = logits.clone()
        logits.fill_diagonal_(-1e9)
        values, indices = torch.topk(logits, self.neighbors, dim=1)
        weights = torch.softmax(values, dim=1)
        return indices, weights

    def forward(self, tokens: torch.Tensor, enabled: bool = True):
        if not enabled:
            return tokens
        idx, weights = self.adjacency()
        v = self.value(tokens)
        neigh = v[:, idx, :]  # [B,F,K,D]
        msg = (neigh * weights[None, :, :, None]).sum(2)
        rho = torch.sigmoid(self.rho_raw)
        return self.norm(tokens + rho * msg)


class MaskedQueryPool(nn.Module):
    def __init__(self, token_dim: int):
        super().__init__()
        self.q = nn.Linear(token_dim, token_dim, bias=False)
        self.k = nn.Linear(token_dim, token_dim, bias=False)
        self.v = nn.Linear(token_dim, token_dim, bias=False)

    def forward(self, query: torch.Tensor, tokens: torch.Tensor, mask: torch.Tensor):
        q = self.q(query)[:, None, :]
        k = self.k(tokens)
        logits = (q * k).sum(-1) / math.sqrt(tokens.shape[-1])
        logits = logits.masked_fill(~mask, -1e9)
        weights = torch.softmax(logits, dim=1)
        weights = torch.where(mask, weights, torch.zeros_like(weights))
        denom = weights.sum(1, keepdim=True).clamp_min(1e-8)
        weights = weights / denom
        pooled = (weights[:, :, None] * self.v(tokens)).sum(1)
        has = mask.any(1)
        pooled = pooled * has[:, None].float()
        return pooled, weights


class AcademicEgoGraphEncoder(nn.Module):
    """Target-conditioned relational set encoder over the Suite12 structured cache."""
    def __init__(self, student_dim: int, course_dim: int, relation_dim: int, component_dim: int,
                 faculty_dim: int, time_dim: int, out_dim: int = 64,
                 relation_types: int = 32, component_types: int = 32, course_relation_types: int = 32,
                 dropout: float = .10):
        super().__init__()
        self.out_dim = int(out_dim)
        self.query = mlp(course_dim + faculty_dim + time_dim, 2*out_dim, out_dim, dropout)
        self.student = mlp(student_dim, out_dim, out_dim, dropout)
        self.course_type = nn.Embedding(course_relation_types, 8, padding_idx=0)
        self.course = mlp(course_dim + 8, out_dim, out_dim, dropout)
        self.rel_type = nn.Embedding(relation_types, 8, padding_idx=0)
        self.relation = mlp(relation_dim + 8, out_dim, out_dim, dropout)
        self.comp_type = nn.Embedding(component_types, 8, padding_idx=0)
        self.component = mlp(component_dim + 8, out_dim, out_dim, dropout)
        self.student_pool = MaskedQueryPool(out_dim)
        self.course_pool = MaskedQueryPool(out_dim)
        self.relation_pool = MaskedQueryPool(out_dim)
        self.component_pool = MaskedQueryPool(out_dim)
        self.out = mlp(5*out_dim + 4, 2*out_dim, out_dim, dropout)

    @staticmethod
    def _safe_type(x, emb):
        return x.long().clamp(0, emb.num_embeddings - 1)

    def forward(self, course_target, faculty, time,
                student_seq, student_mask,
                course_neighbors, course_neighbor_mask, course_relation_type,
                relation_events, relation_mask, relation_type,
                component_events, component_mask, component_type,
                zero_relations: bool = False,
                shuffle_relations: torch.Tensor | None = None):
        q = self.query(torch.cat([course_target, faculty, time], 1))
        if shuffle_relations is not None:
            # Permute all structured evidence together so marginal distributions are
            # preserved while the student-course assignment is destroyed.
            ix = shuffle_relations.long()
            student_seq, student_mask = student_seq[ix], student_mask[ix]
            course_neighbors, course_neighbor_mask, course_relation_type = course_neighbors[ix], course_neighbor_mask[ix], course_relation_type[ix]
            relation_events, relation_mask, relation_type = relation_events[ix], relation_mask[ix], relation_type[ix]
            component_events, component_mask, component_type = component_events[ix], component_mask[ix], component_type[ix]
        if zero_relations:
            student_mask = torch.zeros_like(student_mask)
            course_neighbor_mask = torch.zeros_like(course_neighbor_mask)
            relation_mask = torch.zeros_like(relation_mask)
            component_mask = torch.zeros_like(component_mask)

        st = self.student(student_seq)
        ct = self.course(torch.cat([course_neighbors, self.course_type(self._safe_type(course_relation_type, self.course_type))], -1))
        rt = self.relation(torch.cat([relation_events, self.rel_type(self._safe_type(relation_type, self.rel_type))], -1))
        mt = self.component(torch.cat([component_events, self.comp_type(self._safe_type(component_type, self.comp_type))], -1))
        rs, aw_s = self.student_pool(q, st, student_mask)
        rc, aw_c = self.course_pool(q, ct, course_neighbor_mask)
        rr, aw_r = self.relation_pool(q, rt, relation_mask)
        rm, aw_m = self.component_pool(q, mt, component_mask)
        counts = torch.stack([
            student_mask.sum(1), course_neighbor_mask.sum(1), relation_mask.sum(1), component_mask.sum(1)
        ], 1).float()
        counts = torch.log1p(counts)
        out = self.out(torch.cat([q, rs, rc, rr, rm, counts], 1))
        attn = {"student": aw_s, "course": aw_c, "relation": aw_r, "component": aw_m}
        return out, counts, attn


class InternalBatchEnsembleTabM(nn.Module):
    """Diagnostic/smoke-test surrogate. Production must use official tabm."""
    def __init__(self, d_in: int, k: int, n_blocks: int, d_block: int, dropout: float):
        super().__init__()
        blocks = []
        d = d_in
        for _ in range(n_blocks):
            blocks += [nn.Linear(d, d_block), nn.LayerNorm(d_block), nn.GELU(), nn.Dropout(dropout)]
            d = d_block
        self.backbone = nn.Sequential(*blocks)
        self.r = nn.Parameter(torch.ones(k, d_block))
        self.s = nn.Parameter(torch.ones(k, d_block))
        self.head = nn.Parameter(torch.empty(k, d_block))
        self.bias = nn.Parameter(torch.zeros(k))
        nn.init.normal_(self.r, 1.0, .03)
        nn.init.normal_(self.s, 1.0, .03)
        nn.init.xavier_uniform_(self.head)

    def forward(self, x):
        h = self.backbone(x)
        z = h[:, None, :] * self.r[None, :, :] * self.s[None, :, :]
        return (z * self.head[None, :, :]).sum(-1) + self.bias[None, :]


class TabMBackbone(nn.Module):
    def __init__(self, d_in: int, ensemble_members: int = 32, n_blocks: int = 3,
                 d_block: int = 512, dropout: float = .10, backend: str = "official"):
        super().__init__()
        self.backend = str(backend)
        self.k = int(ensemble_members)
        if self.backend == "official":
            try:
                mod = importlib.import_module("tabm")
                TabM = mod.TabM
            except Exception as e:
                raise ImportError("Suite22 production requires official tabm==0.0.3. No silent fallback is permitted.") from e
            try:
                version = importlib.metadata.version("tabm")
            except Exception:
                version = "unknown"
            if version != "0.0.3":
                raise RuntimeError(f"Suite22 is validated for tabm==0.0.3; found {version}")
            self.model = TabM.make(
                n_num_features=int(d_in), cat_cardinalities=[], d_out=1,
                arch_type="tabm", k=self.k, n_blocks=int(n_blocks),
                d_block=int(d_block), dropout=float(dropout),
            )
        elif self.backend == "internal_smoke":
            self.model = InternalBatchEnsembleTabM(d_in, self.k, n_blocks, d_block, dropout)
        else:
            raise ValueError("backend must be 'official' or explicit 'internal_smoke'")

    def forward(self, x):
        if self.backend == "internal_smoke":
            return self.model(x)
        try:
            out = self.model(x, None)
        except TypeError:
            try:
                out = self.model(x_num=x, x_cat=None)
            except TypeError:
                out = self.model(x)
        if out.ndim == 3 and out.shape[-1] == 1:
            out = out[..., 0]
        elif out.ndim == 2 and out.shape[-1] == 1:
            out = out[:, 0:1]
        if out.ndim != 2:
            raise RuntimeError(f"Unexpected official TabM output shape: {tuple(out.shape)}")
        return out


@dataclass(frozen=True)
class VariantSpec:
    faculty_mod: bool
    time_mod: bool
    interaction_mod: bool
    relational: bool
    feature_graph: bool


VARIANTS = {
    "shared_tabm": VariantSpec(False, False, False, False, False),
    "faculty_mod_tabm": VariantSpec(True, False, False, False, False),
    "faculty_time_tabm": VariantSpec(True, True, True, False, False),
    "relational_ft_tabm": VariantSpec(True, True, True, True, False),
    "sftr_tabm": VariantSpec(True, True, True, True, True),
}


class Suite22Model(nn.Module):
    def __init__(self, variant: str, knots, knot_mask, n_faculties: int,
                 student_dim: int, course_dim: int, relation_dim: int, component_dim: int,
                 relation_types: int, component_types: int, course_relation_types: int,
                 token_dim: int = 4, faculty_dim: int = 16, time_dim: int = 16,
                 modulation_rank: int = 8, graph_neighbors: int = 8, relation_out_dim: int = 64,
                 ensemble_members: int = 32, tabm_blocks: int = 3, tabm_width: int = 512,
                 dropout: float = .10, backend: str = "official"):
        super().__init__()
        if variant not in VARIANTS:
            raise ValueError(f"Unknown Suite22 variant: {variant}")
        self.variant = variant
        self.spec = VARIANTS[variant]
        self.n_current = int(knots.shape[0])
        self.token_dim = int(token_dim)
        self.faculty = nn.Embedding(int(n_faculties), int(faculty_dim))
        self.time = TimeContextEncoder(time_dim)
        self.tokenizer = PiecewiseLinearTokenizer(knots, knot_mask, token_dim)
        self.modulator = FeatureAwareModulator(faculty_dim, time_dim, self.n_current, modulation_rank)
        self.graph = SparseFeatureGraph(self.n_current, token_dim, identity_dim=16, neighbors=graph_neighbors)
        self.relational = AcademicEgoGraphEncoder(
            student_dim, course_dim, relation_dim, component_dim, faculty_dim, time_dim,
            out_dim=relation_out_dim, relation_types=relation_types,
            component_types=component_types, course_relation_types=course_relation_types,
            dropout=dropout,
        )
        base_dim = self.n_current * token_dim + faculty_dim + time_dim + 7
        if self.spec.relational:
            base_dim += relation_out_dim + 4
        self.tabm = TabMBackbone(base_dim, ensemble_members, tabm_blocks, tabm_width, dropout, backend)

    def forward(self, current, faculty_idx, semester_ordinal, semester_z,
                course_target, student_seq, student_mask,
                course_neighbors, course_neighbor_mask, course_relation_type,
                relation_events, relation_mask, relation_type,
                component_events, component_mask, component_type,
                ablation: str = "none", shuffle_index: torch.Tensor | None = None):
        f = self.faculty(faculty_idx.long())
        t, t_raw = self.time(semester_ordinal, semester_z)
        tokens = self.tokenizer(current)

        use_f = self.spec.faculty_mod and ablation not in {"no_faculty_mod", "identity_mod"}
        use_t = self.spec.time_mod and ablation not in {"no_time_mod", "identity_mod"}
        use_i = self.spec.interaction_mod and ablation not in {"no_interaction_mod", "identity_mod"}
        tokens, mod_params, mod_parts = self.modulator(tokens, f, t, use_f, use_t, use_i)

        graph_enabled = self.spec.feature_graph and ablation != "graph_off"
        tokens = self.graph(tokens, enabled=graph_enabled)
        pieces = [tokens.flatten(1), f, t, t_raw]

        attn = {}
        counts = torch.zeros(len(current), 4, device=current.device)
        if self.spec.relational:
            zero_rel = ablation == "zero_relations"
            relation_repr, counts, attn = self.relational(
                course_target, f, t,
                student_seq, student_mask,
                course_neighbors, course_neighbor_mask, course_relation_type,
                relation_events, relation_mask, relation_type,
                component_events, component_mask, component_type,
                zero_relations=zero_rel,
                shuffle_relations=shuffle_index if ablation == "shuffle_relations" else None,
            )
            pieces.extend([relation_repr, counts])
        x = torch.cat(pieces, 1)
        logits = self.tabm(x)
        probs = torch.sigmoid(logits)
        gamma, beta, lam = mod_params
        return {
            "logits": logits,
            "member_probabilities": probs,
            "probability": probs.mean(1),
            "uncertainty": probs.std(1, unbiased=False),
            "gamma": gamma, "beta": beta, "lambda": lam,
            "relation_counts": counts,
            "attention": attn,
        }

    @torch.no_grad()
    def feature_graph_edges(self):
        idx, weights = self.graph.adjacency()
        return idx.detach().cpu().numpy(), weights.detach().cpu().numpy(), float(torch.sigmoid(self.graph.rho_raw).item())

    @torch.no_grad()
    def modulation_magnitudes(self, faculty_idx, semester_ordinal, semester_z):
        f = self.faculty(faculty_idx.long())
        t, _ = self.time(semester_ordinal, semester_z)
        out = {}
        for name, flags in {
            "faculty": (True, False, False),
            "time": (False, True, False),
            "interaction": (False, False, True),
            "full": (self.spec.faculty_mod, self.spec.time_mod, self.spec.interaction_mod),
        }.items():
            g, b, l, _ = self.modulator.parameters_for(f, t, *flags)
            out[name] = {
                "gamma_abs": (g - 1).abs(), "beta_abs": b.abs(), "lambda_abs": l.abs()
            }
        return out
