import math
import sys
import os
from typing import Dict, Tuple

import triton
import triton.language as tl
import torch
import torch.nn as nn

from datetime import datetime
import pytz

IST = pytz.timezone("Asia/Kolkata")


def _maybe_profile(msg: str):
    if os.getenv("MIXTURE_OF_EXPERTS_PROFILE"):
        torch.cuda.synchronize()
        ist_time = datetime.now(IST).strftime("%Y-%m-%d %H:%M:%S")
        print(f"[{ist_time}] {msg}", file=sys.stderr)


class Expert(nn.Module):  # Standard PyTorch Expert, used for shared_expert
    def __init__(self, config: Dict, d_expert: int = None, device=None, dtype=None):
        super().__init__()
        self.d_hidden = config["d_hidden"]
        self.d_expert = config["d_expert"] if d_expert is None else d_expert
        self.act = nn.SiLU()
        kwargs = {}
        if device is not None:
            kwargs["device"] = device
        if dtype is not None:
            kwargs["dtype"] = dtype
        self.W_gate = nn.Linear(self.d_hidden, self.d_expert, bias=False, **kwargs)
        self.W_up = nn.Linear(self.d_hidden, self.d_expert, bias=False, **kwargs)
        self.W_down = nn.Linear(self.d_expert, self.d_hidden, bias=False, **kwargs)

    def forward(self, x: torch.Tensor) -> torch.Tensor:
        gate = self.act(self.W_gate(x))
        up = self.W_up(x)
        return self.W_down(gate * up)


# Configuration constants from your original code
FIXED_BLOCK_D_OUT_K1 = 256  # For D_exp dimension in Kernel 1
CHOSEN_K1_BLOCK_H_IN = 64  # For H_dim dimension in Kernel 1

FIXED_BLOCK_H_OUT_K2 = 128  # For H_dim dimension in Kernel 2
CHOSEN_K2_BLOCK_D_K2 = 32  # For D_exp dimension in Kernel 2


@triton.jit
def _compute_fused_kernel_on_sorted_data(
    # Inputs:
    x_data_for_sorted_pairs_ptr,  # Shape: (P_total_pairs, H_DIM). x data already gathered and sorted by expert.
    sorted_expert_indices_ptr,  # Shape: (P_total_pairs). Expert_id for each pair in the sorted list.
    w_gate_ptr,  # Shape: (E, D_EXP, H_DIM)
    w_up_ptr,  # Shape: (E, D_EXP, H_DIM)
    # Output:
    fused_out_sorted_ptr,  # Output buffer. Shape: (P_total_pairs, D_EXP)
    # Dimensions and constants:
    P_total_pairs: tl.constexpr,  # Total number of token-expert pairs (B * T * K)
    H_DIM: tl.constexpr,  # Hidden dimension of tokens
    D_EXP: tl.constexpr,  # Expert dimension
    BLOCK_D_EXP_K1: tl.constexpr,  # Tile size for D_EXP dimension for this kernel
    BLOCK_H_IN_K1: tl.constexpr,  # Tile size for H_DIM dimension for this kernel (inner loop)
):
    # Program IDs determine which token-expert pair and which D_EXP tile this instance handles
    pid_pair_sorted = tl.program_id(0)  # Index for the token-expert pair in the *sorted* list
    pid_d_tile = tl.program_id(1)  # Index for the tile along the D_EXP dimension

    if pid_pair_sorted >= P_total_pairs:
        return

    expert_id = tl.load(sorted_expert_indices_ptr + pid_pair_sorted)

    # --- Define offsets for D_EXP and H_DIM dimensions ---
    d_start = pid_d_tile * BLOCK_D_EXP_K1
    offs_d_exp = d_start + tl.arange(0, BLOCK_D_EXP_K1)  # Offsets for the D_EXP dimension tile
    offs_h_dim = tl.arange(0, BLOCK_H_IN_K1)  # Offsets for the H_DIM dimension tile

    # --- Initialize accumulators for gate and up projections (float32 for precision) ---
    gate_acc = tl.zeros([BLOCK_D_EXP_K1], dtype=tl.float32)
    up_acc = tl.zeros([BLOCK_D_EXP_K1], dtype=tl.float32)

    # --- Base pointers for fetching X data and Weight data ---
    # Pointer to the start of the X data for the current sorted pair
    ptr_x_pair_base = x_data_for_sorted_pairs_ptr + pid_pair_sorted * H_DIM

    # Base pointers for the weights of the determined expert_id
    base_w_gate_expert = w_gate_ptr + expert_id * D_EXP * H_DIM
    base_w_up_expert = w_up_ptr + expert_id * D_EXP * H_DIM

    # --- Loop over H_DIM in blocks (BLOCK_H_IN_K1) ---
    for h_block_start in range(0, H_DIM, BLOCK_H_IN_K1):
        mask_h = (h_block_start + offs_h_dim) < H_DIM

        # Load a slice of X data for the current sorted pair and h_block
        x_slice = tl.load(ptr_x_pair_base + h_block_start + offs_h_dim, mask=mask_h, other=0.0)
        x_col_vector = tl.reshape(x_slice, (BLOCK_H_IN_K1, 1))

        # --- Gate projection: W_gate * x ---
        ptr_w_gate_tile = (
            base_w_gate_expert + offs_d_exp[:, None] * H_DIM + (h_block_start + offs_h_dim)[None, :]
        )
        mask_weights = (offs_d_exp[:, None] < D_EXP) & mask_h[None, :]
        w_gate_tile = tl.load(ptr_w_gate_tile, mask=mask_weights, other=0.0)
        dot_gate = tl.dot(w_gate_tile, x_col_vector)
        gate_acc += tl.reshape(dot_gate, (BLOCK_D_EXP_K1,))

        # --- Up projection: W_up * x (similar to gate projection) ---
        ptr_w_up_tile = (
            base_w_up_expert + offs_d_exp[:, None] * H_DIM + (h_block_start + offs_h_dim)[None, :]
        )
        w_up_tile = tl.load(ptr_w_up_tile, mask=mask_weights, other=0.0)  # Reuse mask_weights
        dot_up = tl.dot(w_up_tile, x_col_vector)
        up_acc += tl.reshape(dot_up, (BLOCK_D_EXP_K1,))

    # --- Activation and Fused Multiply ---
    gate_activated_f32 = gate_acc * tl.sigmoid(gate_acc)
    fused_result_f32 = gate_activated_f32 * up_acc
    fused_result_f16 = fused_result_f32.to(tl.float16)

    # --- Store the result ---
    out_ptr_base = fused_out_sorted_ptr + pid_pair_sorted * D_EXP + d_start
    mask_d_store = (d_start + tl.arange(0, BLOCK_D_EXP_K1)) < D_EXP
    tl.store(out_ptr_base + tl.arange(0, BLOCK_D_EXP_K1), fused_result_f16, mask=mask_d_store)


@triton.jit
def _project_and_accumulate_kernel_optimized_v2(  # This kernel remains the same
    fused_in_ptr,
    expert_idx_ptr,
    routing_w_ptr,
    w_down_ptr,
    out_ptr,
    NUM_TOKENS: tl.constexpr,
    H_DIM: tl.constexpr,
    D_EXP: tl.constexpr,
    TOP_K: tl.constexpr,
    FIXED_BLOCK_H_OUT_K2: tl.constexpr,
    BLOCK_D_K2: tl.constexpr,
):
    pid_tok = tl.program_id(0)
    pid_h = tl.program_id(1)
    h_start = pid_h * FIXED_BLOCK_H_OUT_K2
    offs_h = tl.arange(0, FIXED_BLOCK_H_OUT_K2)
    if pid_tok >= NUM_TOKENS:
        return

    out_acc = tl.zeros([FIXED_BLOCK_H_OUT_K2], dtype=tl.float32)
    # base_fused = fused_in_ptr + pid_tok * TOP_K * D_EXP # This line is not used
    for k in range(TOP_K):
        pair_id = pid_tok * TOP_K + k
        expert_id = tl.load(expert_idx_ptr + pair_id)
        r_w_fp16 = tl.load(routing_w_ptr + pair_id)

        cur_acc = tl.zeros([FIXED_BLOCK_H_OUT_K2], dtype=tl.float32)
        wd_base = w_down_ptr + expert_id * H_DIM * D_EXP
        fused_base = fused_in_ptr + pair_id * D_EXP  # Input fbuf is indexed by pair_id

        for d0 in range(0, D_EXP, BLOCK_D_K2):
            offs_d = d0 + tl.arange(0, BLOCK_D_K2)
            mask_d = offs_d < D_EXP

            f_tile = tl.load(fused_base + offs_d, mask=mask_d, other=0.0).reshape((BLOCK_D_K2, 1))
            w_tile = tl.load(
                wd_base + (h_start + offs_h)[:, None] * D_EXP + offs_d[None, :],
                mask=((h_start + offs_h)[:, None] < H_DIM)
                & mask_d[None, :],  # Corrected H_DIM masking
                other=0.0,
            )
            dotd = tl.dot(w_tile, f_tile)
            d1 = tl.reshape(dotd, (FIXED_BLOCK_H_OUT_K2,))
            cur_acc += d1
        out_acc += (cur_acc.to(tl.float32) * r_w_fp16.to(tl.float32)).to(tl.float16)

    dst = out_ptr + pid_tok * H_DIM + h_start + offs_h
    mask_o = (h_start + offs_h) < H_DIM
    tl.store(dst, out_acc.to(tl.float16), mask=mask_o)


class TritonMoE(nn.Module):
    def __init__(self, config: Dict, device: torch.device):
        super().__init__()
        self.E = config["n_routed_experts"]
        self.K = config["n_experts_per_token"]
        self.H_dim = config["d_hidden"]
        self.D_exp = config["d_expert"]
        self.device = device
        expert_dtype_arg = torch.float16  # Assuming float16 for weights

        self.W_g = nn.Linear(self.H_dim, self.E, bias=False, device=device, dtype=expert_dtype_arg)
        self.W_gate = nn.Parameter(
            torch.empty(self.E, self.D_exp, self.H_dim, device=device, dtype=expert_dtype_arg)
        )
        self.W_up = nn.Parameter(
            torch.empty(self.E, self.D_exp, self.H_dim, device=device, dtype=expert_dtype_arg)
        )
        self.W_down = nn.Parameter(
            torch.empty(self.E, self.H_dim, self.D_exp, device=device, dtype=expert_dtype_arg)
        )
        shared_dim = self.D_exp * config["n_shared_experts"]
        self.shared_expert = Expert(
            config, d_expert=shared_dim, device=device, dtype=expert_dtype_arg
        )
        self.reset_parameters()

    def load_weights_fast(self, weights: Dict[str, torch.Tensor]):
        dev = self.device
        td = torch.float16
        self.W_g.weight.data.copy_(weights["router.weight"].to(dev, td))
        self.W_gate.data.copy_(
            _stack_t(weights, "experts.{}.0.weight", self.E, (self.E, self.D_exp, self.H_dim)).to(
                dev, td
            )
        )
        self.W_up.data.copy_(
            _stack_t(weights, "experts.{}.1.weight", self.E, (self.E, self.D_exp, self.H_dim)).to(
                dev, td
            )
        )
        self.W_down.data.copy_(
            _stack_t(weights, "experts.{}.2.weight", self.E, (self.E, self.H_dim, self.D_exp)).to(
                dev, td
            )
        )
        # shared
        self.shared_expert.W_gate.weight.data.copy_(
            weights["shared_experts.0.weight"].t().to(dev, td)
        )
        self.shared_expert.W_up.weight.data.copy_(
            weights["shared_experts.1.weight"].t().to(dev, td)
        )
        self.shared_expert.W_down.weight.data.copy_(
            weights["shared_experts.2.weight"].t().to(dev, td)
        )

    def reset_parameters(self):
        nn.init.kaiming_uniform_(self.W_gate, a=math.sqrt(5))
        nn.init.kaiming_uniform_(self.W_up, a=math.sqrt(5))
        # Kaiming for W_down might be better than zeros, depending on initialization schemes
        # Let's keep original zeros for now if that was intended.
        # nn.init.kaiming_uniform_(self.W_down, a=math.sqrt(5))
        nn.init.zeros_(self.W_down)
        if hasattr(self.W_g, "weight"):
            nn.init.kaiming_uniform_(self.W_g.weight, a=math.sqrt(5))

    def forward(self, x: torch.Tensor) -> torch.Tensor:
        B, T, H = x.shape
        P_total_pairs = B * T * self.K  # Renamed P to P_total_pairs for clarity
        NUM_TOKENS = B * T

        # Ensure input x is float16 for consistency if weights are float16
        x_fp16 = x.to(torch.float16 if self.W_g.weight.dtype == torch.float16 else x.dtype)

        logits = self.W_g(x_fp16)
        scores = logits.softmax(dim=-1)
        topk_scores, topk_idx = torch.topk(scores, self.K, dim=-1, sorted=False)

        # --- Original flat structures ---
        original_expert_flat = topk_idx.reshape(-1).int()  # Shape (P_total_pairs)
        original_rout_flat = topk_scores.reshape(-1)  # Shape (P_total_pairs)
        x_flat = x_fp16.reshape(NUM_TOKENS, H)  # Shape (NUM_TOKENS, H)

        # --- MoE Align & Sort (Permutation implemented in PyTorch) ---
        _maybe_profile("start permutation ↘")
        # token_indices_for_flat_pairs: maps each of P_total_pairs back to its original token index (0 to NUM_TOKENS-1)
        token_indices_for_flat_pairs = (
            torch.arange(NUM_TOKENS, device=x.device).unsqueeze(1).expand(-1, self.K).reshape(-1)
        )

        # perm_indices: sorts original_expert_flat. Applying this to other P_total_pairs-length tensors reorders them accordingly.
        # Using stable sort to maintain original token order among those mapped to the same expert.
        perm_indices = torch.argsort(original_expert_flat, stable=True)

        # Create sorted versions of expert indices and the token indices that x_flat should be gathered with
        sorted_expert_indices = original_expert_flat[perm_indices]
        # sorted_token_indices_for_pairs determines which row from x_flat to pick for each sorted pair
        _sorted_original_token_indices = token_indices_for_flat_pairs[perm_indices]

        # Gather x_flat based on the sorted order to create input for Kernel 1
        # x_data_for_sorted_pairs will have shape (P_total_pairs, H)
        x_data_for_sorted_pairs = x_flat[_sorted_original_token_indices].contiguous()
        _maybe_profile("permutation done ↗")

        # Buffer for Kernel 1 output (will be in sorted order)
        fbuf_sorted = torch.empty(
            (P_total_pairs, self.D_exp), device=self.device, dtype=torch.float16
        )

        # Output buffer for final routed results
        obuf = torch.zeros((NUM_TOKENS, H), device=self.device, dtype=torch.float16)

        # --- Kernel 1 (on sorted data) ---
        k1_grid_dim0 = P_total_pairs
        k1_grid_dim1 = (self.D_exp + FIXED_BLOCK_D_OUT_K1 - 1) // FIXED_BLOCK_D_OUT_K1
        k1_grid = (k1_grid_dim0, k1_grid_dim1)

        _maybe_profile(f"launch kernel 1 (sorted) grid={k1_grid} ↘")
        _compute_fused_kernel_on_sorted_data[k1_grid](
            x_data_for_sorted_pairs,  # (P_total_pairs, H_dim)
            sorted_expert_indices,  # (P_total_pairs)
            self.W_gate,
            self.W_up,
            fbuf_sorted,  # Output: (P_total_pairs, D_exp)
            P_total_pairs=P_total_pairs,
            H_DIM=H,
            D_EXP=self.D_exp,
            BLOCK_D_EXP_K1=FIXED_BLOCK_D_OUT_K1,
            BLOCK_H_IN_K1=CHOSEN_K1_BLOCK_H_IN,
            num_warps=4,  # May need tuning, e.g. 2 or 4
            num_stages=1,  # May need tuning, e.g. 1 or 2
        )
        _maybe_profile("kernel 1 (sorted) done ↗")

        # --- Un-permutation Step (PyTorch gather) ---
        _maybe_profile("start un-permutation ↘")
        # We need fbuf_sorted back in the original pair order for Kernel 2.
        # unperm_indices[original_pair_pos] = sorted_pair_pos
        # So, fbuf_for_k2[original_pair_pos] = fbuf_sorted[unperm_indices[original_pair_pos]]
        # This is: fbuf_for_k2 = fbuf_sorted[torch.argsort(perm_indices)]
        unperm_indices = torch.argsort(perm_indices)
        fbuf_for_k2 = fbuf_sorted[unperm_indices].contiguous()  # Ensure contiguity for Kernel 2
        _maybe_profile("un-permutation done ↗")

        # --- Kernel 2 (original kernel, on un-permuted fbuf_for_k2) ---
        k2_grid = (NUM_TOKENS, (H + FIXED_BLOCK_H_OUT_K2 - 1) // FIXED_BLOCK_H_OUT_K2)
        _maybe_profile(f"launch kernel 2 grid={k2_grid} ↘")
        _project_and_accumulate_kernel_optimized_v2[k2_grid](
            fbuf_for_k2,  # Input: (P_total_pairs, D_exp), in original pair order
            original_expert_flat,  # Input: (P_total_pairs), original expert_id for each pair
            original_rout_flat,  # Input: (P_total_pairs), original routing weight for each pair
            self.W_down,
            obuf,
            NUM_TOKENS=NUM_TOKENS,
            H_DIM=H,
            D_EXP=self.D_exp,
            TOP_K=self.K,
            FIXED_BLOCK_H_OUT_K2=FIXED_BLOCK_H_OUT_K2,
            BLOCK_D_K2=CHOSEN_K2_BLOCK_D_K2,
            num_warps=4,  # Default from triton if not specified, can tune.
            num_stages=2,  # Default from triton if not specified, can tune.
        )
        _maybe_profile("kernel 2 done ↗")

        routed = obuf.reshape(B, T, H)
        shared = self.shared_expert(x_fp16)  # Pass x_fp16 to shared expert
        return routed + shared


def _stack_t(weights, key_tmpl: str, n, out_shape):
    mats = [weights[key_tmpl.format(i)].t() for i in range(n)]
    return torch.stack(mats, dim=0).reshape(out_shape).contiguous()


def custom_kernel(data):
    x, weights, config = data
    device = x.device
    _maybe_profile("construct module")
    moe = TritonMoE(config, device=device)
    _maybe_profile("module initialized")
    moe.load_weights_fast(weights)
    _maybe_profile("weights loaded")
    # x is already prepped to device and dtype in the forward pass of TritonMoE
    with torch.no_grad():
        out = moe(x)  # x will be cast to fp16 inside moe.forward if needed
    _maybe_profile("forward done")
    return out
python eval.py test /tmp/tmpmy3ozchq