import pytest

from app.config import Settings
from app.errors import UnknownComponentError
from app.store import SessionOwnershipError
from app.dependencies import (
    resolve_route,
    get_llm_provider,
    get_tts_provider,
    get_store,
)


def test_default_route_from_settings():
    cfg = Settings()
    route = resolve_route(cfg=cfg)
    assert route.stt_provider == cfg.default_stt_provider
    assert route.llm_provider == cfg.default_llm_provider
    assert route.input_endpoint == cfg.default_input_endpoint
    assert route.language == cfg.default_language


def test_request_overrides_win():
    route = resolve_route(overrides={"llm_provider": "openrouter", "output_endpoint": "loopback"})
    assert route.llm_provider == "openrouter"
    assert route.output_endpoint == "loopback"


def test_user_prefs_session_request_precedence():
    store = get_store()
    user, _ = store.create_user("Tester")
    store.set_user_prefs(user.id, {"tts_provider": "chatterbox", "language": "en"})
    user = store.get_user(user.id)

    # Nutzer-Prefs gelten.
    route = resolve_route(user)
    assert route.tts_provider == "chatterbox"
    assert route.language == "en"

    # Session schlägt Nutzer-Prefs.
    store.update_session("s1", user.id, {"tts_provider": "piper"})
    route2 = resolve_route(user, "s1")
    assert route2.tts_provider == "piper"
    assert route2.language == "en"  # weiterhin aus den Nutzer-Prefs

    # Request schlägt Session.
    route3 = resolve_route(user, "s1", {"tts_provider": "openrouter"})
    assert route3.tts_provider == "openrouter"


def test_session_ownership_enforced_in_route():
    store = get_store()
    owner, _ = store.create_user("A")
    other, _ = store.create_user("B")
    store.update_session("shared", owner.id, {"tts_provider": "piper"})
    with pytest.raises(SessionOwnershipError):
        resolve_route(other, "shared")


def test_registry_unknown_provider_raises():
    with pytest.raises(UnknownComponentError):
        get_llm_provider("does-not-exist")


def test_registry_known_provider():
    assert type(get_tts_provider("piper")).__name__ == "PiperTTSProvider"
