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

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

import numpy as np

logger = logging.getLogger(__name__)


@dataclass
class TranscribeResult:
    """转录结果"""
    text: str
    """识别文字"""

    language: str = ""
    """检测到的语言"""

    confidence: float = 0.0
    """置信度 (0-1)"""

    is_partial: bool = False
    """是否为中间结果"""


class BaseSTT(ABC):
    """STT 引擎抽象基类"""

    @abstractmethod
    async def initialize(self) -> None:
        """初始化引擎（加载模型等）"""
        ...

    @abstractmethod
    async def transcribe(self, audio: np.ndarray, sample_rate: int = 16000) -> TranscribeResult:
        """
        转录音频

        Args:
            audio: 音频数据 (float32, [-1, 1])
            sample_rate: 采样率

        Returns:
            转录结果
        """
        ...

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


class STTFactory:
    """STT 引擎工厂"""

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

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

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

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

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

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

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