/**
 * MVGAL Integration Test: P2P Connectivity Matrix
 * 
 * Verifies that the kernel UAPI correctly exposes the P2P matrix
 * and that it matches expected topology heuristics.
 */

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <fcntl.h>
#include <unistd.h>
#include <stdint.h>
#include <sys/ioctl.h>
#include <assert.h>

#include "mvgal/mvgal_uapi.h"

int main(void) {
    int fd;
    struct mvgal_uapi_caps caps = {0};
    struct mvgal_uapi_gpu_count count = {0};

    printf("Testing MVGAL P2P Matrix UAPI...\n");

    fd = open("/dev/" MVGAL_DEVICE_NAME, O_RDONLY);
    if (fd < 0) {
        perror("Failed to open /dev/mvgal0");
        return 0; // Skip if module not loaded
    }

    if (ioctl(fd, MVGAL_IOC_GET_GPU_COUNT, &count) < 0) {
        perror("MVGAL_IOC_GET_GPU_COUNT failed");
        close(fd);
        return 1;
    }

    if (ioctl(fd, MVGAL_IOC_GET_CAPS, &caps) < 0) {
        perror("MVGAL_IOC_GET_CAPS failed");
        close(fd);
        return 1;
    }

    printf("Detected %u GPUs via UAPI\n", count.gpu_count);

    /* Basic validation of P2P matrix */
    for (uint32_t i = 0; i < count.gpu_count; i++) {
        for (uint32_t j = 0; j < count.gpu_count; j++) {
            uint32_t idx = i * MVGAL_UAPI_MAX_GPUS + j;
            uint8_t p2p = caps.p2p_matrix[idx];

            printf("  GPU %u -> GPU %u: ", i, j);
            if (p2p == MVGAL_UAPI_P2P_P2P) printf("P2P\n");
            else if (p2p == MVGAL_UAPI_P2P_DMA) printf("DMA\n");
            else printf("NONE\n");

            /* Diagonal must be P2P (self-connectivity) */
            if (i == j) {
                assert(p2p == MVGAL_UAPI_P2P_P2P);
            }
        }
    }

    printf("P2P Matrix UAPI test PASSED\n");

    close(fd);
    return 0;
}
