"""
Unit tests for FreeExile Multilingual Localization & Wiki Service.
Verifies completeness across 9 global languages, key parity, fallback chaining, and search lookups.
"""

import unittest
import sys
import os

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

from common.wiki_service import LocalizedWikiService


class TestLocalizationAndWiki(unittest.TestCase):
    def setUp(self):
        self.service = LocalizedWikiService()

    def test_all_nine_locales_loaded(self):
        """Must load all 9 primary global gaming languages."""
        expected = {"vi", "en", "zh", "ja", "ko", "th", "de", "ru", "es"}
        loaded = set(self.service.get_supported_locales())
        self.assertTrue(expected.issubset(loaded), f"Missing locales: {expected - loaded}")

    def test_essential_terminology_parity(self):
        """Essential terminology keys must exist across all 9 languages."""
        essential_keys = [
            "game_title",
            "stone_hon_nguyen",
            "stone_thien_menh",
            "stone_thai_hu_kinh",
            "meridian_chart",
            "combat_huyen_anh_bo",
            "vault_title",
            "vault_instant_buyout"
        ]

        for loc in ["vi", "en", "zh", "ja", "ko", "th", "de", "ru", "es"]:
            for key in essential_keys:
                term = self.service.get_term(key, locale=loc)
                self.assertNotEqual(term, key, f"Key '{key}' is missing translation in locale '{loc}'")
                self.assertTrue(len(term) > 0)

    def test_fallback_chain_to_english_and_vietnamese(self):
        """If a key is missing in German, it falls back to English, then Vietnamese."""
        # Inject dummy dictionary
        self.service.dictionaries["en"]["test_fallback_key"] = "English Fallback"
        # German doesn't have it
        term = self.service.get_term("test_fallback_key", locale="de")
        self.assertEqual(term, "English Fallback")

    def test_localized_search_query(self):
        """Search queries return matching terms in target language."""
        results_zh = self.service.search_terms("混元石", locale="zh")
        self.assertGreater(len(results_zh), 0)
        self.assertEqual(results_zh[0]["key"], "stone_hon_nguyen")

        results_en = self.service.search_terms("Primal Chaos", locale="en")
        self.assertGreater(len(results_en), 0)
        self.assertEqual(results_en[0]["key"], "stone_hon_nguyen")


if __name__ == "__main__":
    unittest.main()
