from typing import Optional

import gcld3


class LanguageDetector(object):
    """
    Detect the language of a sample text and return its language code (ISO 639).
    """
    def __init__(self, min_num_bytes: int = 24, max_num_bytes: int = 2000, allow_guess: bool = True):
        self._allow_guess = allow_guess
        self._lang_det = gcld3.NNetLanguageIdentifier(min_num_bytes, max_num_bytes)

    def get_primary_language(self, text: Optional[str]) -> Optional[str]:
        if text:
            r = self._lang_det.FindLanguage(text)
            if (lang := r.language) != "und" and (self._allow_guess or r.is_reliable):
                # There are languages which have romanized or latin transcript from their original alphabet. These
                # transcribed forms have no supported indexing tokenization by solr even if they are a specific language
                # that has support. The best thing we can do is to not detect them in this form and have the fallback
                # tokenization do what it can at least.
                if not lang.endswith("-Latn"):
                    return lang
