"""
TTS (文字转语音) 抽象基类 + 工厂
"""

import logging
from abc import ABC, abstractmethod
from dataclasses import dataclass
from typing import AsyncIterator, Dict, Type

logger = logging.getLogger(__name__)


@dataclass
class TTSResult:
    """TTS 合成结果"""
    audio_data: bytes
    """音频数据"""

    format: str = "mp3"
    """音频格式"""


class BaseTTS(ABC):
    """TTS 引擎抽象基类"""

    @abstractmethod
    async def initialize(self) -> None:
        """初始化引擎"""
        ...

    @abstractmethod
    async def synthesize(self, text: str) -> TTSResult:
        """
        合成语音

        Args:
            text: 待合成文本

        Returns:
            合成结果
        """
        ...

    async def synthesize_stream(self, text: str) -> AsyncIterator[bytes]:
        """
        流式合成语音

        Args:
            text: 待合成文本

        Yields:
            音频数据块 (mp3)
        """
        result = await self.synthesize(text)
        yield result.audio_data

    async def shutdown(self) -> None:
        """释放资源"""
        pass


class TTSFactory:
    """TTS 引擎工厂"""

    _registry: Dict[str, Type[BaseTTS]] = {}

    @classmethod
    def register(cls, name: str, tts_class: Type[BaseTTS]) -> None:
        """注册 TTS 引擎"""
        cls._registry[name] = tts_class
        logger.debug(f"Registered TTS engine: {name}")

    @classmethod
    def create(cls, engine_type: str, **config) -> BaseTTS:
        """
        创建 TTS 引擎实例

        Args:
            engine_type: 引擎类型名称
            **config: 引擎配置参数

        Returns:
            TTS 引擎实例
        """
        if engine_type not in cls._registry:
            available = list(cls._registry.keys())
            raise ValueError(f"Unknown TTS engine: {engine_type}, available: {available}")

        return cls._registry[engine_type](**config)

    @classmethod
    def available(cls) -> list:
        """获取可用的 TTS 引擎列表"""
        return list(cls._registry.keys())
