"""CUDA hardware detection."""

from __future__ import annotations

import os
import subprocess
import sys


def check_cuda_available() -> tuple[bool, str]:
    """Check if CUDA is available after installation."""
    try:
        probe = (
            "import torch; "
            "ok = torch.cuda.is_available(); "
            "name = torch.cuda.get_device_name(0) if ok else ''; "
            "print('1:' + name if ok else '0')"
        )
        env = os.environ.copy()
        env["TORCH_DEVICE_BACKEND_AUTOLOAD"] = "0"
        result = subprocess.run(
            [sys.executable, "-c", probe],
            capture_output=True,
            text=True,
            timeout=20,
            env=env,
        )
        if result.returncode != 0:
            reason = (result.stderr or result.stdout or "CUDA probe failed").strip()
            return False, f"❌ Error: {reason.splitlines()[-1] if reason else 'CUDA probe failed'}"

        output = (result.stdout or "").strip()
        if output.startswith("1:"):
            device_name = output[2:] or "CUDA device"
            return True, f"✅ CUDA ready: {device_name}"
        return False, "❌ CUDA not detected (check NVIDIA drivers)"
    except subprocess.TimeoutExpired:
        return False, "❌ Error: CUDA probe timeout"
    except Exception as e:
        return False, f"❌ Error: {e}"
