"""Unit tests for duty_teller.i18n: get_lang, t, fallback to en."""

from unittest.mock import MagicMock, patch

import duty_teller.config as config
from duty_teller.i18n import get_lang, t


def test_get_lang_always_returns_default_language():
    """get_lang ignores user and always returns config.DEFAULT_LANGUAGE."""
    assert get_lang(None) == config.DEFAULT_LANGUAGE
    user_ru = MagicMock()
    user_ru.language_code = "ru"
    assert get_lang(user_ru) == config.DEFAULT_LANGUAGE
    user_en = MagicMock()
    user_en.language_code = "en"
    assert get_lang(user_en) == config.DEFAULT_LANGUAGE
    user_any = MagicMock(spec=[])
    assert get_lang(user_any) == config.DEFAULT_LANGUAGE


def test_get_lang_returns_ru_when_default_language_is_ru():
    """When DEFAULT_LANGUAGE is ru, get_lang returns 'ru' regardless of user."""
    with patch("duty_teller.i18n.core.config") as mock_cfg:
        mock_cfg.DEFAULT_LANGUAGE = "ru"
        from duty_teller.i18n.core import get_lang as core_get_lang

        assert core_get_lang(None) == "ru"
        user = MagicMock()
        user.language_code = "en"
        assert core_get_lang(user) == "ru"


def test_get_lang_returns_en_when_default_language_is_en():
    """When DEFAULT_LANGUAGE is en, get_lang returns 'en' regardless of user."""
    with patch("duty_teller.i18n.core.config") as mock_cfg:
        mock_cfg.DEFAULT_LANGUAGE = "en"
        from duty_teller.i18n.core import get_lang as core_get_lang

        assert core_get_lang(None) == "en"
        user = MagicMock()
        user.language_code = "ru"
        assert core_get_lang(user) == "en"


def test_t_en_start_greeting():
    result = t("en", "start.greeting")
    assert "help" in result.lower()
    assert "bot" in result.lower()


def test_t_ru_start_greeting():
    result = t("ru", "start.greeting")
    assert "Привет" in result or "бот" in result or "календар" in result


def test_t_fallback_to_en_when_key_missing_for_ru():
    """When key exists in en but not in ru, fallback to en."""
    result = t("ru", "start.greeting")
    assert len(result) > 0
    # start.greeting exists in both; use a key that might be en-only for fallback
    result_any = t("ru", "errors.generic")
    assert "error" in result_any.lower() or "ошибк" in result_any.lower()


def test_t_placeholder_substitution():
    assert t("en", "set_phone.saved", phone="+7 999") == "Phone saved: +7 999"
    assert "999" in t("ru", "set_phone.saved", phone="+7 999")


def test_t_unknown_lang_normalized_to_en():
    assert "help" in t("de", "start.greeting").lower() or "Hi" in t(
        "de", "start.greeting"
    )
