"""F12 temporal adapter: identity-init Conformer on BEATs frames, plus cycle metadata bias.

The conformer branches are zero-initialized, so at step 0 the head matches a linear
frame head. Metadata bias is zero-initialized and only shifts pooled crackle/wheeze
logits when device and chest-location ids are provided.
"""

import torch
import torch.nn as nn


class _MacaronFF(nn.Module):
    def __init__(self, dim, mult, dropout):
        super().__init__()
        hidden = dim * mult
        self.net = nn.Sequential(
            nn.LayerNorm(dim),
            nn.Linear(dim, hidden),
            nn.GELU(),
            nn.Dropout(dropout),
            nn.Linear(hidden, dim),
            nn.Dropout(dropout),
        )
        nn.init.zeros_(self.net[4].weight)
        nn.init.zeros_(self.net[4].bias)

    def forward(self, x):
        return self.net(x)


class ConformerBlock(nn.Module):
    """Pre-norm macaron Conformer block. Residual branches start at zero."""

    def __init__(self, dim, heads, dropout, conv_kernel=15, ff_mult=2):
        super().__init__()
        if conv_kernel % 2 == 0:
            raise ValueError('conv_kernel must be odd')
        self.ff1 = _MacaronFF(dim, ff_mult, dropout)
        self.norm_attn = nn.LayerNorm(dim)
        self.attn = nn.MultiheadAttention(dim, heads, dropout=dropout, batch_first=True)
        nn.init.zeros_(self.attn.out_proj.weight)
        nn.init.zeros_(self.attn.out_proj.bias)
        self.attn_drop = nn.Dropout(dropout)
        self.norm_conv = nn.LayerNorm(dim)
        self.dw = nn.Conv1d(dim, dim, conv_kernel, padding=conv_kernel // 2, groups=dim)
        self.pw = nn.Conv1d(dim, dim, 1)
        nn.init.zeros_(self.pw.weight)
        nn.init.zeros_(self.pw.bias)
        self.conv_drop = nn.Dropout(dropout)
        self.ff2 = _MacaronFF(dim, ff_mult, dropout)

    def forward(self, x):
        x = x + 0.5 * self.ff1(x)
        h = self.norm_attn(x)
        attn_out, _ = self.attn(h, h, h, need_weights=False)
        x = x + self.attn_drop(attn_out)
        conv = self.norm_conv(x).transpose(1, 2)
        conv = self.conv_drop(self.pw(torch.nn.functional.gelu(self.dw(conv))))
        x = x + conv.transpose(1, 2)
        x = x + 0.5 * self.ff2(x)
        return x


class FrameASDTemporalHead(nn.Module):
    """Conformer context over BEATs frames, then per-frame crackle and wheeze logits."""

    def __init__(self, in_dim=768, n_layers=2, n_heads=8, dropout=0.1, ff_mult=2, conv_kernel=15):
        super().__init__()
        if n_layers < 1:
            raise ValueError('temporal head needs at least one conformer block')
        self.blocks = nn.ModuleList([
            ConformerBlock(in_dim, n_heads, dropout, conv_kernel=conv_kernel, ff_mult=ff_mult)
            for _ in range(n_layers)
        ])
        self.residual_scale = nn.Parameter(torch.ones(()))
        self.dropout = nn.Dropout(dropout)
        self.crackle = nn.Linear(in_dim, 1)
        self.wheeze = nn.Linear(in_dim, 1)

    def forward(self, frames):
        h = frames
        for block in self.blocks:
            h = block(h)
        x = frames + self.residual_scale * (h - frames)
        x = self.dropout(x)
        return self.crackle(x).squeeze(-1), self.wheeze(x).squeeze(-1)


class MetaLogitBias(nn.Module):
    """Device and chest-location bias on the two cycle logits. Last layer starts at 0."""

    def __init__(self, n_device=4, n_loc=8, dim=32):
        super().__init__()
        self.device_emb = nn.Embedding(n_device, dim)
        self.loc_emb = nn.Embedding(n_loc, dim)
        self.proj = nn.Linear(dim * 2, 2)
        nn.init.normal_(self.device_emb.weight, std=0.02)
        nn.init.normal_(self.loc_emb.weight, std=0.02)
        nn.init.zeros_(self.proj.weight)
        nn.init.zeros_(self.proj.bias)

    def forward(self, device_id, loc_id):
        x = torch.cat([
            self.device_emb(device_id.long()),
            self.loc_emb(loc_id.long()),
        ], dim=-1)
        bias = self.proj(x)
        return bias[:, 0], bias[:, 1]


def apply_cycle_bias(head, logit_c, logit_w, device_id, loc_id):
    """Add metadata bias when the head owns a MetaLogitBias and ids are in the batch."""
    meta = getattr(head, 'meta', None)
    if meta is None or device_id is None or loc_id is None:
        return logit_c, logit_w
    bias_c, bias_w = meta(device_id, loc_id)
    return logit_c + bias_c.unsqueeze(1), logit_w + bias_w.unsqueeze(1)
