# ===============================================
# RX 480 / GPU Prismatic Infinite Ceiling Finder
# ===============================================
import pyopencl as cl
import numpy as np
import time
import math

# ---------------------------
# Auto-detect GPU
# ---------------------------
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. 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.")

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)

# ---------------------------
# Kernel: Fractional Base(∞) recursion
# ---------------------------
kernel_code = """
__kernel void recurse_prismatic_inf(
    __global double *data,
    const int depth_max,
    const double phi)
{
    int gid = get_global_id(0);
    double x = data[gid];

    for(int d=0; d<depth_max; d++){
        double factor = pow(phi, d/16.0);  // fractional exponent for prismatic braid
        x = sqrt(x * factor + 0.5) * 1.0001;
    }

    data[gid] = x;
}
"""
program = cl.Program(ctx, kernel_code).build()
kernel = cl.Kernel(program, "recurse_prismatic_inf")  # reuse kernel

# ---------------------------
# Benchmark / Ceiling Finder
# ---------------------------
N = 2**20  # fixed thread count (~1M threads)
phi = 1.6180339887
depth_start = 7
depth_end = 50  # go deep for prismatic saturation

# Initialize analog slots (continuous Base(∞) superposition)
data = np.random.rand(N).astype(np.float64)
buf = cl.Buffer(ctx, cl.mem_flags.READ_WRITE | cl.mem_flags.COPY_HOST_PTR, hostbuf=data)

for depth in range(depth_start, depth_end + 1):
    kernel.set_arg(0, buf)
    kernel.set_arg(1, np.int32(depth))
    kernel.set_arg(2, np.float64(phi))

    # Warmup
    evt = cl.enqueue_nd_range_kernel(queue, kernel, (N,), None)
    evt.wait()

    # Timed run
    t0 = time.time()
    for _ in range(3):
        evt = cl.enqueue_nd_range_kernel(queue, kernel, (N,), None)
    evt.wait()
    dt = max((time.time() - t0) / 3.0, 1e-9)  # safe division

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

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