"""GQA prefill kernel — Case 1 (Cube-SP × PE-TP) at single-KV-head group.

Per GQA_full_deck.pptx slide 11 (prefill counterpart, T_q ≫ 1):
  - K, V split S_kv-wise across the 8 cubes (cube=row_wise);
    replicated within each cube (pe=replicate). Each cube owns
    ``S_local = S_kv / C``.
  - Q, O split T_q-wise across cubes AND across PEs intra-cube
    (cube=row_wise, pe=row_wise on T_q). Each rank owns disjoint
    ``T_q_local = T_q / (C · P)`` query rows.
  - Inter-CUBE Ring KV (snake over 4×2 sub-mesh, ADR-0060 §5.5):
    P parallel rings — each PE drives its own same-lane ring via
    independent IPCQ channels. Over C ring steps the cube-owned
    K/V blocks rotate through all C cubes, so every rank sees
    every block.
  - NO inter-CUBE reduce — each rank writes its own disjoint
    T_q_local rows of O.
  - NO intra-CUBE reduce — PEs are disjoint on T_q.

Distinction from decode Case 1: decode T_q=1 makes PE-TP wasteful
(only PE 0 of each cube works). Prefill T_q≫1 makes PE-TP useful —
all 64 ranks work on disjoint Q rows.

Tensor layout:
  Q : (T_q, h_q · d_head) sharded (cube_row_wise, pe_row_wise) on T_q;
      each rank loads ``(G · T_q_local, d_head)``.
  K : (S_kv, h_kv · d_head) with cube=row_wise, pe=replicate — each
      cube's PE 0..P-1 each hold an HBM copy of the cube's
      ``(S_local, h_kv·d_head)`` shard.
  V : same as K.
  O : (T_q, h_q · d_head) sharded same as Q — each rank writes its
      own ``(G · T_q_local, d_head)`` slice.

Topology / SFR:
  - Requires ``configure_sfr_intercube_ring(submesh_shape=(2, 4))``
    for the snake E/W ring across 8 cubes (wrap from cube 3 ↔ cube 7).

Requires ``T_q % (C · P) == 0``.
"""
from __future__ import annotations


TILE_S_KV = 1024  # ADR-0063 §A.2 S_kv-axis tile sweep (per-tile width).


def _merge_running(m_local, l_local, O_local, m_other, l_other, O_other, *, tl):
    """Online-softmax merge of two partial ``(m, ℓ, O)`` triples."""
    m_new = tl.maximum(m_local, m_other)
    scale_old = tl.exp(m_local - m_new)
    scale_new = tl.exp(m_other - m_new)
    l_new = l_local * scale_old + l_other * scale_new
    O_new = O_local * scale_old + O_other * scale_new
    return m_new, l_new, O_new


def gqa_attention_prefill_long_ctx_cube_sp_pe_tp_kernel(
    q_ptr: int,
    k_ptr: int,
    v_ptr: int,
    o_ptr: int,
    T_q: int,
    S_kv: int,
    h_q: int,
    h_kv: int,
    d_head: int,
    C: int,
    P: int,
    *,
    tl,
) -> None:
    """Case-1 prefill: Ring KV across cubes; disjoint T_q rows per rank."""
    if T_q % (C * P) != 0:
        raise ValueError(
            f"Case 1 prefill requires T_q={T_q} divisible by C·P={C * P}"
        )

    G = h_q // h_kv
    T_q_local = T_q // (C * P)
    S_local = S_kv // C
    KV_ROW_BYTES = d_head * 2  # f16
    n_tiles = (S_local + TILE_S_KV - 1) // TILE_S_KV

    # Q is this rank's own disjoint T_q slice (G·T_q_local rows for the
    # G-grouped attention).
    Q = tl.load(q_ptr, shape=(G * T_q_local, d_head), dtype="f16")

    # ── Bootstrap (t=0, k=0): load own cube's tile 0; send W for ring ──
    # Persistent (m, ℓ, O) must live OUTSIDE tl.scratch_scope (kernbench
    # scope teardown discards in-scope tensors). Mirrors decode Cases
    # 1, 3, 4 and the existing prefill_long bootstrap pattern.
    tile_s = min(TILE_S_KV, S_local)
    K_T = tl.load(k_ptr, shape=(d_head, tile_s), dtype="f16")
    V = tl.load(v_ptr, shape=(tile_s, d_head), dtype="f16")
    if C > 1:
        tl.send(dir="W", src=K_T)
        tl.send(dir="W", src=V)
    scores = tl.dot(Q, K_T)
    m_local = tl.max(scores, axis=-1)
    exp_scores = tl.exp(scores - m_local)
    l_local = tl.sum(exp_scores, axis=-1)
    O_local = tl.dot(exp_scores, V)

    # ── Nested loop (outer tile, inner ring step) ──
    # Each tile propagates around the ring before the next tile starts;
    # IPCQ in-flight depth stays at 1 per direction per PE-lane.
    for t in range(n_tiles):
        tile_start = t * TILE_S_KV
        tile_s = min(TILE_S_KV, S_local - tile_start)
        k_start = 1 if t == 0 else 0
        for k in range(k_start, C):
            with tl.scratch_scope():
                if k == 0:
                    K_T_t = tl.load(k_ptr + tile_start * KV_ROW_BYTES,
                                    shape=(d_head, tile_s), dtype="f16")
                    V_t = tl.load(v_ptr + tile_start * KV_ROW_BYTES,
                                  shape=(tile_s, d_head), dtype="f16")
                else:
                    K_T_t = tl.recv(dir="E", shape=(d_head, tile_s), dtype="f16")
                    V_t = tl.recv(dir="E", shape=(tile_s, d_head), dtype="f16")
                if k < C - 1:
                    tl.send(dir="W", src=K_T_t)
                    tl.send(dir="W", src=V_t)
                scores_t = tl.dot(Q, K_T_t)
                m_step = tl.max(scores_t, axis=-1)
                exp_scores_t = tl.exp(scores_t - m_step)
                l_step = tl.sum(exp_scores_t, axis=-1)
                O_step = tl.dot(exp_scores_t, V_t)
                m_new, l_new, O_new = _merge_running(
                    m_local, l_local, O_local, m_step, l_step, O_step, tl=tl,
                )
                tl.copy_to(m_local, m_new)
                tl.copy_to(l_local, l_new)
                tl.copy_to(O_local, O_new)

    # ── Final normalise + store (every rank writes its own T_q_local rows) ──
    O_final = O_local / l_local
    tl.store(o_ptr, O_final)
