# Source code for tabletree.src.lib.i18n

    import json
    import os
    import traceback
    from typing import Any, Literal, Self, TypedDict

    class UidRef(TypedDict):
        uid_ref: str
        uid_type: Literal["i18n"]

    class I18nWord(TypedDict):
        """A word."""

        key: str
        """The key for the vocabulary."""
        ja: str | int | None
        """The Japanese for the vocabulary."""
        en: str | int | None
        """The English for the vocabulary."""
        zh_cn: str | int | None
        """The Chinese for the vocabulary."""

    def is_i18n_word(value: Any) -> bool:
        """Determines if the value is 'I18nWord' or not.

        Returns:
            Whether the input is 'I18nWord' or not.
        """
        return isinstance(value, dict) and (
            "ja" in value or "en" in value or "zh_cn" in value
        )

    class I18nResourcesWriter:
        __self: Self | None = None

        def __init__(self):
            """Create a writer for an i18n resource."""
            I18nResourcesWriter.__self = self
            self.res = dict[str, None | dict[str, str | int | None]]()
            for lang in ["ja", "en", "zh_cn"]:
                self.res[lang] = None

        @staticmethod
        def get_instance():
            """Obtain the instance of I18nResourcesWriter."""
            if I18nResourcesWriter.__self is None:
                I18nResourcesWriter.__self = I18nResourcesWriter()
            return I18nResourcesWriter.__self

        def add_word(self, word: I18nWord) -> Self:
            """Add a word to the resources."""
            langs: list[Literal["ja", "en", "zh_cn"]] = ["ja", "en", "zh_cn"]
            for lang in langs:
                if word[lang] is None:
                    continue
                if self.res[lang] is None:
                    self.res[lang] = {}
                self.res[lang][word["key"]] = word[lang]
            return self

        def write(self, outdir: str) -> bool:
            """Write i18n resources.

            Args:
                outdir:
                    Output directory path.

            Returns:
                Is writing success or fail.
            """
            res = dict[str, dict[str, str | int]]()
            for lang in ["ja", "en", "zh_cn"]:
                res_lang = "zh-CN" if lang == "zh_cn" else lang
                if self.res[lang] is not None:
                    res[res_lang] = {}
                    for key, val in self.res[lang].items():
                        if val is not None:
                            res[res_lang][key] = val
            try:
                os.makedirs(outdir, exist_ok=True)
                with open(os.path.join(outdir, "i18n.json"), "w") as f:
                    json.dump(res, f, allow_nan=False)
                return True
            except Exception:
                traceback.print_exc()
                return False