"""Runtime scalar and vector indexing with indirect DMA."""

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

# ---------------------------------------------------------------------------
# Gather and scatter
# ---------------------------------------------------------------------------


# NKI_EXAMPLE_TILED_GRID_GATHER_KERNEL_BEGIN
@nki.jit
def gather_kernel(data, indices):
    """Gather rows in index tiles, including a partial final index tile."""
    # data is a 2D tensor, for example (512, 1024).
    # indices is a 2D index tensor, for example (200, 1). Its final tile has
    # 72 indices when tile_shape is (128, 1).
    out = nl.ndarray(
        (indices.shape[0], data.shape[1]), dtype=data.dtype, buffer=nl.shared_hbm
    )
    data_tiles = nl.tiles(data, tile_shape=(128, 512))
    index_tiles = nl.tiles(indices, tile_shape=(128, 1))
    out_tiles = nl.tiles(out, tile_shape=(128, 512))

    for i in range(out_tiles.shape[0]):
        index_view = index_tiles[i, 0]
        index_sbuf = nl.empty_like(index_view.data, buffer=nl.sbuf)
        nisa.dma_copy(dst=index_sbuf, src=index_view.data)
        for j in range(out_tiles.shape[1]):
            src_view = data_tiles[index_sbuf, j]
            src_sbuf = nl.empty_like(src_view, buffer=nl.sbuf)
            nisa.dma_copy(dst=src_sbuf.data, src=src_view.data)
            nisa.dma_copy(dst=out_tiles[i, j].data, src=src_sbuf.data)
    return out


# NKI_EXAMPLE_TILED_GRID_GATHER_KERNEL_END


@nki.jit
def scatter_kernel(src, indices, out_rows):
    """Scatter source rows to ``out[indices[:, 0], :]``."""
    # src is a 2D tensor, for example (128, 1024).
    # indices is a 2D index tensor, for example (128, 1).
    out = nl.ndarray((out_rows, src.shape[1]), dtype=src.dtype, buffer=nl.shared_hbm)
    src_tiles = nl.tiles(src, tile_shape=(128, 512))
    index_tiles = nl.tiles(indices, tile_shape=(128, 1))
    out_tiles = nl.tiles(out, tile_shape=(128, 512))

    for i in range(src_tiles.shape[0]):
        index_view = index_tiles[i, 0]
        index_sbuf = nl.empty_like(index_view.data, buffer=nl.sbuf)
        nisa.dma_copy(dst=index_sbuf, src=index_view.data)
        for j in range(src_tiles.shape[1]):
            src_view = src_tiles[i, j]
            src_sbuf = nl.empty_like(src_view, buffer=nl.sbuf)
            nisa.dma_copy(dst=src_sbuf.data, src=src_view.data)
            nisa.dma_copy(dst=out_tiles[index_sbuf, j].data, src=src_sbuf.data)
    return out


@nki.jit
def scalar_gather_dim0(data, row_index):
    """Select one row using an SBUF scalar index."""
    # data is a 2D tensor, for example (128, 512).
    # row_index is a 2D scalar tensor, for example (1, 1).
    index_sbuf = nl.ndarray((1, 1), dtype=row_index.dtype, buffer=nl.sbuf)
    nisa.dma_copy(dst=index_sbuf, src=row_index)
    data_tiles = nl.tiles(data, tile_shape=(1, data.shape[1]))
    src_view = data_tiles[index_sbuf, 0]
    src_sbuf = nl.empty_like(src_view, buffer=nl.sbuf)
    out = nl.ndarray(src_view.element_shape, dtype=data.dtype, buffer=nl.shared_hbm)
    nisa.dma_copy(dst=src_sbuf.data, src=src_view.data)
    nisa.dma_copy(dst=out, src=src_sbuf.data)
    return out


@nki.jit
def scalar_gather_dim1(data, col_index):
    """Select one column using an SBUF scalar index."""
    # data is a 2D tensor, for example (128, 512).
    # col_index is a 2D scalar tensor, for example (1, 1).
    index_sbuf = nl.ndarray((1, 1), dtype=col_index.dtype, buffer=nl.sbuf)
    nisa.dma_copy(dst=index_sbuf, src=col_index)
    data_tiles = nl.tiles(data, tile_shape=(data.shape[0], 1))
    src_view = data_tiles[0, index_sbuf]
    src_sbuf = nl.empty_like(src_view, buffer=nl.sbuf)
    out = nl.ndarray(src_view.element_shape, dtype=data.dtype, buffer=nl.shared_hbm)
    nisa.dma_copy(dst=src_sbuf.data, src=src_view.data)
    nisa.dma_copy(dst=out, src=src_sbuf.data)
    return out


# ---------------------------------------------------------------------------
# Leading-dimension selection
# ---------------------------------------------------------------------------


@nki.jit
def expert_select(weights, expert_id_src):
    """Copy one expert's tiled weight matrix using a scalar register index."""
    # weights is a 3D tensor, for example (8, 256, 1024).
    # expert_id_src is a 2D scalar tensor, for example (1, 1).
    _, partition, free = weights.shape
    tile_shape = (128, 512)
    expert_id_sbuf = nl.ndarray((1, 1), dtype=expert_id_src.dtype, buffer=nl.sbuf)
    nisa.dma_copy(dst=expert_id_sbuf, src=expert_id_src)
    expert_id = nisa.scalar_load(expert_id_sbuf)

    src_tiles = nl.tiles(weights, tile_shape=tile_shape)
    out = nl.ndarray((partition, free), dtype=weights.dtype, buffer=nl.shared_hbm)
    out_tiles = nl.tiles(out, tile_shape=tile_shape)
    tile = nl.alloc_tiles(
        tile_shape=tile_shape,
        element_shape=tile_shape,
        dtype=weights.dtype,
        buffer=nl.sbuf,
    )

    for i in range(src_tiles.shape[1]):
        for j in range(src_tiles.shape[2]):
            nisa.dma_copy(dst=tile.data, src=src_tiles[expert_id, i, j].data)
            nisa.dma_copy(dst=out_tiles[i, j].data, src=tile.data)
    return out


# ---------------------------------------------------------------------------
# Runtime element offsets
# ---------------------------------------------------------------------------


@nki.jit
def runtime_add_logical_index(input_a, input_b, num_partition_tiles):
    """Add tiles selected by the compiled loop's logical tile coordinate."""
    # input_a and input_b are 2D tensors, for example (384, 1024).
    # num_partition_tiles is a 2D scalar tensor, for example (1, 1).
    partition_tile_extent = 128
    free_tile_extent = 512
    _, free = input_a.shape
    out = nl.ndarray(input_a.shape, dtype=input_a.dtype, buffer=nl.shared_hbm)
    tile_shape = (partition_tile_extent, free_tile_extent)
    a_tiles = nl.tiles(input_a, tile_shape=tile_shape)
    b_tiles = nl.tiles(input_b, tile_shape=tile_shape)
    out_tiles = nl.tiles(out, tile_shape=tile_shape)
    a_sbuf = nl.ndarray(tile_shape, dtype=input_a.dtype, buffer=nl.sbuf)
    b_sbuf = nl.ndarray(tile_shape, dtype=input_b.dtype, buffer=nl.sbuf)
    count_sbuf = nl.ndarray((1, 1), dtype=num_partition_tiles.dtype, buffer=nl.sbuf)
    nisa.dma_copy(dst=count_sbuf, src=num_partition_tiles)
    trip_count = nisa.scalar_load(count_sbuf)

    def add_row(i):
        for j in nl.affine_range(free // free_tile_extent):
            nisa.dma_copy(
                dst=a_sbuf,
                src=a_tiles[i, j].data,
            )
            nisa.dma_copy(
                dst=b_sbuf,
                src=b_tiles[i, j].data,
            )
            nisa.tensor_tensor(dst=a_sbuf, data1=a_sbuf, data2=b_sbuf, op=nl.add)
            nisa.dma_copy(
                dst=out_tiles[i, j].data,
                src=a_sbuf,
            )

    nl.fori_loop(0, trip_count, add_row)
    return out


@nki.jit
def runtime_add_element_offset(input_a, input_b, num_partition_tiles):
    """Add tiles selected by a reusable source-element row offset."""
    # input_a and input_b are 2D tensors, for example (384, 1024).
    # num_partition_tiles is a 2D scalar tensor, for example (1, 1).
    partition_tile_extent = 128
    free_tile_extent = 512
    _, free = input_a.shape
    out = nl.ndarray(input_a.shape, dtype=input_a.dtype, buffer=nl.shared_hbm)
    tile_shape = (partition_tile_extent, free_tile_extent)
    a_tiles = nl.tiles(input_a, tile_shape=tile_shape)
    b_tiles = nl.tiles(input_b, tile_shape=tile_shape)
    out_tiles = nl.tiles(out, tile_shape=tile_shape)
    row_step_elements = a_tiles.index_step_elements[0]
    a_sbuf = nl.ndarray(tile_shape, dtype=input_a.dtype, buffer=nl.sbuf)
    b_sbuf = nl.ndarray(tile_shape, dtype=input_b.dtype, buffer=nl.sbuf)
    row_offset_sbuf = nl.ndarray((1, 1), dtype=nl.int32, buffer=nl.sbuf)
    nisa.memset(dst=row_offset_sbuf, value=0)
    count_sbuf = nl.ndarray((1, 1), dtype=num_partition_tiles.dtype, buffer=nl.sbuf)
    nisa.dma_copy(dst=count_sbuf, src=num_partition_tiles)
    trip_count = nisa.scalar_load(count_sbuf)

    def add_row(i):
        offset = nl.grid_element_offset(row_offset_sbuf)
        for j in nl.affine_range(free // free_tile_extent):
            nisa.dma_copy(
                dst=a_sbuf,
                src=a_tiles[offset, j].data,
            )
            nisa.dma_copy(
                dst=b_sbuf,
                src=b_tiles[offset, j].data,
            )
            nisa.tensor_tensor(dst=a_sbuf, data1=a_sbuf, data2=b_sbuf, op=nl.add)
            nisa.dma_copy(
                dst=out_tiles[offset, j].data,
                src=a_sbuf,
            )
        nisa.tensor_scalar(
            dst=row_offset_sbuf,
            data=row_offset_sbuf,
            op0=nl.add,
            operand0=row_step_elements,
        )

    nl.fori_loop(0, trip_count, add_row)
    return out


# ---------------------------------------------------------------------------
# KV-cache indexing
# ---------------------------------------------------------------------------


@nki.jit
def kv_cache_load(cache, batch_id, position_src):
    """Load one KV vector using an SBUF scalar index."""
    # cache is a 3D tensor, for example (4, 256, 512).
    # position_src is a 2D scalar tensor, for example (1, 1).
    position_sbuf = nl.ndarray((1, 1), dtype=position_src.dtype, buffer=nl.sbuf)
    nisa.dma_copy(dst=position_sbuf, src=position_src)
    _, _, free = cache.shape
    cache_tiles = nl.tiles(cache, tile_shape=(1, free))
    src_view = cache_tiles[batch_id, position_sbuf, 0]
    src_sbuf = nl.empty_like(src_view, buffer=nl.sbuf)
    out = nl.ndarray(src_view.element_shape, dtype=cache.dtype, buffer=nl.shared_hbm)
    nisa.dma_copy(dst=src_sbuf.data, src=src_view.data)
    nisa.dma_copy(dst=out, src=src_sbuf.data)
    return out


@nki.jit
def kv_cache_multi_pos(cache, batch_indices, positions):
    """Gather several ``(batch, position)`` pairs with one indirect DMA."""
    # cache is a 3D tensor, for example (8, 256, 512).
    # batch_indices and positions are 2D index tensors, for example (128, 1).
    batch_count, sequence_length, feature_count = cache.shape
    selection_count = batch_indices.shape[0]
    flattened_cache = cache.reshape((batch_count * sequence_length, feature_count))
    cache_tiles = nl.tiles(flattened_cache, tile_shape=(128, feature_count))

    batch_sbuf = nl.ndarray(
        batch_indices.shape, dtype=batch_indices.dtype, buffer=nl.sbuf
    )
    position_sbuf = nl.ndarray(positions.shape, dtype=positions.dtype, buffer=nl.sbuf)
    flat_index_sbuf = nl.ndarray(
        (selection_count, 1), dtype=positions.dtype, buffer=nl.sbuf
    )
    nisa.dma_copy(dst=batch_sbuf, src=batch_indices)
    nisa.dma_copy(dst=position_sbuf, src=positions)
    nisa.tensor_scalar(
        dst=flat_index_sbuf, data=batch_sbuf, op0=nl.multiply, operand0=sequence_length
    )
    nisa.tensor_tensor(
        dst=flat_index_sbuf, data1=flat_index_sbuf, data2=position_sbuf, op=nl.add
    )

    src_view = cache_tiles[flat_index_sbuf, 0]
    src_sbuf = nl.empty_like(src_view, buffer=nl.sbuf)
    out = nl.ndarray(src_view.element_shape, dtype=cache.dtype, buffer=nl.shared_hbm)
    nisa.dma_copy(dst=src_sbuf.data, src=src_view.data)
    nisa.dma_copy(dst=out, src=src_sbuf.data)
    return out
