from __future__ import annotations

import time
from dataclasses import dataclass


@dataclass
class MLXAudioHealth:
    available: bool
    warmed: bool
    backend: str
    detail: str
    checked_at: float


class MLXAudioService:
    """Best-effort wrapper for optional mlx-audio runtime.

    This intentionally degrades safely when mlx-audio is absent so the app can
    keep using existing chat + PTT behavior.
    """

    def __init__(self) -> None:
        self._warmed = False
        self._last_detail = "not checked"
        self._last_backend = "unavailable"
        self._last_checked = 0.0

    def _detect_backend(self) -> tuple[bool, str, str]:
        try:
            import mlx_audio  # type: ignore

            ver = getattr(mlx_audio, "__version__", "unknown")
            return True, "mlx_audio", f"mlx-audio available ({ver})"
        except Exception as exc:
            return False, "fallback", f"mlx-audio unavailable: {exc}"

    def preload(self) -> MLXAudioHealth:
        available, backend, detail = self._detect_backend()
        self._warmed = available
        self._last_backend = backend
        self._last_detail = detail
        self._last_checked = time.time()
        return MLXAudioHealth(
            available=available,
            warmed=self._warmed,
            backend=backend,
            detail=detail,
            checked_at=self._last_checked,
        )

    def health(self) -> MLXAudioHealth:
        if self._last_checked <= 0:
            return self.preload()
        available, backend, detail = self._detect_backend()
        if available:
            self._warmed = self._warmed or available
        self._last_backend = backend
        self._last_detail = detail
        self._last_checked = time.time()
        return MLXAudioHealth(
            available=available,
            warmed=self._warmed and available,
            backend=backend,
            detail=detail,
            checked_at=self._last_checked,
        )
