# SPDX-FileCopyrightText: 2016-2026 PyThaiNLP Project
# SPDX-FileType: SOURCE
# SPDX-License-Identifier: Apache-2.0
"""
Look up romanized Thai words in a predefined dictionary.

The dictionary is compiled by Wannaphong, 2022.

Wannaphong Phatthiyaphaibun. (2022).
wannaphong/thai-english-transliteration-dictionary: v1.4 (v1.4).
Zenodo. https://doi.org/10.5281/zenodo.6716672
"""

from __future__ import annotations

from typing import TYPE_CHECKING, Optional, cast

if TYPE_CHECKING:
    from collections.abc import Callable

from pythainlp.corpus.th_en_translit import (
    TRANSLITERATE_DICT,
    TRANSLITERATE_EN,
    TRANSLITERATE_FOLLOW_RTSG,
)

_TRANSLITERATE_IDX: int = 0


def follow_rtgs(text: str) -> Optional[bool]:
    """
    Check if a word follows the Royal Thai General System of Transcription.

    The system is abbreviated as RTGS.

    :param str text: word to look up; must be a self-contained word
    :return: ``True`` if ``text`` follows the RTGS definition,
        ``False`` if it does not, or ``None`` if the word is unverified
        or unknown
    :rtype: Optional[bool]
    """
    try:
        follow = TRANSLITERATE_DICT[text][TRANSLITERATE_FOLLOW_RTSG][
            _TRANSLITERATE_IDX
        ]
    except IndexError:
        return None
    else:
        return cast("bool", follow)


def _romanize(text: str, fallback_func: Callable[[str], str]) -> str:
    """Romanize one word; look up first, call `fallback_func` if not found."""
    try:
        # Get 0-th entry; ignore other possible variations.
        # IndexError means no mapping.
        lookup = TRANSLITERATE_DICT[text][TRANSLITERATE_EN][_TRANSLITERATE_IDX]
    except IndexError:
        return fallback_func(text)
    except TypeError as e:
        raise TypeError(f"`fallback_engine` is not callable. {e}") from e
    else:
        return cast("str", lookup)


def romanize(text: str, fallback_func: Callable[[str], str]) -> str:
    """
    Render Thai words in Latin alphabet with a lookup dictionary.

    The dictionary maps Thai words to their English transliteration.

    :param str text: Thai text to be romanized
    :param Callable[[str], str] fallback_func: Callable
    :return: A string of Thai words rendered in the Latin alphabet
    :rtype: str
    """
    # split by whitespace. word_tokenizer may break text into subwords.
    # e.g. กาแลกซี่ -> ["กา", "แลก", "ซี่"]
    words = text.strip().split()
    romanized_words = [_romanize(word, fallback_func) for word in words]

    return " ".join(romanized_words)
