import gettext
from contextvars import ContextVar

from fastapi import Cookie, Header, Request

from gallery.util import root_path

_translation: ContextVar[gettext.GNUTranslations | gettext.NullTranslations] = ContextVar("translation")


async def set_language(
    request: Request,
    accept_language: str = Header("en"),
    language: str | None = Cookie(None),
):
    # Simplify the header (e.g., "en-US,en;q=0.9" -> "en")
    lang = language or accept_language.split(",")[0].split("-")[0]

    try:
        t = gettext.translation("messages", localedir=root_path / "locales", languages=[lang])
    except FileNotFoundError:
        t = gettext.NullTranslations()

    token = _translation.set(t)
    request.state.language = lang
    yield lang
    _translation.reset(token)


def _(message: str) -> str:
    return _translation.get().gettext(message)
