"""Blender Python script: GPU compute device probe.

Run via:
  blender --background --python gpu_probe.py

Exit codes:
  0 — GPU found, prints GPU_PROBE_OK line
  1 — No GPU found or error, prints GPU_PROBE_FAIL line
"""
import sys


def main():
    try:
        import bpy

        cprefs = bpy.context.preferences.addons['cycles'].preferences
        for device_type in ('OPTIX', 'CUDA', 'HIP', 'ONEAPI'):
            try:
                cprefs.compute_device_type = device_type
                cprefs.get_devices()
                gpu_devices = [d for d in cprefs.devices if d.type != 'CPU']
                if gpu_devices:
                    device_names = [(d.name, d.type) for d in gpu_devices]
                    print(
                        f"GPU_PROBE_OK: device_type={device_type} devices={device_names}",
                        flush=True,
                    )
                    sys.exit(0)
            except Exception as e:
                print(f"GPU_PROBE: {device_type} not available: {e}", flush=True)

        print("GPU_PROBE_FAIL: no GPU compute device found", flush=True)
        sys.exit(1)

    except SystemExit:
        raise
    except Exception as e:
        print(f"GPU_PROBE_FAIL: exception during probe: {e}", flush=True)
        sys.exit(1)


main()
