import os
import json

class LocalizationService:
    def __init__(self, locales_dir='locales', default_lang='en'):
        self.locales_dir = locales_dir
        self.default_lang = default_lang
        self.cache = {}
        self.load_locales()

    def load_locales(self):
        """Loads all languages and files into memory"""
        for lang in os.listdir(self.locales_dir):
            lang_path = os.path.join(self.locales_dir, lang)

            if os.path.isfile(lang_path) and lang.endswith('.json'):
                with open(lang_path, 'r', encoding='utf-8') as f:
                    self.cache[lang.split('.')[0]] = json.load(f)

            elif os.path.isdir(lang_path):
                self.cache[lang] = {}
                for file in os.listdir(lang_path):
                    if file.endswith('.json'):
                        with open(os.path.join(lang_path, file), 'r', encoding='utf-8') as f:
                            name = file.replace('.json', '')
                            self.cache[lang][name] = json.load(f)

    def t(self, key: str, lang: str = None):
        """Get a string, for example t('auth.login_success')"""
        lang = lang or self.default_lang

        parts = key.split('.')
        if len(parts) == 2:
            file, subkey = parts
        else:
            raise ValueError('Key must be in format module.key')
        
        data = self.cache.get(lang) or self.cache[self.default_lang]

        if isinstance(data, dict) and file in data:
            return data[file].get(subkey, f'[missing:{key}]')

        if file in data:
            return data[file].get(subkey, f'[missing:{key}]')

        return f'[missing:{key}]'
