"""
author: Yagnik Poshiya
organization: Webbrains Technologies Private Limited

Language handling for visitor messages.

Scope is deliberately narrow: Gujarati, Hindi and English, which are the
languages the product supports. Everything here is deterministic string work —
no model call — because it runs on the blocking path of every turn and the
latency budget in docs/architecture/rag-agent-latency-playbook.md leaves no
room for an extra round trip just to find out what language someone typed in.

Detection is by script, which is exact for Gujarati and Devanagari and useless
for anything written in Latin letters. That limit is the point: "mane 30 lakh
nu ghar joiye" is Gujarati in Latin script and no range check will ever see it.
So detection is used to *strengthen* a prompt instruction when it is certain,
never to overrule the model, and the instruction itself always tells the model
to mirror the visitor regardless of what detection concluded.
"""

from __future__ import annotations

import re
from typing import Literal

LanguageCode = Literal["gu", "hi", "en", "unknown"]

# Unicode blocks. Gujarati and Devanagari do not overlap, so a single codepoint
# in either block is conclusive for that script.
_GUJARATI = (0x0A80, 0x0AFF)
_DEVANAGARI = (0x0900, 0x097F)

# Digits are separate from the letter ranges and must be translated before any
# numeric parsing: int("૩૦") raises, and a SQL parameter of "૩૦ લાખ" matches
# nothing in a column holding 3000000.
_GUJARATI_DIGITS = "૦૧૨૩૪૫૬૭૮૯"
_DEVANAGARI_DIGITS = "०१२३४५६७८९"
_DIGIT_MAP = {
    **{ord(d): str(i) for i, d in enumerate(_GUJARATI_DIGITS)},
    **{ord(d): str(i) for i, d in enumerate(_DEVANAGARI_DIGITS)},
}

# Indic scale words mapped to the English equivalents the extraction prompt
# already understands, rather than to raw multipliers. Rewriting "લાખ" to
# "lakh" lets one set of numeric rules keep working instead of duplicating them
# per language.
_SCALE_WORDS: dict[str, str] = {
    # Gujarati
    "લાખ": "lakh",
    "લાખો": "lakh",
    "કરોડ": "crore",
    "કરોડો": "crore",
    "હજાર": "thousand",
    # Hindi / Devanagari
    "लाख": "lakh",
    "लाखों": "lakh",
    "करोड़": "crore",
    "करोड": "crore",
    "करोड़ों": "crore",
    "हजार": "thousand",
    "हज़ार": "thousand",
}

_LANGUAGE_NAMES: dict[str, str] = {
    "gu": "Gujarati",
    "hi": "Hindi",
    "en": "English",
}


def _count_in_range(text: str, block: tuple[int, int]) -> int:
    low, high = block
    return sum(1 for ch in text if low <= ord(ch) <= high)


def detect_language(text: str) -> LanguageCode:
    """
    Best-effort language of a visitor message, by script.

    Returns "unknown" for Latin-script input rather than guessing "en": a
    romanised Gujarati or Hindi message is Latin script, and claiming English
    would make the prompt instruct the model to answer in the wrong language.
    "unknown" lets the caller fall back to "mirror the visitor", which is
    correct in every case.
    """
    value = str(text or "")
    if not value.strip():
        return "unknown"

    gujarati = _count_in_range(value, _GUJARATI)
    devanagari = _count_in_range(value, _DEVANAGARI)

    if gujarati or devanagari:
        return "gu" if gujarati >= devanagari else "hi"
    return "unknown"


def language_display_name(code: LanguageCode) -> str | None:
    return _LANGUAGE_NAMES.get(code)


def normalize_indic_digits(text: str) -> str:
    """Rewrite Gujarati and Devanagari digits to ASCII. Leaves everything else alone."""
    return str(text or "").translate(_DIGIT_MAP)


def normalize_scale_words(text: str) -> str:
    """Rewrite Indic scale words to the English words the numeric rules use."""
    value = str(text or "")
    for source, target in _SCALE_WORDS.items():
        if source in value:
            value = value.replace(source, f" {target} ")
    return re.sub(r"[ \t]{2,}", " ", value)


def normalize_numerics_for_extraction(text: str) -> str:
    """
    Prepare a message for parameter extraction.

    Only numerals and scale words are touched. The rest of the sentence stays
    in its original language, because the extractor still needs it to work out
    which parameter a value belongs to.
    """
    return normalize_scale_words(normalize_indic_digits(text)).strip()


# --- Romanised Gujarati / Hindi -------------------------------------------
#
# Script detection is blind to "mane 30 lakh nu ghar joiye" — it is Gujarati
# written in Latin letters, and every codepoint is ASCII. The only signal left
# is vocabulary, so these are common function words that are frequent in
# romanised Gujarati/Hindi and effectively absent from English.
#
# Deliberately excluded: "ka", "ke", "ki", "ma", "to", "he". They are real
# markers but collide with ordinary English words, and a false positive is
# worse than a miss — it would answer an English visitor in Hindi.
_GUJARATI_ROMAN = frozenset({
    "aapo", "batavo", "che", "chhe", "joiye", "ketla", "ketli", "mane",
    "maru", "mari", "shu", "tamaru", "tamne", "tamara", "nathi", "kyare",
})
_HINDI_ROMAN = frozenset({
    "aap", "batao", "chahiye", "dikhao", "hai", "hain", "kaise", "kitna",
    "kitne", "kripya", "mera", "meri", "mujhe", "nahi", "nahin", "hoga",
})

# Present in both, so they raise confidence that the text is Indic at all but
# cannot decide which language it is.
_SHARED_ROMAN = frozenset({"kya", "ghar", "lakh", "crore", "bhai", "acha", "thoda"})

# Two distinct markers, not one: a single "hai" could be a name or a typo.
_ROMAN_MIN_MARKERS = 2


def _roman_tokens(text: str) -> set[str]:
    return set(re.findall(r"[a-z]+", str(text or "").lower()))


def detect_romanised_language(text: str) -> LanguageCode:
    """
    Best-effort language for Indic text written in Latin letters.

    Returns "unknown" unless at least two distinct marker words are present,
    and unless one language clearly outscores the other. Guessing wrong here
    means answering an English visitor in Hindi, which is far worse than
    leaving them in English.
    """
    tokens = _roman_tokens(text)
    if not tokens:
        return "unknown"

    gu = tokens & _GUJARATI_ROMAN
    hi = tokens & _HINDI_ROMAN
    shared = tokens & _SHARED_ROMAN

    if len(gu) + len(hi) + len(shared) < _ROMAN_MIN_MARKERS:
        return "unknown"
    if len(gu) > len(hi):
        return "gu"
    if len(hi) > len(gu):
        return "hi"
    return "unknown"


def answer_language_instruction(text: str) -> str:
    """
    Prompt fragment telling the model which language to answer in.

    Three cases, in order of confidence. Native script is conclusive, so name
    the language and the script. Romanised Indic is a vocabulary guess, so name
    the language but insist on Latin script — someone who typed "mane ghar
    joiye" wants an answer they can read back, not Gujarati script. Otherwise
    fall back to mirroring, which is never wrong.
    """
    name = language_display_name(detect_language(text))
    if name:
        return (
            f"- The visitor wrote in {name}. Reply entirely in {name}, including "
            f"any labels, headings or list items. Do not switch to English partway "
            f"through, and do not translate proper nouns such as place or project names."
        )

    romanised = language_display_name(detect_romanised_language(text))
    if romanised:
        return (
            f"- The visitor wrote {romanised} using Latin letters (romanised). Reply in "
            f"{romanised} but keep the SAME Latin script they used — do not switch to "
            f"{romanised} script. Do not switch to English partway through."
        )

    return (
        "- Reply in the same language the visitor used, including romanised "
        "Gujarati or Hindi written in Latin letters. Match their script as well "
        "as their language, and do not switch language partway through."
    )


def database_value_language_rule() -> str:
    """
    Prompt fragment for parameter extraction.

    The knowledge base and the customer databases are English. A value lifted
    verbatim out of a Gujarati sentence goes into a SQL WHERE clause and matches
    nothing, so the extractor has to hand back the English form.
    """
    return (
        "- Stored data is in English. Return parameter VALUES in English even when "
        "the visitor wrote in another language or script: transliterate place and "
        "proper names to their usual English spelling (વડોદરા -> Vadodara, "
        "सूरत -> Surat) and return numbers as digits. Parameter NAMES are already "
        "English and must be returned exactly as given."
    )
