/**
 * Minimal debug: write P to SMEM + 1 PV SS MMA K-tile.
 * No QK, no TMEM softmax read, no V load.
 * Start from what test_pv_ss_128.cu does and add the P fill pattern.
 */

#include <cuda_runtime.h>
#include <cstdio>
#include <cstring>

#include "dsv4/kernels/attention/fmha_common.cuh"
#include "dsv4/kernels/attention/fmha_umma_desc.cuh"

using namespace dsv4::kernels::attention;

static bf16_t f32_to_bf16_host(float f) { uint32_t u; memcpy(&u,&f,4); return (uint16_t)(u>>16); }

constexpr int HD = 16, SK = 128, BLOCK_MN = 128;
constexpr int TILE_SZ = BLOCK_MN * MMA_K_BF16;

__global__ void __launch_bounds__(128)
test_minimal_pv()
{
    const int tid = threadIdx.x, wid = tid / 32, lane = tid % 32;

    extern __shared__ char sbuf[];
    uint32_t* sTmemBase = (uint32_t*)sbuf;
    bf16_t* sQ0 = (bf16_t*)(((uintptr_t)(sbuf + 4) + 15) & ~(uintptr_t)15);
    bf16_t* sK0 = sQ0 + TILE_SZ;
    bf16_t* sPk = (bf16_t*)(((uintptr_t)(sK0 + TILE_SZ) + 127) & ~(uintptr_t)127);
    bf16_t* sV = (bf16_t*)(((uintptr_t)(sPk + TILE_SZ) + 127) & ~(uintptr_t)127);
    float* s_p_vals = (float*)(sV + 256);  // 16 P values for 1 K-tile

    // Fill sQ0, sK0 (will be used by QK)
    for (int i = tid; i < TILE_SZ; i += 128) { sQ0[i] = 0; sK0[i] = 0; }
    __syncthreads();

    // Softmax: read S from TMEM, compute P, write to s_p_vals
    if (wid == 0) {
        float s_vals[16], row_max = -INFINITY;
        // Read first 16 columns of S (for K-tile 0)
        float tmp[8];
        asm volatile("tcgen05.ld.sync.aligned.32x32b.x8.b32 {%0,%1,%2,%3,%4,%5,%6,%7},[%8];"
            : "=f"(tmp[0]),"=f"(tmp[1]),"=f"(tmp[2]),"=f"(tmp[3]),
              "=f"(tmp[4]),"=f"(tmp[5]),"=f"(tmp[6]),"=f"(tmp[7])
            : "r"(tb));
        asm volatile("tcgen05.wait::ld.sync.aligned;");
        if (lane == 0) for (int c=0;c<8;c++) { s_vals[c] = tmp[c]; row_max = fmaxf(row_max, tmp[c]); }
        asm volatile("tcgen05.ld.sync.aligned.32x32b.x8.b32 {%0,%1,%2,%3,%4,%5,%6,%7},[%8];"
            : "=f"(tmp[0]),"=f"(tmp[1]),"=f"(tmp[2]),"=f"(tmp[3]),
              "=f"(tmp[4]),"=f"(tmp[5]),"=f"(tmp[6]),"=f"(tmp[7])
            : "r"(tb+8));
        asm volatile("tcgen05.wait::ld.sync.aligned;");
        if (lane == 0) for (int c=0;c<8;c++) { s_vals[8+c] = tmp[c]; row_max = fmaxf(row_max, tmp[c]); }
        row_max = wmax(row_max);
        float row_sum = 0.0f;
        if (lane == 0) for (int j=0;j<16;j++) { s_vals[j] = expf(s_vals[j] - row_max); row_sum += s_vals[j]; }
        row_sum = wsum(row_sum);
        if (lane == 0) for (int j=0;j<16;j++) { s_vals[j] /= row_sum; s_p_vals[j] = s_vals[j]; }
    }
    __syncthreads();

    // Fill sPk: (128, 16) canonical, row 0 = s_p_vals
    for (int i = tid; i < TILE_SZ; i += 128) sPk[i] = 0;
    __syncthreads();
    if (tid < 16) {
        int c = tid;
        int ck = c / 8, lc = c % 8;
        int dst_idx = ck * 16 * 64 + 0 * 64 + 0 * 8 + lc;
        sPk[dst_idx] = f32_to_bf16(s_p_vals[c]);
    }
    __syncthreads();

    // Fill sV: (16, 16) canonical, all 1.0
    for (int i = tid; i < 256; i += 128) sV[i] = 0;
    __syncthreads();
    for (int i = tid; i < 256; i += 128) {
        int r = i / 16, c = i % 16;
        int ck = c / 8, lc = c % 8, tmn = r / 8, lr = r % 8;
        sV[ck * 2 * 64 + tmn * 64 + lr * 8 + lc] = f32_to_bf16(1.0f);
    }
    __syncthreads();

    uint32_t tb = 0;
    // TMEM alloc
    if (wid == 1) tmem_alloc(__cvta_generic_to_shared(sTmemBase), 128);
    __syncthreads();
    tb = *sTmemBase;

    // QK GEMM (SS) — uses sQ0 and sK0
    {
        uint64_t dq = make_umma_desc_kmajor_none(__cvta_generic_to_shared(sQ0), BLOCK_MN);
        uint64_t dk = make_umma_desc_kmajor_none(__cvta_generic_to_shared(sK0), BLOCK_MN);
        uint32_t idesc = make_idesc(BLOCK_MN, BLOCK_MN);
        if (tid == 0) umma_ss_f16(tb, dq, dk, idesc, false);
        asm volatile("tcgen05.fence::after_thread_sync;" ::: "memory");
        __syncthreads();
    }

    // PV SS MMA
    uint64_t dp = make_umma_desc_kmajor_none(__cvta_generic_to_shared(sPk), BLOCK_MN);
    uint64_t dv = make_umma_desc_kmajor_none(__cvta_generic_to_shared(sV), 16);
    uint32_t idesc = make_idesc(BLOCK_MN, HD);
    if (tid == 0) umma_ss_f16(tb, dp, dv, idesc, false);
    asm volatile("tcgen05.fence::after_thread_sync;" ::: "memory");
    __syncthreads();

    // Read O
    if (wid == 0) {
        float tmp[8];
        asm volatile("tcgen05.ld.sync.aligned.32x32b.x8.b32 {%0,%1,%2,%3,%4,%5,%6,%7},[%8];"
            : "=f"(tmp[0]),"=f"(tmp[1]),"=f"(tmp[2]),"=f"(tmp[3]),
              "=f"(tmp[4]),"=f"(tmp[5]),"=f"(tmp[6]),"=f"(tmp[7])
            : "r"(tb));
        asm volatile("tcgen05.wait::ld.sync.aligned;");
        if (lane == 0) { printf("O[0,0..7]: "); for(int c=0;c<8;c++) printf("%.1f ", tmp[c]); printf("(expect 8.0)\n"); }
    }

    if (wid == 0) tmem_dealloc(tb, 128);
}

int main() {
    printf("=== Minimal PV with s_p_vals ===\n");
    int smem = (4+16 + TILE_SZ*2 + TILE_SZ*2 + TILE_SZ*2 + 256*2 + 16*4 + 256 + 127) & ~127;
    printf("SMEM: %d bytes\n", smem);
    test_minimal_pv<<<1, 128, smem>>>();
    cudaError_t err = cudaDeviceSynchronize();
    if (err != cudaSuccess) { printf("CUDA ERROR: %s\n", cudaGetErrorString(err)); return 1; }
    return 0;
}
