"""LLMHosts Core GPU detection wrapper."""

from __future__ import annotations

import json
import logging
from typing import Any

logger = logging.getLogger(__name__)

LLMHOSTS_GPU_AVAILABLE: bool = False
_detect_gpus_native = None

try:
    from _llmhosts import gpu as _llmhosts_gpu_mod

    _detect_gpus_native = _llmhosts_gpu_mod.detect_gpus
    LLMHOSTS_GPU_AVAILABLE = True
    logger.debug("LLMHosts Core GPU loaded (_llmhosts.gpu %s)", _llmhosts_gpu_mod.LLMHOSTS_GPU_VERSION)
except ImportError:
    # Fallback: try standalone module (development mode with individual maturin develop)
    try:
        import _llmhosts_gpu

        _detect_gpus_native = _llmhosts_gpu.detect_gpus
        LLMHOSTS_GPU_AVAILABLE = True
        logger.debug("LLMHosts Core GPU loaded (standalone _llmhosts_gpu %s)", _llmhosts_gpu.LLMHOSTS_GPU_VERSION)
    except ImportError:
        logger.debug("LLMHosts Core GPU not available")


def detect_gpus() -> dict[str, Any]:
    if _detect_gpus_native is None:
        return {"gpus": [], "total_vram_mb": 0, "total_free_vram_mb": 0, "recommended_strategy": "CpuOnly"}
    try:
        result: dict[str, Any] = json.loads(_detect_gpus_native())
        return result
    except Exception as exc:
        logger.warning("GPU detection failed: %s", exc)
        return {"gpus": [], "total_vram_mb": 0, "total_free_vram_mb": 0, "recommended_strategy": "CpuOnly"}
