"""
Edge TTS 引擎

使用 Microsoft Edge TTS 服务，免费、中文质量好。
"""

import asyncio
import logging
from typing import AsyncIterator

from .base_tts import BaseTTS, TTSFactory, TTSResult

logger = logging.getLogger(__name__)


class EdgeTTSEngine(BaseTTS):
    """
    Edge TTS 语音合成引擎

    基于 edge-tts 库，使用微软 Edge 的在线 TTS 服务。
    """

    def __init__(
        self,
        voice: str = "zh-CN-XiaoxiaoNeural",
        rate: str = "+0%",
        volume: str = "+0%",
        pitch: str = "+0Hz",
    ):
        """
        Args:
            voice: 语音角色
            rate: 语速 (如 "+20%", "-10%")
            volume: 音量
            pitch: 音调
        """
        self._voice = voice
        self._rate = rate
        self._volume = volume
        self._pitch = pitch

    async def initialize(self) -> None:
        """初始化（edge-tts 不需要预加载）"""
        logger.info(f"Edge TTS initialized: voice={self._voice}, rate={self._rate}")

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

        communicate = edge_tts.Communicate(
            text,
            voice=self._voice,
            rate=self._rate,
            volume=self._volume,
            pitch=self._pitch,
        )

        # 收集所有音频数据
        audio_data = bytearray()
        async for chunk in communicate.stream():
            if chunk["type"] == "audio":
                audio_data.extend(chunk["data"])

        return TTSResult(
            audio_data=bytes(audio_data),
            format="mp3",
        )

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

        communicate = edge_tts.Communicate(
            text,
            voice=self._voice,
            rate=self._rate,
            volume=self._volume,
            pitch=self._pitch,
        )

        async for chunk in communicate.stream():
            if chunk["type"] == "audio":
                yield chunk["data"]

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


# 自动注册到工厂
TTSFactory.register("edge_tts", EdgeTTSEngine)
