"""
automl_lib.hardware
~~~~~~~~~~~~~~~~~~~
Auto-detect the best available compute device.
"""

from __future__ import annotations

import torch

from .utils import get_logger

logger = get_logger(__name__)


def detect_device(preferred: str | None = None) -> torch.device:
    """Return the fastest available ``torch.device``.

    Priority: user preference → CUDA → MPS → CPU.

    Parameters
    ----------
    preferred : str, optional
        Force a specific device string (e.g. ``"cuda:0"``, ``"cpu"``).
    """
    if preferred:
        dev = torch.device(preferred)
        logger.info(f"Using user-specified device: {dev}")
        return dev

    if torch.cuda.is_available():
        dev = torch.device("cuda")
        gpu_name = torch.cuda.get_device_name(0)
        logger.info(f"CUDA GPU detected: {gpu_name}")
        return dev

    if hasattr(torch.backends, "mps") and torch.backends.mps.is_available():
        dev = torch.device("mps")
        logger.info("Apple MPS backend detected")
        return dev

    logger.info("No GPU found - using CPU")
    return torch.device("cpu")


def device_summary() -> dict:
    """Return a dict summarizing available hardware."""
    info: dict = {"cpu_count": torch.get_num_threads()}
    if torch.cuda.is_available():
        info["cuda"] = {
            "device_count": torch.cuda.device_count(),
            "devices": [
                torch.cuda.get_device_name(i)
                for i in range(torch.cuda.device_count())
            ],
        }
    if hasattr(torch.backends, "mps"):
        info["mps_available"] = torch.backends.mps.is_available()
    return info
