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


class TimeBlock(nn.Module):
    def __init__(self, in_channels, out_channels, kernel_size=3):
        super().__init__()
        self.conv1 = nn.Conv2d(in_channels, out_channels, (1, kernel_size))
        self.conv2 = nn.Conv2d(in_channels, out_channels, (1, kernel_size))
        self.conv3 = nn.Conv2d(in_channels, out_channels, (1, kernel_size))

    def forward(self, x):
        # x: (B, N, F, T)  → (B, F, N, T)
        x = x.permute(0, 2, 1, 3)
        y = self.conv1(x) + torch.sigmoid(self.conv2(x))
        y = F.relu(y + self.conv3(x))
        return y.permute(0, 2, 1, 3)                       # (B, N, C, T')


class STGCNBlock(nn.Module):
    def __init__(self, in_channels, spatial_channels, out_channels):
        super().__init__()
        self.temp1 = TimeBlock(in_channels, out_channels)
        self.Theta = nn.Parameter(torch.FloatTensor(out_channels, spatial_channels))
        self.temp2 = TimeBlock(spatial_channels, out_channels)
        self.bn = nn.BatchNorm2d(out_channels)
        self.reset_parameters()

    def reset_parameters(self):
        std = 1.0 / math.sqrt(self.Theta.shape[1])
        self.Theta.data.uniform_(-std, std)

    def forward(self, x, A_hat):
        # x: (B, N, Fin, T)
        t = self.temp1(x)                                  # (B, N, Cout, T1)
        lfs = torch.einsum('ij,jbct->bict', A_hat, t.permute(1, 0, 2, 3))
        t2 = F.relu(torch.einsum('bnct,cf->bnft', lfs, self.Theta))
        t3 = self.temp2(t2)                                # (B, N, Cout, T2)
        t3 = self.bn(t3.permute(0, 2, 1, 3)).permute(0, 2, 1, 3)
        return t3                                          # (B, N, Cout, T2)


class STGCN(nn.Module):
    """
    Spatio-Temporal GCN for *multiclass* node-level classification.
    Output: (B, N, T_out, num_classes)
    """
    def __init__(self,
                 num_nodes, num_features,
                 num_timesteps_input, num_classes,
                 num_timesteps_output):
        super().__init__()
        self.block1 = STGCNBlock(num_features, 16, 64)
        self.block2 = STGCNBlock(64, 16, 64)
        self.last_temp = TimeBlock(64, 64)
        # 5 TimeBlocks → reduce time dimension by 10 (kernel_size=3, no padding)
        self.t_final = num_timesteps_input - 10
        self.fc = nn.Linear(self.t_final * 64,
                            num_timesteps_output * num_classes)
        self.t_out = num_timesteps_output
        self.num_classes = num_classes

    def forward(self, A_hat, x):
        # x: (B, N, F, T_in)
        y = self.block1(x, A_hat)
        y = self.block2(y, A_hat)
        y = self.last_temp(y)                              # (B, N, 64, T_final)
        B, N, C, T = y.shape
        y = y.reshape(B, N, -1)                            # flatten (C * T)
        y = self.fc(y)                                     # (B, N, T_out * C)
        return y.view(B, N, self.t_out, self.num_classes)