/**
 * Minimal HIP diagnostic — step-by-step GPU compute validation
 * Tests each operation individually with timeout awareness
 *
 * Compile: hipcc --offload-arch=gfx1010 -o hip_minimal_test hip_minimal_test.cpp
 * Run:     HSA_OVERRIDE_GFX_VERSION=10.1.0 ./hip_minimal_test
 */
#include <hip/hip_runtime.h>
#include <cstdio>
#include <cstdlib>
#include <cstring>

#define HIP_CHECK(call) do { \
    hipError_t err = call; \
    if (err != hipSuccess) { \
        fprintf(stderr, "HIP ERROR [%d]: %s at %s:%d\n", \
                (int)err, hipGetErrorString(err), __FILE__, __LINE__); \
        exit(1); \
    } \
} while(0)

__global__ void simpleKernel(int* out) {
    out[threadIdx.x] = threadIdx.x * 2;
}

int main() {
    setbuf(stdout, NULL); // Force unbuffered output
    setbuf(stderr, NULL);
    
    printf("STEP 0: HIP init\n");
    int count;
    HIP_CHECK(hipGetDeviceCount(&count));
    printf("  Devices: %d\n", count);
    
    hipDeviceProp_t p;
    HIP_CHECK(hipGetDeviceProperties(&p, 0));
    printf("  Device: %s, CU=%d, Mem=%zuMB, isIntegrated=%d\n",
           p.name, p.multiProcessorCount, p.totalGlobalMem/(1024*1024), p.integrated);

    printf("STEP 1: hipMalloc (small: 256 bytes)\n");
    int *d_buf = nullptr;
    HIP_CHECK(hipMalloc(&d_buf, 256));
    printf("  OK: d_buf=%p\n", (void*)d_buf);

    printf("STEP 2: hipMemset\n");
    HIP_CHECK(hipMemset(d_buf, 0, 256));
    printf("  OK\n");

    printf("STEP 3: hipMemcpy H2D (64 ints)\n");
    int h_buf[64];
    for (int i = 0; i < 64; i++) h_buf[i] = i + 100;
    HIP_CHECK(hipMemcpy(d_buf, h_buf, 256, hipMemcpyHostToDevice));
    printf("  OK\n");

    printf("STEP 4: Launch kernel (1 block, 32 threads)\n");
    simpleKernel<<<1, 32>>>(d_buf);
    HIP_CHECK(hipGetLastError());
    printf("  Launched\n");

    printf("STEP 5: hipDeviceSynchronize\n");
    HIP_CHECK(hipDeviceSynchronize());
    printf("  OK\n");

    printf("STEP 6: hipMemcpy D2H\n");
    int h_out[64];
    memset(h_out, 0, 256);
    HIP_CHECK(hipMemcpy(h_out, d_buf, 128, hipMemcpyDeviceToHost));
    printf("  OK\n");

    printf("STEP 7: Verify results\n");
    int pass = 1;
    for (int i = 0; i < 32; i++) {
        if (h_out[i] != i * 2) {
            printf("  FAIL: h_out[%d]=%d expected %d\n", i, h_out[i], i*2);
            pass = 0;
        }
    }
    if (pass) printf("  ALL 32 VALUES CORRECT\n");
    
    HIP_CHECK(hipFree(d_buf));
    printf("\nRESULT: %s\n", pass ? "PASS — ROCm HIP COMPUTE WORKS" : "FAIL");
    return pass ? 0 : 1;
}
