# SPDX-FileCopyrightText: (c) TagStudio Contributors
# SPDX-License-Identifier: MIT


from collections import defaultdict
from pathlib import Path
from platform import system
from typing import Any

import structlog
import ujson

from tagstudio.qt.helpers.mnemonics import remove_mnemonic_marker

logger = structlog.get_logger(__name__)

DEFAULT_TRANSLATION = "en"

LANGUAGES = [
    # "am",  # Minimal
    "ceb",
    "cs",
    # "da",  # Minimal
    "de",
    "el",
    "en",
    "es",
    "fi",
    "fil",
    "fr",
    "hu",
    # "is",  # Minimal
    "it",
    "ja",
    "nb_NO",
    "nl",
    "pl",
    "pt_BR",
    "pt",
    "qpv",
    "ro",
    "ru",
    "sv",
    "ta",
    # "th",  # Minimal
    "tok",
    "tr",
    "zh_Hans",
    "zh_Hant",
]

# A map of field class names to their respective translation keys.
FIELD_TYPE_KEYS = {
    "DatetimeField": "field_type.datetime",
    "DatetimeFieldTemplate": "field_type.datetime",
    "TextField": "field_type.text",
    "TextFieldTemplate": "field_type.text",
}


class Translator:
    _default_strings: dict[str, str]
    _strings: dict[str, str] = {}
    __lang: str = DEFAULT_TRANSLATION

    def __init__(self):
        self._default_strings = self.__get_translation_dict(DEFAULT_TRANSLATION)

    def __get_translation_dict(self, lang: str) -> dict[str, str]:
        try:
            with open(
                Path(__file__).parents[1] / "resources" / "translations" / f"{lang}.json",
                encoding="utf-8",
            ) as f:
                return ujson.loads(f.read())
        except FileNotFoundError:
            return self._default_strings

    def change_language(self, lang: str):
        self.__lang = lang
        self._strings = self.__get_translation_dict(lang)
        if system() == "Darwin":
            for k, v in self._strings.items():
                self._strings[k] = remove_mnemonic_marker(v)

    def __format(self, text: str, **kwargs: ...) -> str:
        try:
            return text.format(**kwargs)
        except KeyError, ValueError:
            logger.error(
                "[Translations] Error while formatting translation.",
                text=text,
                kwargs=kwargs,
                language=self.__lang,
            )
            params: defaultdict[str, Any] = defaultdict(lambda: "{unknown_key}")  # pyright: ignore[reportExplicitAny]
            params.update(kwargs)
            return text.format_map(params)

    def format(self, key: str, **kwargs: ...) -> str:
        return self.__format(self[key], **kwargs)

    def __getitem__(self, key: str) -> str:
        return self._strings.get(key) or self._default_strings.get(key) or f"[{key}]"

    @property
    def current_language(self) -> str:
        return self.__lang


Translations = Translator()
