"""Kokoro TTS via ONNX runtime."""

import asyncio
import sys

from kokoro_onnx import Kokoro

from ..audio import wav_duration, write_wav
from ..settings import settings
from .base import TTSEngine, TTSResult


class KokoroEngine(TTSEngine):
    """Kokoro ONNX TTS — fast local inference (~4x realtime on CPU)."""

    name = "kokoro"
    default_voice = "af_heart"

    def __init__(self, model: Kokoro) -> None:
        self._model = model

    async def synthesize(self, text: str, voice: str | None = None) -> TTSResult:
        voice = voice or self.default_voice

        # kokoro.create() is CPU-bound, run in executor
        loop = asyncio.get_running_loop()
        samples, sample_rate = await loop.run_in_executor(
            None, self._model.create, text, voice, 1.0
        )

        path = write_wav(samples, sample_rate, prefix="kokoro-")

        return TTSResult(
            audio_path=path,
            sample_rate=sample_rate,
            duration_seconds=wav_duration(path),
            engine=self.name,
            voice=voice,
        )

    async def list_voices(self) -> list[str]:
        try:
            voices = self._model.get_voices()
            blacklist = settings.blacklisted_voices
            return sorted(v for v in voices if v.lower() not in blacklist)
        except Exception as e:
            print(f"Kokoro voice listing failed: {e}", file=sys.stderr)
            return []

    async def check_health(self) -> dict:
        try:
            voices = self._model.get_voices()
            return {
                "status": "healthy",
                "engine": self.name,
                "voice_count": len(voices),
            }
        except Exception as e:
            return {"status": "unhealthy", "engine": self.name, "error": str(e)}
