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

Tests for agent.language.

Written as plain asserts so they run under pytest once the runner lands
(CLAUDE.md §9 rule 3, tracked as T-05) and, until then, directly:

    PYTHONPATH=src .venv/bin/python tests/test_language.py
"""

from __future__ import annotations

import os
import sys

sys.path.insert(0, os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), "src"))

from agent.language import (  # noqa: E402
    answer_language_instruction,
    detect_romanised_language,
    database_value_language_rule,
    detect_language,
    language_display_name,
    normalize_indic_digits,
    normalize_numerics_for_extraction,
    normalize_scale_words,
)


def test_detects_gujarati_script():
    assert detect_language("મને ઘર જોઈએ") == "gu"
    assert detect_language("વડોદરામાં ફ્લેટ") == "gu"


def test_detects_devanagari_as_hindi():
    assert detect_language("मुझे घर चाहिए") == "hi"
    assert detect_language("सूरत में फ्लैट") == "hi"


def test_latin_script_is_unknown_not_english():
    # Romanised Gujarati is Latin script. Claiming "en" here would make the
    # prompt instruct the model to answer in the wrong language, so the
    # honest answer is "unknown" and the caller falls back to mirroring.
    assert detect_language("mane 30 lakh nu ghar joiye") == "unknown"
    assert detect_language("show me homes under 30 lakh") == "unknown"


def test_empty_and_blank_are_unknown():
    assert detect_language("") == "unknown"
    assert detect_language("   \n\t ") == "unknown"
    assert detect_language(None) == "unknown"


def test_mixed_script_picks_the_dominant_one():
    # A Gujarati sentence quoting one English word is still Gujarati.
    assert detect_language("મને Vadodara માં ઘર જોઈએ") == "gu"
    assert detect_language("मुझे Surat में घर चाहिए") == "hi"


def test_digits_alone_do_not_decide_language():
    assert detect_language("3000000") == "unknown"


def test_gujarati_digits_become_ascii():
    assert normalize_indic_digits("૩૦") == "30"
    assert normalize_indic_digits("૦૧૨૩૪૫૬૭૮૯") == "0123456789"


def test_devanagari_digits_become_ascii():
    assert normalize_indic_digits("३०") == "30"
    assert normalize_indic_digits("०१२३४५६७८९") == "0123456789"


def test_digit_normalisation_leaves_letters_alone():
    assert normalize_indic_digits("મને ૩૦ જોઈએ") == "મને 30 જોઈએ"
    assert normalize_indic_digits("already 30 ascii") == "already 30 ascii"


def test_scale_words_map_to_english():
    assert "lakh" in normalize_scale_words("૩૦ લાખ")
    assert "crore" in normalize_scale_words("२ करोड़")
    assert "thousand" in normalize_scale_words("પચાસ હજાર")


def test_scale_word_plurals():
    assert "lakh" in normalize_scale_words("લાખો")
    assert "crore" in normalize_scale_words("करोड़ों")


def test_full_normalisation_leaves_the_sentence_translatable():
    # Numerals and scale words become machine-readable, but the rest of the
    # sentence stays Gujarati so the extractor can still tell which parameter
    # the value belongs to.
    out = normalize_numerics_for_extraction("મને ૩૦ લાખનું ઘર જોઈએ")
    assert "30" in out
    assert "lakh" in out
    assert "ઘર" in out


def test_normalisation_is_a_noop_for_plain_english():
    assert normalize_numerics_for_extraction("homes under 30 lakh") == "homes under 30 lakh"


def test_answer_instruction_names_a_detected_language():
    assert "Gujarati" in answer_language_instruction("મને ઘર જોઈએ")
    assert "Hindi" in answer_language_instruction("मुझे घर चाहिए")


def test_answer_instruction_falls_back_to_mirroring():
    # Neither native script nor enough romanised markers to call it, so the
    # instruction must fall back to "mirror whatever they used".
    instruction = answer_language_instruction("hello, can you help me")
    assert "same language" in instruction
    # The fallback still has to mention romanised input, or Hinglish that the
    # marker list misses would silently get an English answer.
    assert "romanised" in instruction.lower()


def test_answer_instruction_always_forbids_switching_midway():
    for message in ("મને ઘર જોઈએ", "मुझे घर चाहिए", "show me homes"):
        assert "partway" in answer_language_instruction(message)


def test_detects_romanised_gujarati():
    assert detect_romanised_language("mane 30 lakh nu ghar joiye") == "gu"
    assert detect_romanised_language("tamne shu joiye che") == "gu"


def test_detects_romanised_hindi():
    assert detect_romanised_language("mujhe ghar chahiye") == "hi"
    assert detect_romanised_language("kitne products hain") == "hi"


def test_plain_english_is_never_mistaken_for_indic():
    # A false positive answers an English visitor in Hindi, which is worse
    # than missing a romanised one — so these must all stay "unknown".
    for message in (
        "show me products that are in stock",
        "hello there how are you",
        "what is the price of this item",
        "I need a house in the city centre",
        "can you help me find something",
    ):
        assert detect_romanised_language(message) == "unknown", message


def test_single_marker_is_not_enough():
    # "hai" alone could be a name or a typo; one word must not decide.
    assert detect_romanised_language("hai") == "unknown"
    assert detect_romanised_language("che") == "unknown"


def test_ambiguous_romanised_stays_unknown():
    # Shared vocabulary with no language-specific marker cannot be resolved,
    # and guessing between Gujarati and Hindi would be a coin flip.
    assert detect_romanised_language("kya ghar") == "unknown"


def test_romanised_instruction_keeps_latin_script():
    instruction = answer_language_instruction("mane 30 lakh nu ghar joiye")
    assert "Gujarati" in instruction
    assert "Latin" in instruction
    # Someone typing in Latin letters wants to read the answer back.
    assert "SAME Latin script" in instruction


def test_native_script_still_wins_over_romanised():
    # Gujarati script present, so the romanised path must not override it.
    instruction = answer_language_instruction("મને ઘર જોઈએ")
    assert "Gujarati" in instruction
    assert "romanised" not in instruction.lower()


def test_database_rule_demands_english_values():
    rule = database_value_language_rule()
    assert "English" in rule
    assert "Vadodara" in rule  # a worked example beats an abstract instruction


def test_language_display_names():
    assert language_display_name("gu") == "Gujarati"
    assert language_display_name("hi") == "Hindi"
    assert language_display_name("unknown") is None


def _main() -> int:
    tests = [(n, f) for n, f in sorted(globals().items()) if n.startswith("test_") and callable(f)]
    failed = 0
    for name, fn in tests:
        try:
            fn()
            print(f"  ✓ {name}")
        except AssertionError as exc:
            failed += 1
            print(f"  ✗ {name}: {exc or 'assertion failed'}")
    print(f"\n{len(tests) - failed} passed, {failed} failed")
    return 1 if failed else 0


if __name__ == "__main__":
    raise SystemExit(_main())
