import math

import torch
from torch import nn
from torch.nn import functional

from models.ops import generate_causal_mask

class TimeDistributed(nn.Module):

    def __init__(self, fn=None, sequential=False):
        super(TimeDistributed, self).__init__()
        if fn is None:
            fn = lambda x: x
        self.fn = fn
        self.batch_size = None
        self.time_steps = None
        self.sequential = sequential

    def distribute(self, x):
        is_sequence = (x.ndim == 5) or (x.ndim == 3)
        if is_sequence:
            self.batch_size, self.time_steps = x.shape[:2]
            x = x.reshape(self.batch_size * self.time_steps, *x.shape[2:])
        else:
            self.batch_size = x.shape[:1]
            self.time_steps = None
        return x

    def gather(self, x):
        if self.time_steps is not None:
            x = x.reshape(-1, self.time_steps, *x.shape[1:])
        return x

    def forward(self, x):
        if self.sequential:
            return self.fn(x)
        x = self.distribute(x)
        x = self.fn(x)
        x = self.gather(x)
        return x
    
class PatchEmbed3D(nn.Module):
    """ Video to Patch Embedding.
    Args:
        patch_size (int): Patch token size. Default: (2,4,4).
        num_channels (int): Number of input video channels. Default: 3.
        embed_dim (int): Number of linear projection output channels. Default: 96.
        norm_layer (nn.Module, optional): Normalization layer. Default: None
    """

    def __init__(self, patch_size=(2, 4, 4), num_channels=3, embed_dim=96, norm_layer=None):
        super().__init__()
        self.patch_size = patch_size

        self.num_channels = num_channels
        self.embed_dim = embed_dim

        self.proj = nn.Conv3d(num_channels, embed_dim, kernel_size=patch_size, stride=patch_size)
        if norm_layer is not None:
            self.norm = norm_layer(embed_dim)
        else:
            self.norm = None

    def forward(self, x):
        """Forward function."""
        # padding
        _, _, D, H, W = x.size()
        if W % self.patch_size[2] != 0:
            x = functional.pad(x, (0, self.patch_size[2] - W % self.patch_size[2]))
        if H % self.patch_size[1] != 0:
            x = functional.pad(x, (0, 0, 0, self.patch_size[1] - H % self.patch_size[1]))
        if D % self.patch_size[0] != 0:
            x = functional.pad(x, (0, 0, 0, 0, 0, self.patch_size[0] - D % self.patch_size[0]))

        x = self.proj(x)  # B C D Wh Ww
        if self.norm is not None:
            D, Wh, Ww = x.size(2), x.size(3), x.size(4)
            x = x.flatten(2).transpose(1, 2)
            x = self.norm(x)
            x = x.transpose(1, 2).view(-1, self.embed_dim, D, Wh, Ww)

        return x


class Mlp(nn.Module):
    """ Multilayer perceptron."""

    def __init__(self, in_features, hidden_features=None, out_features=None, 
                 act_layer=nn.GELU, bias=True, drop=0.):
        super().__init__()
        out_features = out_features or in_features
        hidden_features = hidden_features or in_features
        bias0, bias1 = (bias[0], bias[1]) if isinstance(bias, list) else (bias, True)
        drop0, drop1 = (drop[0], drop[1]) if isinstance(drop, list) else (drop, 0.0)
        layers = []
        layers.append(nn.Linear(in_features, hidden_features, bias=bias0))
        if act_layer is not None:
            layers.append(act_layer())
        layers.append(nn.Dropout(drop0))
        layers.append(nn.Linear(hidden_features, out_features, bias=bias1))
        if drop1 > 0.0:
            layers.append(nn.Dropout(drop1))
        self.block = nn.Sequential(*layers)
    def forward(self, x):
        return self.block(x)


class WindowAttention3D(nn.Module):
    """ Window based multi-head self attention (W-MSA) module with relative position bias.
    It supports both of shifted and non-shifted window.
    Args:
        dim (int): Number of input channels.
        window_size (tuple[int]): The temporal length, height and width of the window.
        num_heads (int): Number of attention heads.
        qkv_bias (bool, optional):  If True, add a learnable bias to query, key, value. Default: True
        qk_scale (float | None, optional): Override default qk scale of head_dim ** -0.5 if set
        attn_drop (float, optional): Dropout ratio of attention weight. Default: 0.0
        proj_drop (float, optional): Dropout ratio of output. Default: 0.0
    """

    def __init__(self, dim, window_size, num_heads, qkv_bias=False, qk_scale=None, attn_drop=0., proj_drop=0.):

        super().__init__()
        self.dim = dim
        self.window_size = window_size  # Wd, Wh, Ww
        self.num_heads = num_heads
        head_dim = dim // num_heads
        self.scale = qk_scale or head_dim ** -0.5

        # define a parameter table of relative position bias
        self.relative_position_bias_table = nn.Parameter(
            torch.zeros((2 * window_size[0] - 1) * (2 * window_size[1] - 1) * (2 * window_size[2] - 1),
                        num_heads))  # 2*Wd-1 * 2*Wh-1 * 2*Ww-1, nH

        # get pair-wise relative position index for each token inside the window
        coords_d = torch.arange(self.window_size[0])
        coords_h = torch.arange(self.window_size[1])
        coords_w = torch.arange(self.window_size[2])
        coords = torch.stack(torch.meshgrid(coords_d, coords_h, coords_w, indexing='ij'))  # 3, Wd, Wh, Ww
        coords_flatten = torch.flatten(coords, 1)  # 3, Wd*Wh*Ww
        relative_coords = coords_flatten[:, :, None] - coords_flatten[:, None, :]  # 3, Wd*Wh*Ww, Wd*Wh*Ww
        relative_coords = relative_coords.permute(1, 2, 0).contiguous()  # Wd*Wh*Ww, Wd*Wh*Ww, 3
        relative_coords[:, :, 0] += self.window_size[0] - 1  # shift to start from 0
        relative_coords[:, :, 1] += self.window_size[1] - 1
        relative_coords[:, :, 2] += self.window_size[2] - 1

        relative_coords[:, :, 0] *= (2 * self.window_size[1] - 1) * (2 * self.window_size[2] - 1)
        relative_coords[:, :, 1] *= (2 * self.window_size[2] - 1)
        relative_position_index = relative_coords.sum(-1)  # Wd*Wh*Ww, Wd*Wh*Ww
        self.register_buffer("relative_position_index", relative_position_index)

        self.qkv = nn.Linear(dim, dim * 3, bias=qkv_bias)
        self.attn_drop = nn.Dropout(attn_drop)
        self.proj = nn.Linear(dim, dim)
        self.proj_drop = nn.Dropout(proj_drop)

        nn.init.trunc_normal_(self.relative_position_bias_table, std=.02)
        self.softmax = nn.Softmax(dim=-1)

    def forward(self, x, mask=None, temporal_mask=None, return_weights=False):
        """ Forward function.
        Args:
            x: input features with shape of (num_windows*B, N, C)
            mask: (0/-inf) mask with shape of (num_windows, N, N) or None
        """
        B_, N, C = x.shape
        qkv = self.qkv(x).reshape(B_, N, 3, self.num_heads, C // self.num_heads).permute(2, 0, 3, 1, 4)
        q, k, v = qkv[0], qkv[1], qkv[2]  # B_, nH, N, C

        q = q * self.scale
        attn = q @ k.transpose(-2, -1)

        relative_position_bias = self.relative_position_bias_table[
            self.relative_position_index[:N, :N].reshape(-1)].reshape(
            N, N, -1)  # Wd*Wh*Ww,Wd*Wh*Ww,nH
        relative_position_bias = relative_position_bias.permute(2, 0, 1).contiguous()  # nH, Wd*Wh*Ww, Wd*Wh*Ww
        attn = attn + relative_position_bias.unsqueeze(0)  # B_, nH, N, N

        if temporal_mask is not None:
            Wd = temporal_mask.shape[0]
            temporal_mask = temporal_mask.view(1, 1, Wd, 1, Wd, 1)
            attn = attn.view(B_, self.num_heads, Wd, N // Wd, Wd, N // Wd)
            attn = attn.masked_fill(temporal_mask == 0.0, float('-inf'))
            attn = attn.view(-1, self.num_heads, N, N)
            
        if mask is not None:
            nW = mask.shape[0]
            attn = attn.view(B_ // nW, nW, self.num_heads, N, N) + mask.unsqueeze(1).unsqueeze(0)
            attn = attn.view(-1, self.num_heads, N, N)
            attn = self.softmax(attn)
        else:
            attn = self.softmax(attn)

        attn = self.attn_drop(attn)
        
        x = (attn @ v).transpose(1, 2).reshape(B_, N, C)
        x = self.proj(x)
        x = self.proj_drop(x)
        attn_weights = None
        if return_weights:
            attn_weights = attn
        out = {'outputs': x, 'weights': attn_weights}
        return out


class PatchMerging(nn.Module):
    """ Patch Merging Layer
    Args:
        dim (int): Number of input channels.
        norm_layer (nn.Module, optional): Normalization layer.  Default: nn.LayerNorm
    """

    def __init__(self, dim, norm_layer=nn.LayerNorm):
        super().__init__()
        self.dim = dim
        self.reduction = nn.Linear(4 * dim, 2 * dim, bias=False)
        self.norm = norm_layer(4 * dim)

    def forward(self, x):
        """ Forward function.
        Args:
            x: Input feature, tensor size (B, D, H, W, C).
        """
        _, _, H, W, _ = x.shape

        # padding
        pad_input = (H % 2 == 1) or (W % 2 == 1)
        if pad_input:
            x = functional.pad(x, (0, 0, 0, W % 2, 0, H % 2))

        x0 = x[:, :, 0::2, 0::2, :]  # B D H/2 W/2 C
        x1 = x[:, :, 1::2, 0::2, :]  # B D H/2 W/2 C
        x2 = x[:, :, 0::2, 1::2, :]  # B D H/2 W/2 C
        x3 = x[:, :, 1::2, 1::2, :]  # B D H/2 W/2 C
        x = torch.cat([x0, x1, x2, x3], -1)  # B D H/2 W/2 4*C

        x = self.norm(x)
        x = self.reduction(x)

        return x


class CausalSelfAttention(nn.Module):
    def __init__(self, dim, num_heads, attn_drop=0.1, resid_pdrop=0.1):
        super().__init__()
        assert dim % num_heads == 0, '...'

        self.num_heads = num_heads
        
        self.key = nn.Linear(dim, dim)
        self.query = nn.Linear(dim, dim)
        self.value = nn.Linear(dim, dim)
        
        self.attn_drop = nn.Dropout(attn_drop)
        self.resd_drop = nn.Dropout(resid_pdrop)
        
        self.proj = nn.Linear(dim, dim)
        
    def forward(self, x, attn_span=1, return_weights=False):
        # x: B * N * D
        B, N, D = x.size()
        
        temporal_mask = generate_causal_mask(N, attn_span, device=x.device)

        q = self.query(x.view(B*N, -1)).view(B, N, self.num_heads, D//self.num_heads).transpose(1, 2)
        k = self.key(x.view(B*N, -1)).view(B, N, self.num_heads, D//self.num_heads).transpose(1, 2)
        v = self.value(x.view(B*N, -1)).view(B, N, self.num_heads, D//self.num_heads).transpose(1, 2)
        
        attn = q @ k.transpose(-2, -1) * (1.0 / math.sqrt(k.size(-1)))
        attn = attn.masked_fill(temporal_mask == 0.0, float('-inf'))
        attn = functional.softmax(attn, dim=-1)
        attn = self.attn_drop(attn)
        y = (attn @ v).transpose(1, 2).contiguous().view(B, N, D)
        y = self.resd_drop(self.proj(y))
        out = {'outputs': y, 'weights': None}
        if return_weights:
            out['weights'] = attn
        return out

class SequenceEmbedding(nn.Module):

    def __init__(self, num_tokens, embeds_dim, discrete=True):
        super(SequenceEmbedding, self).__init__()
        self.num_tokens = num_tokens
        self.embeds_dim = embeds_dim
        self.discrete = discrete
        
        if discrete:
            self.embed = nn.Embedding(num_embeddings=num_tokens, embedding_dim=embeds_dim)
        else:
            self.embed = nn.Linear(num_tokens, embeds_dim)

    def forward(self, x):
        if (not self.discrete) and (x.ndim == 2):
            x = x.unsqueeze(-1)
        embeds = self.embed(x)
        return embeds

class PredictionNetwork(nn.Module):
    
    def __init__(self, dim, hidden_dims, use_norm=True, act_layer=nn.GELU, drop=0.1):
        super(PredictionNetwork, self).__init__()
        hidden_dims = hidden_dims or []
        layers, k = [], len(hidden_dims)
        for idx, (in_dim, out_dim) in enumerate(zip([dim] + hidden_dims[:-1], hidden_dims)):
            if use_norm:
                layers.append(nn.LayerNorm(in_dim))
            layers.append(nn.Linear(in_dim, out_dim))
            if (idx + 1 < k):
                layers.append(act_layer())
            if (drop > 0.0) and (idx + 1 < k):
                layers.append(nn.Dropout(drop))
        self.network = nn.Sequential(*layers)
    
    def forward(self, x):
        return self.network(x)
    
class PredictionHead(nn.Module):
    def __init__(self, dim, num_tokens, use_norm=False, nonneg_constraints=False):
        super(PredictionHead, self).__init__()
        self.norm = None
        if use_norm:
            self.norm = nn.LayerNorm(dim)
        self.linear = nn.Linear(dim, num_tokens, bias=False)
        self.nonneg_constraints = nonneg_constraints
    def forward(self, x):
        if self.norm is not None:
            x = self.norm(x)
        w = self.linear.weight
        if self.nonneg_constraints:
           w = torch.relu(w) 
        y =  functional.linear(x, w)
        return y
