import shutil
import subprocess
from . import ui

def detect_gpu():
    """
    Detect available GPU and return hashcat flags.

    Returns a list like ["-O", "-D", "1,2", "-w", "3"] for GPU,
    or ["-O", "--force"] for CPU-only fallback.

    These flags are the SINGLE SOURCE OF TRUTH for how hashcat is invoked.
    Every hashcat call must use these — never hardcode --force or -O elsewhere.
    """
    ui.section("GPU Detection")
    flags = ["-O"]  # optimized kernels — always beneficial

    # Try nvidia-smi first (most reliable for NVIDIA)
    nvidia_smi = shutil.which("nvidia-smi")
    if nvidia_smi:
        try:
            result = subprocess.run(
                [nvidia_smi, "--query-gpu=name", "--format=csv,noheader"],
                capture_output=True, text=True, timeout=10
            )
            if result.returncode == 0 and result.stdout.strip():
                gpu_info = result.stdout.strip().split('\n')[0]
                ui.ok(f"NVIDIA GPU detected: {gpu_info}")
                flags.extend(["-D", "1,2", "-w", "3"])
                return flags
        except Exception:
            pass

    # Fallback: ask hashcat what devices it sees
    try:
        result = subprocess.run(["hashcat", "-I"], capture_output=True, text=True, timeout=15)
        if any(kw in result.stdout for kw in ("CUDA", "OpenCL", "HIP")):
            ui.ok("GPU compute platform detected via hashcat -I")
            flags.extend(["-D", "1,2", "-w", "3"])
            return flags
    except Exception:
        pass

    ui.warn("No GPU detected — falling back to CPU mode (will be slow)")
    flags.append("--force")
    return flags

