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

class QuizI18n:
    """Handles internationalization for the quiz plugin"""
    
    def __init__(self, language: str = 'en', custom_synonyms: Optional[Dict] = None):
        self.language = language
        self.fallback_language = 'en'
        self.custom_synonyms = custom_synonyms or {}
        
        self.i18n_dir = Path(__file__).parent / 'i18n'
        self.translations = self._load_translations()
        self.fallback = self._load_fallback()
        self.quiz_type_map = self._build_quiz_type_map()
    
    def _load_translations(self) -> Dict:
        translation_file = self.i18n_dir / f'{self.language}.json'
        
        if not translation_file.exists():
            print(f"⚠️  Translation file not found: {translation_file}")
            print(f"   Falling back to {self.fallback_language}")
            return {}
        
        with open(translation_file, 'r', encoding='utf-8') as f:
            return json.load(f)
    
    def _load_fallback(self) -> Dict:
        fallback_file = self.i18n_dir / f'{self.fallback_language}.json'
        
        with open(fallback_file, 'r', encoding='utf-8') as f:
            return json.load(f)
    
    def _build_quiz_type_map(self) -> Dict[str, str]:
        mapping = {}
        
        quiz_types = self.translations.get('quiz_types', self.fallback.get('quiz_types', {}))
        
        for quiz_type, data in quiz_types.items():
            for synonym in data.get('synonyms', []):
                if synonym in mapping:
                    print(f"⚠️  Synonym conflict: '{synonym}' already maps to '{mapping[synonym]}'")
                else:
                    mapping[synonym.lower()] = quiz_type
            
            custom = self.custom_synonyms.get(quiz_type, {}).get('synonyms', '')
            if custom:
                custom_list = [s.strip() for s in custom.split(',') if s.strip()]
                for synonym in custom_list:
                    synonym_lower = synonym.lower()
                    if synonym_lower in mapping:
                        print(f"⚠️  Custom synonym '{synonym}' conflicts with existing mapping")
                        print(f"   Skipping to avoid ambiguity")
                    else:
                        mapping[synonym_lower] = quiz_type
                        print(f"✅ Added custom synonym: '{synonym}' -> '{quiz_type}'")
        
        return mapping
    
    def get_quiz_type(self, synonym: str) -> Optional[str]:
        return self.quiz_type_map.get(synonym.lower())
    
    def get_quiz_synonyms(self, quiz_type: str) -> List[str]:
        quiz_types = self.translations.get('quiz_types', self.fallback.get('quiz_types', {}))
        return quiz_types.get(quiz_type, {}).get('synonyms', [])
    
    def t(self, key: str, fallback: str = '') -> str:
        keys = key.split('.')
        
        value = self.translations
        for k in keys:
            if isinstance(value, dict):
                value = value.get(k)
            else:
                value = None
                break
        
        if value is not None:
            return str(value)
        
        value = self.fallback
        for k in keys:
            if isinstance(value, dict):
                value = value.get(k)
            else:
                value = None
                break
        
        if value is not None:
            return str(value)
        
        return fallback or key
    
    def get_all_quiz_type_synonyms(self) -> List[str]:
        return list(self.quiz_type_map.keys())

