import pytest
from pydantic_settings import SettingsConfigDict

from app import config as cfg

EXAMPLE_TOML = str(cfg.BASE_DIR / "config" / "voice-assistant.example.toml")


class IsolatedSettings(cfg.Settings):
    # .env ausblenden, damit nur TOML/Defaults/ENV-Monkeypatch zaehlen.
    model_config = SettingsConfigDict(env_file=None, case_sensitive=False, extra="ignore")


def _clear_provider_env(monkeypatch):
    for name in ("DEFAULT_STT_PROVIDER", "DEFAULT_LLM_PROVIDER", "DEFAULT_TTS_PROVIDER"):
        monkeypatch.delenv(name, raising=False)
    monkeypatch.setenv("VA_CONFIG_FILE", EXAMPLE_TOML)


def test_profile_local_dev(monkeypatch):
    _clear_provider_env(monkeypatch)
    monkeypatch.setenv("VA_PROFILE", "local-dev")
    s = IsolatedSettings()
    assert s.default_stt_provider == "faster-whisper"
    assert s.default_llm_provider == "local-openai-compatible"
    assert s.default_tts_provider == "piper"


def test_profile_cloud(monkeypatch):
    _clear_provider_env(monkeypatch)
    monkeypatch.setenv("VA_PROFILE", "cloud")
    s = IsolatedSettings()
    assert s.default_stt_provider == "openrouter"
    assert s.default_llm_provider == "openrouter"
    assert s.default_tts_provider == "openrouter"


def test_env_overrides_toml(monkeypatch):
    _clear_provider_env(monkeypatch)
    monkeypatch.setenv("VA_PROFILE", "local-dev")
    monkeypatch.setenv("DEFAULT_LLM_PROVIDER", "openrouter")  # ENV gewinnt ueber TOML
    s = IsolatedSettings()
    assert s.default_llm_provider == "openrouter"
    assert s.default_tts_provider == "piper"  # vom Profil, nicht ueberschrieben


def test_unknown_profile_raises(monkeypatch):
    _clear_provider_env(monkeypatch)
    monkeypatch.setenv("VA_PROFILE", "gibtsnicht")
    with pytest.raises(ValueError):
        IsolatedSettings()


def test_missing_config_file_falls_back_to_defaults(monkeypatch):
    for name in ("DEFAULT_STT_PROVIDER", "DEFAULT_LLM_PROVIDER", "DEFAULT_TTS_PROVIDER"):
        monkeypatch.delenv(name, raising=False)
    monkeypatch.setenv("VA_CONFIG_FILE", "/nonexistent/voice-assistant.toml")
    monkeypatch.delenv("VA_PROFILE", raising=False)
    s = IsolatedSettings()
    assert s.default_stt_provider == "openrouter"  # eingebauter Field-Default
