import asyncio
import logging
from contextlib import suppress

from aiogram import Bot, Dispatcher
from aiogram.client.default import DefaultBotProperties
from aiogram.enums import ParseMode
from aiogram.exceptions import TelegramAPIError
from aiogram.filters import Command, CommandStart
from aiogram import F
from aiogram.types import Message

from config import config, app_config
from handlers import (
    handle_start_command,
    handle_text_message,
    handle_stats_callback,
    handle_help_command,
    handle_unknown_command,
    handle_qr_info_command,
)
from admin_handlers import (
    handle_admin_command,
    handle_generate_qr_callback,
    handle_qr_type_callback,
    handle_qr_generation_text,
    handle_admin_cancel_callback,
    handle_admin_stats_callback,
    handle_admin_settings_callback,
)

# Configure logging
logging.basicConfig(level=getattr(logging, app_config.LOG_LEVEL))
logger = logging.getLogger(__name__)

# Initialize bot
bot = Bot(token=config.token, default=DefaultBotProperties(parse_mode=ParseMode.HTML))
dp = Dispatcher()


def register_handlers():
    """Register all bot handlers"""

    # Start with just one handler to test
    dp.message.register(handle_start_command, CommandStart())

    # Callback query handlers
    dp.callback_query.register(handle_stats_callback, F.data == "stats")


async def main():
    """Main bot function"""
    try:
        # Validate configuration
        logger.info("Validating configuration...")
        config.validate()
        logger.info("Configuration validated successfully")

        # Register handlers
        logger.info("Registering handlers...")
        register_handlers()
        logger.info("Handlers registered successfully")

        # Set bot commands
        from aiogram.types import BotCommand
        await bot.set_my_commands([
            BotCommand(command="start", description="Запустить бота"),
            BotCommand(command="help", description="Помощь"),
            BotCommand(command="qr", description="Информация о QR-кодах"),
            BotCommand(command="admin", description="Панель администратора"),
        ])

        # Log bot startup
        logger.info(f"Starting bot @{config.bot_username}")
        logger.info(f"Frontend URL: {config.frontend_url}")
        logger.info(f"Backend API URL: {config.backend_api_url}")

        # Start bot
        await dp.start_polling(bot)

    except TelegramAPIError as e:
        logger.error(f"Telegram API error: {e}")
        raise
    except ValueError as e:
        logger.error(f"Configuration error: {e}")
        raise
    except Exception as e:
        logger.error(f"Unexpected error: {e}")
        raise


if __name__ == "__main__":
    try:
        asyncio.run(main())
    except KeyboardInterrupt:
        logger.info("Bot stopped by user")
    except Exception as e:
        logger.error(f"Bot crashed: {e}")