import torch
import torch.nn as nn
import torch.nn.functional as F
from ts_benchmark.baselines.CSMoE.layers.Expert import Expert
from ts_benchmark.baselines.CSMoE.layers.RevIN import RevIN
from einops import rearrange



class CSMoE(nn.Module):
    def __init__(self, configs):
        super(CSMoE, self).__init__()
        self.task_name = configs.task_name
        if self.task_name == 'classification' or self.task_name == 'anomaly_detection' or self.task_name == 'imputation':
            self.pred_len = configs.seq_len
        else:
            self.pred_len = configs.pred_len
        self.CI = configs.CI
        self.n_vars = configs.enc_in
        self.seq_len = configs.seq_len
        self.pred_len = configs.horizon
        self.num_experts = configs.num_experts  # 默认4个专家
        self.hidden_dim = configs.hidden_dim   # 门控网络隐藏维度

        self.correlation_embedding = nn.Conv1d(configs.enc_in, configs.enc_in, 3, padding='same')

        self.alpha = nn.Parameter(torch.ones([1]) * 1.0)
        self.revin = RevIN(
            self.n_vars,
            1e-5,
            False
        )
        # MoE Linear experts
        self.experts = nn.ModuleList([
            Expert(self.seq_len, configs.d_model, configs.horizon, configs.e_layers, configs.dropout) for _ in range(self.num_experts)
        ])
        
        # Gating network: 输入均值 -> 权重
        self.gating = nn.Sequential(
            nn.Linear(self.seq_len, self.hidden_dim),
            nn.ReLU(),
            nn.Linear(self.hidden_dim, self.num_experts),
            nn.Softmax(dim=-1)
        )
        
        
        if self.task_name == 'classification':
            self.act = F.gelu
            self.dropout = nn.Dropout(configs.dropout)
            self.projection = nn.Linear(
                configs.enc_in * configs.seq_len, configs.num_class)
        
    def encoder(self, input):        
        input = self.revin(input, "norm")

        input = input.permute(0, 2, 1)  # [B, C, T]
        B, C, T = input.shape
        
        input_stat = input.mean(dim=1)  # [B, T]
        gate_scores = self.gating(input_stat)  # [B, num_experts]
        if self.CI != 1:
            input = self.alpha * input + (1 - self.alpha) * self.correlation_embedding(input)
        # Collect expert outputs
        expert_outputs = torch.stack([expert(input) for expert in self.experts], dim=1)  # [B, num_experts, C, pred_len]

        # Expand gate scores: [B, num_experts] -> [B, num_experts, 1, 1]
        weights = gate_scores.unsqueeze(-1).unsqueeze(-1)
        
        output = (weights * expert_outputs).sum(dim=1)  # Weighted sum: [B, C, pred_len]
        output = output.permute(0, 2, 1)  # [B, pred_len, C]

        output = self.revin(output, "denorm")
        return output

    def compute_expert_l1_loss(self):
        loss = torch.tensor(0.0, device='cuda' if torch.cuda.is_available() else 'cpu')

        for expert in self.experts:
            for param in expert.parameters():
                if param.requires_grad:
                    l1_sum = torch.norm(param, p=1)
                    param_count = param.numel()
                    loss += l1_sum / param_count
        return loss
    
    
    def forecast(self, x_enc):
        # Encoder
        return self.encoder(x_enc)

    def imputation(self, x_enc):
        # Encoder
        return self.encoder(x_enc)

    def anomaly_detection(self, x_enc):
        # Encoder
        return self.encoder(x_enc)

    def classification(self, x_enc):
        # Encoder
        enc_out = self.encoder(x_enc)
        # Output
        # (batch_size, seq_length * d_model)
        output = enc_out.reshape(enc_out.shape[0], -1)
        # (batch_size, num_classes)
        output = self.projection(output)
        return output

    def forward(self, x_enc, x_mark_enc, x_dec, x_mark_dec, mask=None):
        if self.task_name == 'long_term_forecast' or self.task_name == 'short_term_forecast':
            dec_out = self.forecast(x_enc)
            return dec_out[:, -self.pred_len:, :]  # [B, L, D]
        if self.task_name == 'imputation':
            dec_out = self.imputation(x_enc)
            return dec_out  # [B, L, D]
        if self.task_name == 'anomaly_detection':
            dec_out = self.anomaly_detection(x_enc)
            return dec_out  # [B, L, D]
        if self.task_name == 'classification':
            dec_out = self.classification(x_enc)
            return dec_out  # [B, N]
        return None
