"""
Kokoro-82M TTS service configuration.

Model: Kokoro-82M (Chinese + English bilingual)
Voice: zf_xiaoxiao (Chinese female)
"""

import numpy as np


def _patch_misaki_compat():
    """Patch misaki.en compatibility: MutableToken was renamed to MToken."""
    try:
        import misaki.en as en
        if not hasattr(en, 'MutableToken') and hasattr(en, 'MToken'):
            en.MutableToken = en.MToken
    except ImportError:
        pass


class KokoroTTSService:
    """Text-to-Speech service using Kokoro-82M."""

    def __init__(self, model: str = "kokoro-82m", voice: str = "zf_xiaoxiao"):
        self.model_name = model
        self.voice = voice
        self._pipeline = None

    async def initialize(self):
        """Load the Kokoro TTS model."""
        _patch_misaki_compat()
        from kokoro import KPipeline

        self._pipeline = KPipeline(lang_code='z')  # Chinese

    async def synthesize(self, text: str) -> bytes:
        """Convert text to speech audio (24kHz float32 → 16-bit PCM)."""
        samples = []
        for _, _, audio in self._pipeline(text, voice=self.voice):
            if hasattr(audio, 'numpy'):
                samples.append(audio.numpy())
            else:
                samples.append(audio)

        if not samples:
            return b''

        audio_np = np.concatenate(samples)
        return (audio_np * 32768).clip(-32768, 32767).astype(np.int16).tobytes()
