/**
 * @file test_shader_backend.c
 * @brief Shader Backend Integration Tests
 */

#include "mvgal/mvgal_types.h"
#include "mvgal/mvgal_shader_backend.h"
#include "mvgal/mvgal_log.h"

#include <stdio.h>
#include <stdlib.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)

/* Minimal valid SPIR-V module for testing */
static const uint32_t test_spirv[] = {
    0x07230203,  /* Magic number */
    0x00010000,  /* Version */
    0,           /* Schema */
    0,           /* Generated */
    0x03022000,  /* Consumer */
};

static void test_shader_backend_dispatch(void)
{
    MVGAL_LOG_INFO("--- Backend Dispatch ---");

    char *source = NULL;
    size_t size = 0;

    /* Test each vendor dispatch */
    int rc_amd = mvgal_compile_shader(MVGAL_VENDOR_AMD, test_spirv, 5, &source, &size);
    TEST_ASSERT(rc_amd == -1 || source != NULL, "AMD backend callable");

    int rc_nvidia = mvgal_compile_shader(MVGAL_VENDOR_NVIDIA, test_spirv, 5, &source, &size);
    TEST_ASSERT(rc_nvidia == -1 || source != NULL, "NVIDIA backend callable");

    int rc_intel = mvgal_compile_shader(MVGAL_VENDOR_INTEL, test_spirv, 5, &source, &size);
    TEST_ASSERT(rc_intel == -1 || source != NULL, "Intel backend callable");

    int rc_mtt = mvgal_compile_shader(MVGAL_VENDOR_MOORE_THREADS, test_spirv, 5, &source, &size);
    TEST_ASSERT(rc_mtt == -1 || source != NULL, "MTT backend callable");
}

static void test_null_safety(void)
{
    MVGAL_LOG_INFO("--- Null Safety ---");

    char *source = NULL;
    size_t size = 0;

    int rc = mvgal_compile_shader(MVGAL_VENDOR_UNKNOWN, NULL, 0, &source, &size);
    TEST_ASSERT(rc == -1, "NULL SPIR-V rejected");

    rc = mvgal_compile_shader(MVGAL_VENDOR_AMD, test_spirv, 5, &source, &size);
    /* Should either succeed or fail gracefully */
    TEST_ASSERT(rc == 0 || rc == -1, "Valid SPIR-V handled");
}

int main(void)
{
    printf("\n============================================================\n");
    printf("  MVGAL Shader Backend Unit Tests\n");
    printf("============================================================\n\n");

    test_shader_backend_dispatch();
    test_null_safety();

    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;
}