/**
 * Test multi-row FMHA kernel (6-warp, T>1 prefill).
 * Compile with -DHD_VAL=64 etc.
 *
 * Tests:
 * 1. Single KV tile, T=1..128 (normalized output + LSE)
 * 2. Multi-tile KV via Python merge (s_k=256, 2 segments)
 * 3. Multi-head and batched launches
 */

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

#ifndef HD_VAL
#define HD_VAL 64
#endif

#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); }
static float bf16_to_f32_host(bf16_t h) { uint32_t u=(uint32_t)h<<16; float f; memcpy(&f,&u,4); return f; }

constexpr int HD = HD_VAL;
constexpr int SK = 128;
constexpr int MAX_T = 128;

#include "dsv4/kernels/attention/fmha_6warp_multirow.cuh"

static int compute_smem() {
    size_t off = 0;
    off += 4;                           // sTmemBase
    off += 128 * sizeof(float);         // sRowMax
    off += 128 * sizeof(float);         // sRowSum
    off = (off + 127) & ~(size_t)127;
    off += 128 * MMA_K_BF16 * sizeof(bf16_t);  // sQ0
    off += 128 * MMA_K_BF16 * sizeof(bf16_t);  // sK0
    off = (off + 127) & ~(size_t)127;
    off += 128 * MMA_K_BF16 * sizeof(bf16_t);  // sPk
    off = (off + 127) & ~(size_t)127;
    off += 16 * MMA_K_BF16 * sizeof(bf16_t);   // sV
    return (int)off;
}

static void reference_attention_multirow(
    const bf16_t* q, const bf16_t* k, const bf16_t* v,
    float* o_ref, float* lse_ref,
    int hd, int T, int s_k, float scale
) {
    for (int t = 0; t < T; t++) {
        float s[512];
        for (int j = 0; j < s_k; j++) {
            float dot = 0.0f;
            for (int d = 0; d < hd; d++)
                dot += bf16_to_f32_host(q[t * hd + d]) * bf16_to_f32_host(k[j * hd + d]);
            s[j] = dot * scale;
        }
        float mx = -INFINITY;
        for (int j = 0; j < s_k; j++) mx = fmaxf(mx, s[j]);
        float sm = 0.0f;
        for (int j = 0; j < s_k; j++) { s[j] = expf(s[j] - mx); sm += s[j]; }
        for (int j = 0; j < s_k; j++) s[j] /= sm;
        for (int d = 0; d < hd; d++) {
            float ov = 0.0f;
            for (int j = 0; j < s_k; j++) ov += s[j] * bf16_to_f32_host(v[d * s_k + j]);
            o_ref[t * hd + d] = ov;
        }
        if (lse_ref) lse_ref[t] = logf(sm) + mx;
    }
}

static int test_single(int T, int n_h = 1, int batch = 1) {
    printf("\n=== T=%d, n_h=%d, batch=%d, HD=%d ===\n", T, n_h, batch, HD);
    const float SCALE = 1.0f / sqrtf((float)HD);
    int total_heads = batch * n_h;

    bf16_t* h_q = (bf16_t*)malloc(total_heads * T * HD * sizeof(bf16_t));
    bf16_t* h_k = (bf16_t*)malloc(total_heads * SK * HD * sizeof(bf16_t));
    bf16_t* h_v = (bf16_t*)malloc(total_heads * HD * SK * sizeof(bf16_t));
    bf16_t* h_o = (bf16_t*)calloc(total_heads * T * HD, sizeof(bf16_t));
    float* h_lse = (float*)calloc(total_heads * T, sizeof(float));

    srand(42 + T);
    for (int i = 0; i < total_heads * T * HD; i++) h_q[i] = f32_to_bf16_host((float)(rand()%100)/100.0f - 0.5f);
    for (int i = 0; i < total_heads * SK * HD; i++) h_k[i] = f32_to_bf16_host((float)(rand()%100)/100.0f - 0.5f);
    for (int i = 0; i < total_heads * HD * SK; i++) h_v[i] = f32_to_bf16_host((float)(rand()%100)/100.0f - 0.5f);

    bf16_t *d_q, *d_k, *d_v, *d_o; float *d_lse;
    cudaMalloc(&d_q, total_heads * T * HD * sizeof(bf16_t));
    cudaMalloc(&d_k, total_heads * SK * HD * sizeof(bf16_t));
    cudaMalloc(&d_v, total_heads * HD * SK * sizeof(bf16_t));
    cudaMalloc(&d_o, total_heads * T * HD * sizeof(bf16_t));
    cudaMalloc(&d_lse, total_heads * T * sizeof(float));
    cudaMemcpy(d_q, h_q, total_heads * T * HD * sizeof(bf16_t), cudaMemcpyHostToDevice);
    cudaMemcpy(d_k, h_k, total_heads * SK * HD * sizeof(bf16_t), cudaMemcpyHostToDevice);
    cudaMemcpy(d_v, h_v, total_heads * HD * SK * sizeof(bf16_t), cudaMemcpyHostToDevice);

    FmhaMultiRowParams params;
    params.q = d_q; params.k = d_k; params.v = d_v; params.o = d_o; params.lse = d_lse;
    params.s_k = SK; params.T = T; params.scale = SCALE; params.head_dim = HD;
    params.q_head_stride = T * HD; params.q_batch_stride = n_h * T * HD;
    params.k_head_stride = SK * HD; params.k_batch_stride = n_h * SK * HD;
    params.v_head_stride = HD * SK; params.v_batch_stride = n_h * HD * SK;
    params.o_head_stride = T * HD; params.o_batch_stride = n_h * T * HD;
    params.lse_head_stride = T; params.lse_batch_stride = n_h * T;

    int smem = compute_smem();
    if (smem > 48 * 1024)
        cudaFuncSetAttribute(fmha_6warp_multirow_kernel<HD>, cudaFuncAttributeMaxDynamicSharedMemorySize, smem);

    dim3 grid(1, n_h, batch);
    fmha_6warp_multirow_kernel<HD><<<grid, 192, smem>>>(params);

    cudaError_t err = cudaDeviceSynchronize();
    if (err != cudaSuccess) {
        printf("  CUDA ERROR: %s\n", cudaGetErrorString(err));
        cudaFree(d_q); cudaFree(d_k); cudaFree(d_v); cudaFree(d_o); cudaFree(d_lse);
        free(h_q); free(h_k); free(h_v); free(h_o); free(h_lse);
        return 0;
    }

    cudaMemcpy(h_o, d_o, total_heads * T * HD * sizeof(bf16_t), cudaMemcpyDeviceToHost);
    cudaMemcpy(h_lse, d_lse, total_heads * T * sizeof(float), cudaMemcpyDeviceToHost);

    int failed = 0; float min_cos = 1.0f;
    for (int b = 0; b < batch; b++) {
        for (int h = 0; h < n_h; h++) {
            int idx = b * n_h + h;
            float o_ref[MAX_T * 512]; float lse_ref[MAX_T];
            reference_attention_multirow(
                h_q + idx*T*HD, h_k + idx*SK*HD, h_v + idx*HD*SK,
                o_ref, lse_ref, HD, T, SK, SCALE);
            for (int t = 0; t < T; t++) {
                float cs=0,na=0,nb=0;
                for (int d=0;d<HD;d++) {
                    float a=bf16_to_f32_host(h_o[(idx*T+t)*HD+d]), b2=o_ref[t*HD+d];
                    if(fabsf(b2)>1e-4f){cs+=a*b2;na+=a*a;nb+=b2*b2;}
                }
                cs /= (sqrtf(na)*sqrtf(nb)+1e-10f);
                if(cs<min_cos) min_cos=cs;
                if(cs<0.999f) { printf("  FAIL b=%d h=%d t=%d cos=%.6f\n",b,h,t,cs); failed++; }
                // Check LSE
                float lse_err = fabsf(h_lse[idx*T+t] - lse_ref[t]);
                if(lse_err > 0.01f) { printf("  FAIL LSE b=%d h=%d t=%d kernel=%.6f ref=%.6f err=%.6f\n",b,h,t,h_lse[idx*T+t],lse_ref[t],lse_err); failed++; }
            }
        }
    }
    printf("  min_cos=%.8f %s\n", min_cos, failed==0?"PASSED":"FAILED");

    cudaFree(d_q); cudaFree(d_k); cudaFree(d_v); cudaFree(d_o); cudaFree(d_lse);
    free(h_q); free(h_k); free(h_v); free(h_o); free(h_lse);
    return failed == 0;
}

static int test_multitile_merge(int T) {
    printf("\n=== MULTI-TILE MERGE T=%d, s_k=256, HD=%d ===\n", T, HD);
    constexpr int SK_TOTAL = 256;  // 2 KV tiles
    constexpr int N_TILES = SK_TOTAL / SK;  // 2
    const float SCALE = 1.0f / sqrtf((float)HD);

    bf16_t* h_q = (bf16_t*)malloc(T * HD * sizeof(bf16_t));
    bf16_t* h_k = (bf16_t*)malloc(SK_TOTAL * HD * sizeof(bf16_t));
    bf16_t* h_v = (bf16_t*)malloc(HD * SK_TOTAL * sizeof(bf16_t));

    srand(42 + T + 2000);
    for (int i = 0; i < T * HD; i++) h_q[i] = f32_to_bf16_host((float)(rand()%100)/100.0f - 0.5f);
    for (int i = 0; i < SK_TOTAL * HD; i++) h_k[i] = f32_to_bf16_host((float)(rand()%100)/100.0f - 0.5f);
    for (int i = 0; i < HD * SK_TOTAL; i++) h_v[i] = f32_to_bf16_host((float)(rand()%100)/100.0f - 0.5f);

    bf16_t *d_q, *d_k, *d_v, *d_o; float *d_lse;
    cudaMalloc(&d_q, T * HD * sizeof(bf16_t));
    cudaMalloc(&d_k, SK * HD * sizeof(bf16_t));  // single tile
    cudaMalloc(&d_v, HD * SK * sizeof(bf16_t));   // single tile
    cudaMalloc(&d_o, T * HD * sizeof(bf16_t));
    cudaMalloc(&d_lse, T * sizeof(float));
    cudaMemcpy(d_q, h_q, T * HD * sizeof(bf16_t), cudaMemcpyHostToDevice);

    int smem = compute_smem();
    if (smem > 48 * 1024)
        cudaFuncSetAttribute(fmha_6warp_multirow_kernel<HD>, cudaFuncAttributeMaxDynamicSharedMemorySize, smem);

    float* lse_per_tile = (float*)malloc(N_TILES * T * sizeof(float));
    float* o_per_tile = (float*)malloc(N_TILES * T * HD * sizeof(float));

    // We need separate V buffer per tile since V is (HD, SK_TOTAL) and
    // the tile columns are not contiguous in the original array
    bf16_t* h_v_tile = (bf16_t*)malloc(HD * SK * sizeof(bf16_t));

    for (int tile = 0; tile < N_TILES; tile++) {
        // K for this tile: K is (SK_TOTAL, HD), rows are contiguous
        cudaMemcpy(d_k, h_k + tile * SK * HD, SK * HD * sizeof(bf16_t), cudaMemcpyHostToDevice);

        // V for this tile: V is (HD, SK_TOTAL), tile columns are NOT contiguous
        // Copy V[d, tile*SK..(tile+1)*SK-1] into h_v_tile[d, 0..SK-1]
        for (int d = 0; d < HD; d++)
            memcpy(h_v_tile + d * SK, h_v + d * SK_TOTAL + tile * SK, SK * sizeof(bf16_t));
        cudaMemcpy(d_v, h_v_tile, HD * SK * sizeof(bf16_t), cudaMemcpyHostToDevice);

        FmhaMultiRowParams params;
        params.q = d_q; params.k = d_k; params.v = d_v; params.o = d_o; params.lse = d_lse;
        params.s_k = SK; params.T = T; params.scale = SCALE; params.head_dim = HD;
        params.q_head_stride = T * HD; params.q_batch_stride = T * HD;
        params.k_head_stride = SK * HD; params.k_batch_stride = SK * HD;
        params.v_head_stride = HD * SK; params.v_batch_stride = HD * SK;
        params.o_head_stride = T * HD; params.o_batch_stride = T * HD;
        params.lse_head_stride = T; params.lse_batch_stride = T;

        dim3 grid(1, 1, 1);
        fmha_6warp_multirow_kernel<HD><<<grid, 192, smem>>>(params);
        cudaError_t err = cudaDeviceSynchronize();
        if (err != cudaSuccess) {
            printf("  CUDA ERROR tile %d: %s\n", tile, cudaGetErrorString(err));
            cudaFree(d_q); cudaFree(d_k); cudaFree(d_v); cudaFree(d_o); cudaFree(d_lse);
            free(h_q); free(h_k); free(h_v);
            free(lse_per_tile); free(o_per_tile);
            return 0;
        }

        bf16_t* h_o_tile = (bf16_t*)malloc(T * HD * sizeof(bf16_t));
        cudaMemcpy(h_o_tile, d_o, T * HD * sizeof(bf16_t), cudaMemcpyDeviceToHost);
        cudaMemcpy(lse_per_tile + tile * T, d_lse, T * sizeof(float), cudaMemcpyDeviceToHost);

        for (int i = 0; i < T * HD; i++)
            o_per_tile[tile * T * HD + i] = bf16_to_f32_host(h_o_tile[i]);
        free(h_o_tile);
    }

    // Python KV merge with normalized O + LSE:
    // O = Σ exp(lse_i - L) * O_i_norm / Σ exp(lse_i - L)
    // where L = max(lse_i) for numerical stability
    float* h_o_merged = (float*)calloc(T * HD, sizeof(float));
    for (int t = 0; t < T; t++) {
        float lse_max = -INFINITY;
        for (int tile = 0; tile < N_TILES; tile++)
            lse_max = fmaxf(lse_max, lse_per_tile[tile * T + t]);
        float sum_w = 0.0f;
        for (int tile = 0; tile < N_TILES; tile++)
            sum_w += expf(lse_per_tile[tile * T + t] - lse_max);
        for (int d = 0; d < HD; d++) {
            float ov = 0.0f;
            for (int tile = 0; tile < N_TILES; tile++)
                ov += expf(lse_per_tile[tile * T + t] - lse_max) * o_per_tile[tile * T * HD + t * HD + d];
            h_o_merged[t * HD + d] = ov / sum_w;
        }
    }

    // Compare with full reference
    float o_ref[MAX_T * 512];
    reference_attention_multirow(h_q, h_k, h_v, o_ref, nullptr, HD, T, SK_TOTAL, SCALE);

    int failed = 0; float min_cos = 1.0f;
    for (int t = 0; t < T; t++) {
        float cs=0,na=0,nb=0;
        for (int d=0;d<HD;d++) {
            float a=h_o_merged[t*HD+d], b2=o_ref[t*HD+d];
            if(fabsf(b2)>1e-4f){cs+=a*b2;na+=a*a;nb+=b2*b2;}
        }
        cs /= (sqrtf(na)*sqrtf(nb)+1e-10f);
        if(cs<min_cos) min_cos=cs;
        if(cs<0.999f) { printf("  FAIL merge t=%d cos=%.6f\n",t,cs); failed++; }
    }
    printf("  min_cos=%.8f %s\n", min_cos, failed==0?"PASSED":"FAILED");

    cudaFree(d_q); cudaFree(d_k); cudaFree(d_v); cudaFree(d_o); cudaFree(d_lse);
    free(h_q); free(h_k); free(h_v); free(h_o_merged); free(h_v_tile);
    free(lse_per_tile); free(o_per_tile);
    return failed == 0;
}

int main() {
    printf("Multi-row FMHA test (HD=%d)\n", HD);

    int ok = 1;

    // 1. Single KV tile, normalized output
    printf("\n--- Single KV tile tests ---\n");
    ok &= test_single(1);
    ok &= test_single(2);
    ok &= test_single(4);
    ok &= test_single(8);
    ok &= test_single(16);
    ok &= test_single(32);
    ok &= test_single(64);
    ok &= test_single(128);

    // 2. Multi-tile KV merge (s_k=256, 2 segments)
    printf("\n--- Multi-tile KV merge tests ---\n");
    ok &= test_multitile_merge(1);
    ok &= test_multitile_merge(4);
    ok &= test_multitile_merge(16);
    ok &= test_multitile_merge(32);
    ok &= test_multitile_merge(64);
    ok &= test_multitile_merge(128);

    // 3. Multi-head and batched
    printf("\n--- Multi-head and batched tests ---\n");
    ok &= test_single(4, 4, 1);   // 4 heads, T=4
    ok &= test_single(16, 4, 1);  // 4 heads, T=16
    ok &= test_single(64, 4, 1);  // 4 heads, T=64
    ok &= test_single(1, 2, 2);   // 2 heads, 2 batch, T=1
    ok &= test_single(16, 2, 2);  // 2 heads, 2 batch, T=16

    printf("\n%s\n", ok ? "ALL PASSED" : "SOME FAILED");
    return ok ? 0 : 1;
}
