"""ASR 服务工厂单元测试."""

from __future__ import annotations

import os

import pytest
from services.asr_service_factory import get_asr_service, reset_asr_service_cache


@pytest.fixture(autouse=True)
def clean_env():
    """每个测试前后清理环境变量和缓存."""
    # 保存原始值
    old = os.environ.get("ASR_PROVIDER")
    reset_asr_service_cache()
    yield
    # 恢复
    if old is not None:
        os.environ["ASR_PROVIDER"] = old
    elif "ASR_PROVIDER" in os.environ:
        del os.environ["ASR_PROVIDER"]
    reset_asr_service_cache()


class TestGetAsrService:
    """ASR服务工厂测试."""

    def test_default_no_provider_returns_none(self):
        """未配置ASR_PROVIDER时返回None."""
        if "ASR_PROVIDER" in os.environ:
            del os.environ["ASR_PROVIDER"]
        reset_asr_service_cache()
        result = get_asr_service()
        assert result is None

    def test_empty_provider_returns_none(self):
        """ASR_PROVIDER为空字符串时返回None."""
        os.environ["ASR_PROVIDER"] = ""
        reset_asr_service_cache()
        result = get_asr_service()
        assert result is None

    def test_whitespace_provider_returns_none(self):
        """ASR_PROVIDER为空白字符时返回None."""
        os.environ["ASR_PROVIDER"] = "   "
        reset_asr_service_cache()
        result = get_asr_service()
        assert result is None

    def test_mock_provider_returns_mock_service(self):
        """mock provider返回MockASRService."""
        os.environ["ASR_PROVIDER"] = "mock"
        reset_asr_service_cache()
        result = get_asr_service()
        assert result is not None
        # 检查类型名称
        assert type(result).__name__ == "MockASRService"

    def test_mock_provider_case_insensitive(self):
        """provider大小写不敏感."""
        os.environ["ASR_PROVIDER"] = "MOCK"
        reset_asr_service_cache()
        result = get_asr_service()
        assert result is not None
        assert type(result).__name__ == "MockASRService"

    def test_unknown_provider_returns_none(self):
        """未知provider返回None（不阻断主流程）."""
        os.environ["ASR_PROVIDER"] = "unknown_provider_xyz"
        reset_asr_service_cache()
        result = get_asr_service()
        assert result is None

    def test_singleton_caching(self):
        """单例缓存有效，多次调用返回同一实例."""
        os.environ["ASR_PROVIDER"] = "mock"
        reset_asr_service_cache()
        s1 = get_asr_service()
        s2 = get_asr_service()
        assert s1 is s2

    def test_reset_cache_clears_singleton(self):
        """重置缓存后返回新实例."""
        os.environ["ASR_PROVIDER"] = "mock"
        reset_asr_service_cache()
        s1 = get_asr_service()
        reset_asr_service_cache()
        s2 = get_asr_service()
        assert s1 is not s2
