/**
 * @file test_p2p_cross_vendor.c
 * @brief Cross-Vendor P2P DMA Tests
 */

#include "mvgal/mvgal.h"
#include "mvgal/mvgal_p2p_dma.h"
#include "mvgal/mvgal_log.h"
#include "mvgal/mvgal_gpu.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

static int test_passed = 0;
static int test_failed = 0;

#define TEST_ASSERT(condition, message) \
    do { if (condition) { test_passed++; MVGAL_LOG_INFO("  ✓ %s", message); } \
         else { test_failed++; MVGAL_LOG_ERROR("  ✗ %s", message); } \
    } while (0)

static void test_p2p_basic(void)
{
    MVGAL_LOG_INFO("--- P2P basic initialization ---");
    
    mvgal_p2p_context_t ctx = NULL;
    mvgal_error_t err = mvgal_p2p_init(&ctx);
    TEST_ASSERT(err == MVGAL_SUCCESS, "P2P context initialization");
    TEST_ASSERT(ctx != NULL, "Context is non-NULL");
    
    mvgal_p2p_fini(ctx);
    MVGAL_LOG_INFO("--- P2P basic initialization passed ---");
}

static void test_p2p_matrix_build(void)
{
    MVGAL_LOG_INFO("--- P2P matrix build ---");
    
    uint8_t matrix[256];
    uint32_t gpu_count = 0;
    
    mvgal_error_t err = mvgal_p2p_build_matrix(matrix, sizeof(matrix), &gpu_count);
    TEST_ASSERT(err == MVGAL_SUCCESS, "P2P matrix build");
    TEST_ASSERT(gpu_count > 0, "GPU count detected");
    
    MVGAL_LOG_INFO("  Detected %u GPU(s)", gpu_count);
    
    /* Diagonal should always be 1 (self-access) */
    for (uint32_t i = 0; i < gpu_count && i < 16; i++) {
        TEST_ASSERT(matrix[i * gpu_count + i] == 1, "Self-access enabled");
    }
}

static void test_bandwidth_estimation(void)
{
    MVGAL_LOG_INFO("--- Bandwidth estimation ---");
    
    int32_t gpu_count = mvgal_gpu_get_count();
    if (gpu_count < 2) {
        MVGAL_LOG_INFO("  Skipping: requires 2+ GPUs");
        return;
    }
    
    uint32_t bw = mvgal_p2p_get_bandwidth(0, 1);
    MVGAL_LOG_INFO("  Estimated bandwidth between GPU 0 and 1: %u MB/s", bw);
    TEST_ASSERT(bw > 0, "Bandwidth is positive");
}

int main(void)
{
    printf("\n============================================================\n");
    printf("  MVGAL Cross-Vendor P2P DMA Tests\n");
    printf("============================================================\n\n");
    
    mvgal_init(0);
    
    test_p2p_basic();
    test_p2p_matrix_build();
    test_bandwidth_estimation();
    
    mvgal_shutdown();
    
    printf("\n============================================================\n");
    printf("  Test Summary\n");
    printf("============================================================\n");
    printf("  Passed: %d\n", test_passed);
    printf("  Failed: %d\n", test_failed);
    printf("  Total:  %d\n", test_passed + test_failed);
    printf("============================================================\n\n");
    
    return (test_failed > 0) ? EXIT_FAILURE : EXIT_SUCCESS;
}