"""MLP CTE: single-rank MLP SwiGLU kernel using tiled grids.

Computes ``y = (silu(x @ gate) * (x @ up)) @ down`` for a single rank with
M-axis sharding for LNC.
"""

from dataclasses import dataclass, field
from typing import Any

import nki
import nki.isa as nisa
import nki.language as nl
from nki.language import NKIObject


def _ceiling_div(dividend, divisor):
    return (dividend + divisor - 1) // divisor


def _largest_divisor(value, *, max_val):
    for divisor in range(min(value, max_val), 0, -1):
        if value % divisor == 0:
            return divisor
    raise ValueError("value must be positive")


@dataclass(frozen=True)
class MLPConfig(NKIObject):
    """Configuration for the single-rank MLP SwiGLU kernel.

    Args:
        K: Input hidden dimension (matmul reduction dim of gate/up).
        I: Intermediate dimension between gate/up and down projections.
        H: Output hidden dimension (matmul output dim of down projection).
        tile_m: M-dim tile size in elements.
        tile_k: K-dim tile size in elements.
        tile_i: I-dim tile size for gate/up matmuls in elements.
        tile_down_i: I-dim tile size for the down projection in elements.
        tile_h: H-dim tile size in elements.
        projection_slots: Rotating SBUF slots for gate/up weight streams.
        down_slots: Rotating SBUF slots for the down-weight stream.
        block_m: Number of M tiles processed per activation block.
        dge_mode: DMA gather/scatter mode passed to weight loads.

    Notes:
        Frozen=True is required for JAX tracing compatibility (kernel args
        must be hashable and immutable). The K, I, and H block sizes are
        derived in ``__post_init__``.
    """

    K: int
    I: int  # noqa: E741 - Matches standard MLP intermediate-dimension notation.
    H: int
    tile_m: int = 128
    tile_k: int = 128
    tile_i: int = 512
    tile_down_i: int = 128
    tile_h: int = 512
    projection_slots: int = 2
    down_slots: int = 2
    block_m: int = 2
    dge_mode: Any = nisa.dge_mode.unknown
    block_k: int = field(init=False)
    block_i: int = field(init=False)
    block_h: int = field(init=False)

    def __post_init__(self):
        assert self.K % self.tile_k == 0, (
            f"K={self.K} must be divisible by tile_k={self.tile_k}"
        )
        assert self.I % self.tile_down_i == 0, (
            f"I={self.I} must be divisible by tile_down_i={self.tile_down_i}. "
            "Non-square transpose remainder not yet supported."
        )
        assert self.H % self.tile_h == 0, (
            f"H={self.H} must be divisible by tile_h={self.tile_h}"
        )
        assert self.projection_slots >= 2, "projection_slots must be at least 2"
        assert self.down_slots >= 2, "down_slots must be at least 2"
        assert 1 <= self.block_m <= 8, "block_m must be between 1 and 8"

        object.__setattr__(
            self,
            "block_k",
            _largest_divisor(self.K // self.tile_k, max_val=8),
        )
        object.__setattr__(
            self,
            "block_i",
            _largest_divisor(self.I // self.tile_down_i, max_val=4),
        )
        object.__setattr__(
            self,
            "block_h",
            _largest_divisor(
                self.H // self.tile_h,
                max_val=min(4, 8 // self.block_m),
            ),
        )


# ---------------------------------------------------------------------------
# Helpers
# ---------------------------------------------------------------------------


# NKI_EXAMPLE_TILED_GRID_TRANSPOSE_IN_PLACE_BEGIN
def transpose_in_place(block_sbuf):
    """Transpose (tile_p x tile_p) subtiles in-place via PSUM bank pipelining.

    Re-tiles the block into square subtiles, transposes each through PSUM,
    and writes back to the same SBUF location. Interleaves across PSUM banks
    for pipeline efficiency, then bulk-copies each whole bank back to SBUF
    (one tensor_copy per bank, not per subtile).

    Args:
        block_sbuf: NKI SBUF block or tile-grid view.

    Returns:
        The same allocation with each square subtile transposed.
    """
    PSUM_SLOT_SIZE = 512
    NUM_HW_BANKS = 8

    tile_p = block_sbuf.tile_shape[0]

    # Retile the resident block into square Tensor Engine operands.
    tiles_sbuf = nl.tiles(block_sbuf, tile_shape=(tile_p, tile_p))
    tiles_per_bank = min(tiles_sbuf.shape[1], PSUM_SLOT_SIZE // tile_p)

    # Group square tiles by PSUM bank for coalesced copyback.
    sbuf_banks = nl.blocks(
        tiles_sbuf,
        block_shape=(1, tiles_per_bank),
    )
    num_rows, num_banks = sbuf_banks.shape
    assert num_banks <= NUM_HW_BANKS

    for i in range(num_rows):
        # One PSUM tile per bank slot lets each completed bank copy back as
        # one contiguous region.
        transpose_psum = nl.alloc_tiles(
            tile_shape=(tile_p, tile_p),
            element_shape=(num_banks * tile_p, tiles_per_bank * tile_p),
            buffer=nl.psum,
            dtype=block_sbuf.dtype,
        )

        # Phase 1: SBUF -> PSUM transposes, fanned across banks (interleaved
        # for pipelining).
        for j in range(tiles_per_bank):
            for k in range(num_banks):
                bank_view = nl.tiles(sbuf_banks[i, k])
                if j < bank_view.shape[1]:
                    nisa.nc_transpose(
                        transpose_psum[k, j].data,
                        bank_view[0, j].data,
                    )
        # Phase 2: bulk PSUM -> SBUF copy-back -- one tensor_copy per bank
        # with the whole bank addressed as a single contiguous F-slab on the
        # SBUF side.
        for k in range(num_banks):
            bank_view = nl.tiles(sbuf_banks[i, k])
            nisa.tensor_copy(
                bank_view.data,
                transpose_psum[k, : bank_view.shape[1]].data,
            )

    return block_sbuf


# NKI_EXAMPLE_TILED_GRID_TRANSPOSE_IN_PLACE_END


# ---------------------------------------------------------------------------
# Stage 2 -- Gate/Up Projection + SwiGLU Activation
# ---------------------------------------------------------------------------


# NKI_EXAMPLE_TILED_GRID_COMPUTE_SWIGLU_BEGIN
def compute_swiglu(x_sbuf, gate, up, bias_sbuf, config: MLPConfig):
    """Compute ``silu(x @ gate) * (x @ up)`` one I group at a time.

    Args:
        x_sbuf: SBUF block view of the input ``[M, K]`` for one shard.
        gate: NKI HBM block view of the gate weights ``[K, I]``.
        up: NKI HBM block view of the up weights ``[K, I]``.
        bias_sbuf: SBUF tile providing the SiLU bias, typically zeros.
        config: Kernel configuration carrying tile/block sizes and DGE mode.

    Returns:
        SBUF tile grid containing the ``[M, I]`` SwiGLU result.
    """
    assert isinstance(x_sbuf, nl.NkiBlockGrid), (
        "x_sbuf must preserve the K-block dimension"
    )
    assert x_sbuf.element_shape[1] == config.K, (
        "x must span full K for correct accumulation"
    )
    assert x_sbuf.shape[0] == gate.shape[0]
    assert x_sbuf.shape[0] == up.shape[0]

    tile_m = x_sbuf.tile_shape[0]
    m_tiles = nl.tiles(x_sbuf).shape[0]
    tile_i = gate.tile_shape[1]
    dtype = gate.dtype
    i_tiles = gate.shape[1]

    # Each (M tile, I tile) pair needs one of the eight PSUM tiles.
    max_i_per_group = 8 // m_tiles
    assert max_i_per_group > 0, "activation block exceeds PSUM capacity"
    has_i_remainder = (config.I % tile_i) != 0
    if has_i_remainder and i_tiles > 1:
        max_i_per_group = min(max_i_per_group, i_tiles - 1)
    i_groups = _ceiling_div(i_tiles, max_i_per_group)

    # Allocate SBUF for the complete SwiGLU result across all I groups.
    gated_sbuf = nl.alloc_tiles(
        tile_shape=(tile_m, tile_i),
        element_shape=(x_sbuf.element_shape[0], gate.element_shape[1]),
        buffer=nl.sbuf,
        dtype=dtype,
    )

    for i_group in range(i_groups):
        # Select one I group that fits the eight-PSUM budget.
        i_start = i_group * max_i_per_group
        i_count = min(max_i_per_group, i_tiles - i_start)
        gated_group = gated_sbuf[:, i_start : i_start + i_count]
        gate_view = gate[:, i_start : i_start + i_count]
        up_view = up[:, i_start : i_start + i_count]

        # Gate projection: stream gate weights and accumulate x @ gate.
        psum_element_shape = (
            x_sbuf.element_shape[0],
            gate_view.element_shape[1],
        )
        gate_psum = nl.alloc_tiles(
            tile_shape=(tile_m, tile_i),
            element_shape=psum_element_shape,
            buffer=nl.psum,
            dtype=nl.float32,
        )
        gate_sbufs = nl.alloc_stream_buffers(
            gate_view,
            buffer=nl.sbuf,
            dim=0,
            num_slots=config.projection_slots,
        )

        # Gate prologue: load the first narrowed K-block row.
        nisa.dma_copy(
            dst=gate_sbufs[0].data,
            src=gate_view[0].data,
            dge_mode=config.dge_mode,
        )

        for k_block in range(gate_view.shape[0]):
            # Prefetch the next gate row while computing the current row.
            if k_block + 1 < gate_view.shape[0]:
                nisa.dma_copy(
                    dst=gate_sbufs[k_block + 1].data,
                    src=gate_view[k_block + 1].data,
                    dge_mode=config.dge_mode,
                )

            x_tiles = nl.tiles(x_sbuf[k_block])
            gate_tiles = nl.tiles(gate_sbufs[k_block])
            for m_tile in range(m_tiles):
                for k_tile in range(gate_tiles.shape[0]):
                    for i_tile in range(i_count):
                        nisa.nc_matmul(
                            dst=gate_psum[m_tile, i_tile].data,
                            stationary=x_tiles[m_tile, k_tile].data,
                            moving=gate_tiles[k_tile, i_tile].data,
                            accumulate=k_block > 0 or k_tile > 0,
                        )

        # Move SiLU(gate) to SBUF before reusing PSUM for the up projection.
        for m_tile in range(m_tiles):
            for i_tile in range(i_count):
                nisa.activation(
                    gated_group[m_tile, i_tile].data,
                    op=nl.silu,
                    data=gate_psum[m_tile, i_tile].data,
                    bias=bias_sbuf,
                )

        # Up projection: reuse the PSUM budget to accumulate x @ up.
        up_psum = nl.alloc_tiles(
            tile_shape=(tile_m, tile_i),
            element_shape=psum_element_shape,
            buffer=nl.psum,
            dtype=nl.float32,
        )
        up_sbufs = nl.alloc_stream_buffers(
            up_view,
            buffer=nl.sbuf,
            dim=0,
            num_slots=config.projection_slots,
        )

        # Up prologue: load the first narrowed K-block row.
        nisa.dma_copy(
            dst=up_sbufs[0].data,
            src=up_view[0].data,
            dge_mode=config.dge_mode,
        )

        for k_block in range(up_view.shape[0]):
            # Prefetch the next up row while computing the current row.
            if k_block + 1 < up_view.shape[0]:
                nisa.dma_copy(
                    dst=up_sbufs[k_block + 1].data,
                    src=up_view[k_block + 1].data,
                    dge_mode=config.dge_mode,
                )

            x_tiles = nl.tiles(x_sbuf[k_block])
            up_tiles = nl.tiles(up_sbufs[k_block])
            for m_tile in range(m_tiles):
                for k_tile in range(up_tiles.shape[0]):
                    for i_tile in range(i_count):
                        nisa.nc_matmul(
                            dst=up_psum[m_tile, i_tile].data,
                            stationary=x_tiles[m_tile, k_tile].data,
                            moving=up_tiles[k_tile, i_tile].data,
                            accumulate=k_block > 0 or k_tile > 0,
                        )

        # Multiply the up result into the resident SiLU(gate) SBUF tiles.
        for m_tile in range(m_tiles):
            for i_tile in range(i_count):
                nisa.tensor_tensor(
                    gated_group[m_tile, i_tile].data,
                    gated_group[m_tile, i_tile].data,
                    up_psum[m_tile, i_tile].data,
                    op=nl.multiply,
                )

    return gated_sbuf


# NKI_EXAMPLE_TILED_GRID_COMPUTE_SWIGLU_END


# ---------------------------------------------------------------------------
# Stage 3 -- Down Projection
# ---------------------------------------------------------------------------


# NKI_EXAMPLE_TILED_GRID_COMPUTE_DOWN_MATMUL_BEGIN
def compute_down_matmul(gated_t_sbuf, down, config: MLPConfig):
    """Compute the down projection with a resident activation block.

    Args:
        gated_t_sbuf: Transposed gated activations in SBUF.
        down: NKI HBM block view of the down weights ``[I, H]``.
        config: Kernel configuration carrying tile/block sizes and DGE mode.

    Returns:
        SBUF block grid containing the ``[M, H]`` result.
    """
    assert isinstance(down, nl.NkiBlockGrid), "down must be a block view"

    tile_i_down, tile_h = down.tile_shape
    block_i, block_h = down.block_shape
    tile_m = gated_t_sbuf.tile_shape[0]
    h_blocks = down.shape[1]

    # Retile the resident SwiGLU block for the down projection.
    gated_t_tiles = nl.tiles(gated_t_sbuf, tile_shape=(tile_i_down, tile_m))
    m_tiles = gated_t_tiles.shape[0]

    # Allocate SBUF for the complete output block.
    out_sbuf = nl.alloc_blocks(
        tile_shape=(tile_m, tile_h),
        block_shape=(m_tiles, block_h),
        element_shape=(gated_t_sbuf.element_shape[0], down.element_shape[1]),
        buffer=nl.sbuf,
        dtype=nl.bfloat16,
    )

    for h_block in range(h_blocks):
        # Accumulate one H block while streaming down weights over I.
        down_view = down[:, h_block]
        out_psum = nl.alloc_tiles(
            tile_shape=(tile_m, tile_h),
            element_shape=(m_tiles * tile_m, block_h * tile_h),
            buffer=nl.psum,
            dtype=nl.float32,
        )

        # Allocate rotating SBUF slots and load the first weight block.
        down_sbufs = nl.alloc_stream_buffers(
            down_view,
            buffer=nl.sbuf,
            dim=0,
            num_slots=config.down_slots,
        )
        nisa.dma_copy(
            dst=down_sbufs[0].data,
            src=down_view[0].data,
            dge_mode=config.dge_mode,
        )

        for i_block in range(down_view.shape[0]):
            # Prefetch I block i_block + 1 while computing I block i_block.
            if i_block + 1 < down_view.shape[0]:
                nisa.dma_copy(
                    dst=down_sbufs[i_block + 1].data,
                    src=down_view[i_block + 1].data,
                    dge_mode=config.dge_mode,
                )

            down_tiles = nl.tiles(down_sbufs[i_block])
            i_tile_count = down_tiles.shape[0]
            i_start = i_block * block_i
            gated_view = gated_t_tiles[:, i_start : i_start + i_tile_count]

            for m_tile in range(m_tiles):
                for i_tile in range(i_tile_count):
                    for h_tile in nl.affine_range(block_h):
                        nisa.nc_matmul(
                            dst=out_psum[m_tile, h_tile].data,
                            stationary=gated_view[m_tile, i_tile].data,
                            moving=down_tiles[i_tile, h_tile].data,
                            accumulate=i_block > 0 or i_tile > 0,
                        )

        # Move completed PSUM tiles into the SBUF output block.
        out_tiles = nl.tiles(out_sbuf[0, h_block])
        for m_tile in range(m_tiles):
            for h_tile in nl.affine_range(block_h):
                nisa.tensor_copy(
                    dst=out_tiles[m_tile, h_tile].data,
                    src=out_psum[m_tile, h_tile].data,
                )

    return out_sbuf


# NKI_EXAMPLE_TILED_GRID_COMPUTE_DOWN_MATMUL_END


# ---------------------------------------------------------------------------
# Kernel -- MLP CTE
# ---------------------------------------------------------------------------


# NKI_EXAMPLE_TILED_GRID_MLP_CTE_BEGIN
@nki.jit
def mlp_cte(
    x: nl.NkiTensor,
    gate_proj: nl.NkiTensor,
    up_proj: nl.NkiTensor,
    down_proj: nl.NkiTensor,
    config: MLPConfig,
) -> nl.NkiTensor:
    """Single-rank Context Encoding MLP using tiled grids.

    Computes ``y = (silu(x @ gate_proj) * (x @ up_proj)) @ down_proj`` for a
    single rank with M-axis sharding across logical NeuronCores.

    Dimensions:
        B: Batch size
        S: Sequence length
        K: Input hidden dimension and gate/up reduction dimension
        I: Intermediate dimension between gate/up and down
        H: Output hidden dimension
        M: Flattened B * S

    Args:
        x (nl.NkiTensor): [B, S, K] input hidden states in HBM.
        gate_proj (nl.NkiTensor): [K, I] gate projection weights in HBM.
        up_proj (nl.NkiTensor): [K, I] up projection weights in HBM.
        down_proj (nl.NkiTensor): [I, H] down projection weights in HBM.
        config (MLPConfig): Kernel configuration (tile/block sizes, buffering).

    Returns:
        out (nl.NkiTensor): [B, S, H] MLP result in HBM.

    Notes:
        - LNC sharding partitions the M = B * S axis across cores; each core
          processes its slice of x_blocks and writes its slice of
          out_blocks.
        - Two activation slots allow the next owned block to load while the
          current block moves through the projection stages.
    """
    assert len(x.shape) == 3, "x must be [B, S, K]"
    batch, sequence, k_size = x.shape
    assert k_size == config.K, "x hidden size must equal config.K"
    assert gate_proj.shape == (config.K, config.I)
    assert up_proj.shape == (config.K, config.I)
    assert down_proj.shape == (config.I, config.H)

    # Flatten batch and sequence, then define input and output block grids.
    m_size = batch * sequence
    assert m_size % config.tile_m == 0, (
        f"M={m_size} must be divisible by tile_m={config.tile_m}"
    )
    x = x.reshape((m_size, k_size))
    out = nl.ndarray(
        (m_size, config.H),
        dtype=x.dtype,
        buffer=nl.shared_hbm,
    )

    x_blocks = nl.blocks(
        x,
        tile_shape=(config.tile_m, config.tile_k),
        block_shape=(config.block_m, config.block_k),
    )
    out_blocks = nl.blocks(
        out,
        tile_shape=(config.tile_m, config.tile_h),
        block_shape=(config.block_m, config.H // config.tile_h),
    )

    # Define per-core sharding of input and output blocks.
    owned_m = nl.contiguous_indices(
        x_blocks.shape[0],
        shard_id=nl.program_id(0),
        num_shards=nl.num_programs(0),
    )
    x_view = x_blocks[owned_m]
    out_view = out_blocks[owned_m]

    # Create block-grid views for weights shared by all owned x blocks.
    gate = nl.blocks(
        gate_proj,
        tile_shape=(config.tile_k, config.tile_i),
        block_shape=(config.block_k, 1),
    )
    up = nl.blocks(
        up_proj,
        tile_shape=(config.tile_k, config.tile_i),
        block_shape=(config.block_k, 1),
    )
    down = nl.blocks(
        down_proj,
        tile_shape=(config.tile_down_i, config.tile_h),
        block_shape=(config.block_i, config.block_h),
    )

    # Allocate the SiLU bias once for all owned x blocks.
    bias_sbuf = nl.ndarray((config.tile_m, 1), dtype=nl.float32, buffer=nl.sbuf)
    nisa.memset(bias_sbuf, value=0.0)

    # Allocate rotating SBUF slots for x and load the first block (prologue).
    assert x_view.shape[0] > 0, "each program must own an activation block"
    x_sbufs = nl.alloc_stream_buffers(
        x_view,
        buffer=nl.sbuf,
        dim=0,
        num_slots=2,
    )
    nisa.dma_copy(
        dst=x_sbufs[0].data,
        src=x_view[0].data,
        dge_mode=config.dge_mode,
    )

    for m_block in range(x_view.shape[0]):
        # Prefetch x block m_block + 1 while computing x block m_block.
        if m_block + 1 < x_view.shape[0]:
            nisa.dma_copy(
                dst=x_sbufs[m_block + 1].data,
                src=x_view[m_block + 1].data,
                dge_mode=config.dge_mode,
            )

        # Run the fused MLP stages on the current resident x block.
        x_sbuf = x_sbufs[m_block]
        x_t_sbuf = transpose_in_place(x_sbuf)
        gated_sbuf = compute_swiglu(x_t_sbuf, gate, up, bias_sbuf, config)
        gated_t_sbuf = transpose_in_place(gated_sbuf)
        out_sbuf = compute_down_matmul(gated_t_sbuf, down, config)

        # Store the completed output block to this core's HBM view.
        nisa.dma_copy(
            dst=out_view[m_block].data,
            src=out_sbuf.data,
        )

    return out.reshape((batch, sequence, config.H))


# NKI_EXAMPLE_TILED_GRID_MLP_CTE_END
