"""Single source of truth for normalizing language codes to 'ru' or 'en'.

Use for: env DEFAULT_LANGUAGE, Accept-Language header, Telegram user.language_code,
and initData user object in Miniapp auth.
"""

from typing import Literal


def normalize_lang(code: str | None) -> Literal["ru", "en"]:
    """Normalize a language code to 'ru' or 'en'.

    Suitable for: env DEFAULT_LANGUAGE, Accept-Language header,
    Telegram user.language_code, and initData user in Miniapp auth.

    Args:
        code: Raw language code (e.g. 'ru', 'ru-RU', 'en', 'en-US') or None.

    Returns:
        'ru' if code starts with 'ru' (after strip/lower), else 'en'.
        Returns 'en' when code is empty or not a string.
    """
    if not code or not isinstance(code, str):
        return "en"
    code = code.strip().lower()
    return "ru" if code.startswith("ru") else "en"
