"""
Main Bot Application
Advanced Telegram Bot for VPN/V2ray Shop with Referral System
"""
import asyncio
import logging
from aiogram import Dispatcher, Bot, F
from aiogram.types import BotCommand
from aiogram.client.default import DefaultBotProperties
from aiogram.enums import ParseMode
from aiogram.filters import Command

# Import handlers
from handlers import user_handlers, payment_handlers, admin_handlers
from config.settings import BOT_TOKEN, ADMIN_ID

# Configure logging
logging.basicConfig(
    level=logging.INFO,
    format='%(asctime)s - %(name)s - %(levelname)s - %(message)s'
)
logger = logging.getLogger(__name__)


async def set_bot_commands(bot: Bot):
    """Set bot commands"""
    commands = [
        BotCommand(command="start", description="شروع ربات"),
        BotCommand(command="help", description="راهنما"),
        BotCommand(command="admin", description="پنل مدیریت"),
    ]
    await bot.set_my_commands(commands)


async def on_startup(bot: Bot):
    """On startup handler"""
    logger.info("Bot is starting up...")
    await set_bot_commands(bot)
    logger.info(f"Bot commands set successfully")


async def on_shutdown(bot: Bot):
    """On shutdown handler"""
    logger.info("Bot is shutting down...")
    await bot.session.close()


async def main():
    """Main function"""
    # Create bot and dispatcher
    bot = Bot(
        token=BOT_TOKEN,
        default=DefaultBotProperties(parse_mode=ParseMode.HTML)
    )
    dp = Dispatcher()
    
    # Include routers
    dp.include_router(user_handlers.router)
    dp.include_router(payment_handlers.router)
    dp.include_router(admin_handlers.router)
    
    # Start polling
    try:
        logger.info("Bot started polling...")
        # Call setup before polling
        await on_startup(bot)
        await dp.start_polling(bot, allowed_updates=dp.resolve_used_update_types())
    except Exception as e:
        logger.error(f"Error during polling: {e}")
    finally:
        await bot.session.close()


if __name__ == "__main__":
    try:
        asyncio.run(main())
    except KeyboardInterrupt:
        logger.info("Bot stopped by user")
