from __future__ import annotations

import asyncio
import logging

from aiogram import Bot, Dispatcher
from aiogram.client.default import DefaultBotProperties
from aiogram.enums import ParseMode
from aiogram.fsm.storage.memory import MemoryStorage

from app import leaderboard, reseller_runtime
from app.config import get_settings
from app.db import init_db
from app.handlers import build_router
from app.middlewares import SubscriptionMiddleware

logger = logging.getLogger(__name__)


async def run_bot() -> None:
    settings = get_settings()
    if not settings.bot_token:
        raise RuntimeError("BOT_TOKEN is not set. Fill in .env (see .env.example).")
    if not settings.admin_id_list:
        logger.warning("ADMIN_IDS is empty — the admin panel will be unavailable.")

    await init_db()

    bot = Bot(
        token=settings.bot_token,
        default=DefaultBotProperties(parse_mode=ParseMode.HTML),
    )
    dp = Dispatcher(storage=MemoryStorage())
    dp.update.outer_middleware(SubscriptionMiddleware())
    dp.include_router(build_router())

    logger.info("Bot started.")
    await bot.delete_webhook(drop_pending_updates=True)
    lb_task = asyncio.create_task(leaderboard.weekly_loop(bot))
    await reseller_runtime.start_all_reseller_bots()
    try:
        await dp.start_polling(bot)
    finally:
        lb_task.cancel()
        for task in reseller_runtime.reseller_tasks():
            task.cancel()
