from typing import Any, Dict
from aiogram.types import TelegramObject
from aiogram.utils.i18n import I18n, I18nMiddleware


class CustomI18nMiddleware(I18nMiddleware):
    def __init__(self, i18n, db):
        super().__init__(i18n)
        self.db = db

    async def get_locale(self, event: TelegramObject, data: Dict[str, Any]) -> str:
        user = data["event_from_user"]
        if user is None:
            return 'en'

        user_id = int(user.id)
        user_info = await self.db.get_by_user_id(user_id)

        if user_info is None:
            if user.language_code != 'ru':
                return 'en'
            if user.language_code == 'ru': 
                return 'ru'

        lang_code = user_info["language"]
        if lang_code == 'ru':
            return lang_code
        if lang_code != 'ru':
            return 'en'
        return lang_code