"""
Пример использования UI Router
"""

import asyncio
from aiogram import Bot, Dispatcher, BaseMiddleware
from aiogram.types import Message
from aiogram.filters import CommandStart
from aiogram.fsm.storage.memory import MemoryStorage

from ui_router import (
    UIRouter,
    UIRouterExecutor,
    Scene,
    Handler,
    GlobalHandler,
    ActionInstruction,
    ActionType,
    EventType,
    TransitionType,
    MessageContent,
    Keyboard,
    Button,
    Filter,
    Flag,
    FlagGetter,
    DynamicContent,
    ContentTemplate,
    CallbackDataStrategy,
)
from ui_router.services import SharedServices
from ui_router.state.storage import InMemoryNavigationStorage
from ui_router.state.variables import InMemoryVariableRepository
from ui_router.events import EventBus, InMemoryEventScheduler


# ============================================================================
# Кастомные функции (геттеры, условия)
# ============================================================================


async def get_user_balance(context) -> int:
    """Получить баланс пользователя"""
    # В реальном проекте - запрос в БД
    return 1500


async def get_user_name(context) -> str:
    """Получить имя пользователя"""
    return "Иван"


async def is_user_vip(context) -> bool:
    """Проверка VIP статуса"""
    # В реальном проекте - проверка в БД
    return True


# ============================================================================
# Создание UI схемы
# ============================================================================

ui_schema = UIRouter(
    name="shop_bot",
    version="1.0.0",
    initial_scene="main_menu",
    # Настройки callback_data
    callback_strategy=CallbackDataStrategy(
        type="inline",  # или "cache" с Redis
        separator=":",
        max_length=64,
    ),
    # Регистрация кастомных функций
    custom_functions={
        "get_user_balance": "example.get_user_balance",
        "get_user_name": "example.get_user_name",
        "is_user_vip": "example.is_user_vip",
    },
    # Глобальные хендлеры
    global_handlers=[
        GlobalHandler(
            name="cancel_command",
            event_type=EventType.MESSAGE,
            filters=[Filter(type="command", commands=["cancel"])],
            priority=10,
            interrupt_propagation=True,
            actions=[
                ActionInstruction(
                    type=ActionType.SEND_MESSAGE,
                    content=MessageContent(text="❌ Действие отменено"),
                ),
                ActionInstruction(
                    type=ActionType.GOTO_SCENE,
                    scene_id="main_menu",
                    transition=TransitionType.SEND,
                ),
            ],
        ),
    ],
    # Сцены
    scenes=[
        # ====================================================================
        # Главное меню
        # ====================================================================
        Scene(
            id="main_menu",
            name="Главное меню",
            description="Стартовая сцена",
            # Флаги (динамические данные)
            flags=[
                Flag(
                    name="user_name",
                    getter=FlagGetter(type="function", function="get_user_name"),
                ),
                Flag(
                    name="balance",
                    getter=FlagGetter(type="function", function="get_user_balance"),
                    default=0,
                ),
            ],
            # Контент по умолчанию
            default_content=MessageContent(
                text=DynamicContent(
                    type="template",
                    template=ContentTemplate(
                        template="👋 Привет, {user_name}!\n\n💰 Ваш баланс: {balance} руб.",
                        flags=["user_name", "balance"],
                    ),
                ),
            ),
            # Клавиатура по умолчанию
            default_keyboard=Keyboard(
                is_inline=True,
                buttons=[
                    [
                        Button(
                            text="🛍 Товары",
                            callback_action="show_products",
                        ),
                    ],
                    [
                        Button(
                            text="💳 Пополнить баланс",
                            callback_action="topup_menu",
                        ),
                    ],
                    [
                        Button(
                            text="👤 Профиль",
                            callback_action="show_profile",
                        ),
                    ],
                ],
            ),
            # Хендлеры
            handlers=[
                Handler(
                    name="show_products",
                    event_type=EventType.CALLBACK,
                    filters=[],  # Вызов через callback_action="show_products"
                    actions=[
                        ActionInstruction(
                            type=ActionType.GOTO_SCENE,
                            scene_id="products",
                            transition=TransitionType.EDIT_SMART,
                        ),
                    ],
                    require_state=False,
                ),
                Handler(
                    name="topup_menu",
                    event_type=EventType.CALLBACK,
                    filters=[],
                    actions=[
                        ActionInstruction(
                            type=ActionType.GOTO_SCENE,
                            scene_id="topup",
                            transition=TransitionType.EDIT_SMART,
                        ),
                    ],
                    require_state=False,
                ),
                Handler(
                    name="show_profile",
                    event_type=EventType.CALLBACK,
                    filters=[],
                    actions=[
                        ActionInstruction(
                            type=ActionType.GOTO_SCENE,
                            scene_id="profile",
                            transition=TransitionType.EDIT_SMART,
                        ),
                    ],
                    require_state=False,
                ),
            ],
        ),
        # ====================================================================
        # Каталог товаров
        # ====================================================================
        Scene(
            id="products",
            name="Каталог товаров",
            parent_scene="main_menu",
            default_content=MessageContent(
                text="🛍 <b>Каталог товаров</b>\n\nВыберите категорию:",
            ),
            default_keyboard=Keyboard(
                buttons=[
                    [
                        Button(text="📱 Электроника", callback_action="category_electronics"),
                    ],
                    [
                        Button(text="👕 Одежда", callback_action="category_clothes"),
                    ],
                    [
                        Button(text="🏠 Для дома", callback_action="category_home"),
                    ],
                    [
                        Button(text="◀️ Назад", callback_action="go_back"),
                    ],
                ],
            ),
            handlers=[
                Handler(
                    name="category_electronics",
                    event_type=EventType.CALLBACK,
                    actions=[
                        ActionInstruction(
                            type=ActionType.EDIT_MESSAGE,
                            content=MessageContent(
                                text="📱 <b>Электроника</b>\n\nТовары появятся здесь...",
                            ),
                            keyboard=Keyboard(
                                buttons=[
                                    [Button(text="◀️ Назад", callback_action="go_back")],
                                ],
                            ),
                        ),
                    ],
                    require_state=False,
                ),
                Handler(
                    name="go_back",
                    event_type=EventType.CALLBACK,
                    actions=[
                        ActionInstruction(
                            type=ActionType.BACK,
                            transition=TransitionType.EDIT_SMART,
                        ),
                    ],
                    require_state=False,
                ),
            ],
        ),
        # ====================================================================
        # Пополнение баланса
        # ====================================================================
        Scene(
            id="topup",
            name="Пополнение баланса",
            parent_scene="main_menu",
            default_content=MessageContent(
                text="💳 <b>Пополнение баланса</b>\n\nВыберите сумму:",
            ),
            default_keyboard=Keyboard(
                buttons=[
                    [
                        Button(text="100 ₽", callback_action="topup_100"),
                        Button(text="500 ₽", callback_action="topup_500"),
                    ],
                    [
                        Button(text="1000 ₽", callback_action="topup_1000", style="danger"),
                        Button(text="5000 ₽", callback_action="topup_5000"),
                    ],
                    [
                        Button(text="✏️ Свою сумму", callback_action="topup_custom"),
                    ],
                    [
                        Button(text="◀️ Назад", callback_action="go_back"),
                    ],
                ],
            ),
            handlers=[
                Handler(
                    name="topup_100",
                    event_type=EventType.CALLBACK,
                    actions=[
                        ActionInstruction(
                            type=ActionType.ANSWER_CALLBACK,
                            callback_text="Создаём ссылку на оплату...",
                        ),
                        ActionInstruction(
                            type=ActionType.BUSINESS_ACTION,
                            business_action="create_payment_link",
                            params={"amount": 100, "currency": "RUB"},
                        ),
                        ActionInstruction(
                            type=ActionType.SEND_MESSAGE,
                            content=MessageContent(
                                text="💳 Ссылка для оплаты 100 руб:\n{payment_url}",
                            ),
                        ),
                    ],
                    require_state=False,
                ),
                Handler(
                    name="topup_custom",
                    event_type=EventType.CALLBACK,
                    actions=[
                        ActionInstruction(
                            type=ActionType.GOTO_SCENE,
                            scene_id="topup_custom_amount",
                            transition=TransitionType.EDIT_SMART,
                        ),
                    ],
                    require_state=False,
                ),
                Handler(
                    name="go_back",
                    event_type=EventType.CALLBACK,
                    actions=[
                        ActionInstruction(type=ActionType.BACK),
                    ],
                    require_state=False,
                ),
            ],
        ),
        # ====================================================================
        # Ввод кастомной суммы
        # ====================================================================
        Scene(
            id="topup_custom_amount",
            name="Ввод суммы",
            parent_scene="topup",
            expect_input=True,
            default_content=MessageContent(
                text="✏️ Введите сумму для пополнения (от 100 до 15000 руб):",
            ),
            handlers=[
                Handler(
                    name="process_amount",
                    event_type=EventType.MESSAGE,
                    filters=[Filter(type="text")],
                    actions=[
                        ActionInstruction(
                            type=ActionType.SAVE_INPUT,
                            save_as="topup_amount",
                        ),
                        ActionInstruction(
                            type=ActionType.BUSINESS_ACTION,
                            business_action="create_payment_link",
                            params={"amount": "{topup_amount}", "currency": "RUB"},
                        ),
                        ActionInstruction(
                            type=ActionType.SEND_MESSAGE,
                            content=MessageContent(
                                text="💳 Ссылка для оплаты {topup_amount} руб:\n{payment_url}",
                            ),
                        ),
                        ActionInstruction(
                            type=ActionType.GOTO_SCENE,
                            scene_id="main_menu",
                        ),
                    ],
                ),
            ],
        ),
        # ====================================================================
        # Профиль (только для VIP)
        # ====================================================================
        Scene(
            id="profile",
            name="Профиль",
            parent_scene="main_menu",
            flags=[
                Flag(
                    name="user_name",
                    getter=FlagGetter(type="function", function="get_user_name"),
                ),
                Flag(
                    name="balance",
                    getter=FlagGetter(type="function", function="get_user_balance"),
                ),
            ],
            default_content=MessageContent(
                text=DynamicContent(
                    type="template",
                    template=ContentTemplate(
                        template="👤 <b>Профиль</b>\n\nИмя: {user_name}\nБаланс: {balance} руб.\nСтатус: VIP ⭐",
                        flags=["user_name", "balance"],
                    ),
                ),
            ),
            default_keyboard=Keyboard(
                buttons=[
                    [Button(text="◀️ Назад", callback_action="go_back")],
                ],
            ),
            handlers=[
                Handler(
                    name="show_vip_section",
                    event_type=EventType.CALLBACK,
                    conditions=["is_user_vip"],  # Только для VIP
                    actions=[
                        ActionInstruction(
                            type=ActionType.SEND_MESSAGE,
                            content=MessageContent(
                                text="⭐ VIP раздел доступен!",
                            ),
                        ),
                    ],
                ),
                Handler(
                    name="go_back",
                    event_type=EventType.CALLBACK,
                    actions=[
                        ActionInstruction(type=ActionType.BACK),
                    ],
                ),
            ],
        ),
    ],
)


# ============================================================================
# Инициализация бота
# ============================================================================


async def main() -> None:
    # Создаём бота
    bot = Bot(token="5923234043:AAE0NIq1_dNVHVXrkcVG0sz-4mZWAQyQR28")
    storage = MemoryStorage()
    dp = Dispatcher(storage=storage)

    # Создаём SharedServices - общие компоненты для всех роутеров
    shared = SharedServices(
        navigation_storage=InMemoryNavigationStorage(),
        variable_repository=InMemoryVariableRepository(),
        event_bus=EventBus(),
        event_scheduler=InMemoryEventScheduler(event_callback=lambda e: None),
    )

    # Создаём UI роутер с новым API
    ui_router = UIRouterExecutor(
        schema=ui_schema,
        shared=shared,
    )

    # Регистрируем функции вручную (если не через import_path)
    ui_router.registry.getters.register("get_user_balance", get_user_balance)
    ui_router.registry.getters.register("get_user_name", get_user_name)
    ui_router.registry.conditions.register("is_user_vip", is_user_vip)

    # Подключаем роутер к диспетчеру
    dp.include_router(ui_router.get_router())

    class CallbackDataLogMiddleware(BaseMiddleware):
        async def __call__(self, handler, event, data):
            print(event.data)
            return await handler(event, data)

    dp.callback_query.middleware(CallbackDataLogMiddleware())

    # Хендлер /start
    @dp.message(CommandStart())
    async def start_handler(message: Message, **kwargs) -> None:
        print(1)
        await ui_router.start(message.from_user.id, message, **kwargs)

    # Запуск
    print("Бот запущен!")
    await dp.start_polling(bot)


if __name__ == "__main__":
    asyncio.run(main())
