# ===============================================
# Robust Prismatic Recursion Benchmark (Auto GPU Detect)
# ===============================================
import pyopencl as cl
import numpy as np
import time
import math

# ---------------------------
# Auto-detect GPU device
# ---------------------------
device = None
for platform in cl.get_platforms():
    for d in platform.get_devices():
        if d.type & cl.device_type.GPU:
            device = d
            break
    if device:
        break

if device is None:
    print("[WARN] No GPU found via OpenCL. Falling back to CPU.")
    for platform in cl.get_platforms():
        for d in platform.get_devices():
            if d.type & cl.device_type.CPU:
                device = d
                break
        if device:
            break
    if device is None:
        raise RuntimeError("No OpenCL devices found on this system.")

ctx = cl.Context([device])
queue = cl.CommandQueue(ctx)

print("Using device:", device.name)
print("Global Memory (MB):", device.global_mem_size // 1024**2)
print("Compute Units:", device.max_compute_units)
print("Max Clock (MHz):", device.max_clock_frequency)

# ---------------------------
# Recursive Expansion Model
# ---------------------------
def expansion(depth):
    return 8**depth

def total_instances(depth):
    base_instances = 131072  # safe VRAM seeds
    return expansion(depth) * base_instances

# ---------------------------
# Kernel (simulate recursion FLOPs)
# ---------------------------
kernel_code = """
__kernel void recurse(
    __global float *data,
    const int expansion)
{
    int gid = get_global_id(0);
    float x = data[gid];
    for(int i=0; i<expansion; i++){
        x = sqrt(x * 1.618f + 0.5f) * 1.0001f;
    }
    data[gid] = x;
}
"""
program = cl.Program(ctx, kernel_code).build()

# ---------------------------
# Benchmark Loop
# ---------------------------
for depth in range(1, 11):
    N = min(total_instances(depth), 2**20)  # safe clamp to avoid OOM
    expansion_factor = expansion(depth)

    data = np.random.rand(N).astype(np.float32)
    buf = cl.Buffer(ctx, cl.mem_flags.READ_WRITE | cl.mem_flags.COPY_HOST_PTR, hostbuf=data)

    # Warmup
    evt = program.recurse(queue, (N,), None, buf, np.int32(expansion_factor))
    evt.wait()

    # Timed run
    t0 = time.time()
    for _ in range(5):
        evt = program.recurse(queue, (N,), None, buf, np.int32(expansion_factor))
    evt.wait()
    dt = (time.time() - t0) / 5.0

    fps = 1.0 / dt
    vram_mb = data.nbytes / 1024**2
    flops = (N * expansion_factor) / dt / 1e9

    print(f"Depth {depth:2d} | N={N:,} | VRAM={vram_mb:.1f} MB | {fps:.2f} FPS | {flops:.2f} GFLOPs")
