"""
Multilingual Wiki & Knowledge Base Service for FreeExile.
Provides localized terminology lookup and search queries across 9 global languages
for in-game encyclopedia screens, tooltips, and community APIs.
"""

import json
from pathlib import Path
from typing import Dict, List, Optional, Any


LOCALES_DIR = Path(r"C:\Projects\FreeExile\data\locales")


class LocalizedWikiService:
    def __init__(self, locales_dir: Path = LOCALES_DIR):
        self.locales_dir = locales_dir
        self.dictionaries: Dict[str, Dict[str, str]] = {}
        self.load_all_locales()

    def load_all_locales(self):
        """Loads all .json files in the locales directory."""
        if not self.locales_dir.exists():
            return

        for json_path in self.locales_dir.glob("*.json"):
            try:
                with open(json_path, "r", encoding="utf-8") as f:
                    data = json.load(f)
                    locale = data.get("locale")
                    translations = data.get("translations", {})
                    if locale and translations:
                        self.dictionaries[locale] = translations
            except Exception:
                pass

    def get_term(self, key: str, locale: str = "en") -> str:
        """Retrieves localized string with fallback chain (locale -> en -> vi -> key)."""
        # 1. Target locale
        if locale in self.dictionaries and key in self.dictionaries[locale]:
            return self.dictionaries[locale][key]

        # 2. English fallback
        if "en" in self.dictionaries and key in self.dictionaries["en"]:
            return self.dictionaries["en"][key]

        # 3. Vietnamese fallback
        if "vi" in self.dictionaries and key in self.dictionaries["vi"]:
            return self.dictionaries["vi"][key]

        return key

    def search_terms(self, query: str, locale: str = "en") -> List[Dict[str, str]]:
        """Searches terms matching the query in the specified locale."""
        dict_data = self.dictionaries.get(locale, self.dictionaries.get("en", {}))
        results = []
        q_lower = query.lower()

        for key, val in dict_data.items():
            if q_lower in key.lower() or q_lower in val.lower():
                results.append({
                    "key": key,
                    "translation": val,
                    "locale": locale
                })

        return results

    def get_supported_locales(self) -> List[str]:
        return list(self.dictionaries.keys())
