import asyncio
import logging
from aiogram import Bot, Dispatcher

from config import config
from database import Database
from handlers import admin, user
from services.sms_poller import sms_poller_loop

logging.basicConfig(
    level=logging.INFO,
    format="%(asctime)s [%(levelname)s] %(name)s: %(message)s",
)


async def expired_lock_cleaner(db: Database) -> None:
    while True:
        try:
            released = await db.release_expired_locks()
            if released:
                logging.info("Released %s expired number locks.", released)
        except Exception as exc:
            logging.error("Lock cleaner error: %s", exc)
        await asyncio.sleep(60)


async def main() -> None:
    if not config.bot_token:
        raise RuntimeError("BOT_TOKEN is missing. Please configure .env first.")

    db = Database(
        config.db_path,
        default_mask_text=config.default_mask_text,
        default_sms_url=config.sms_api_url,
        default_sms_key=config.sms_api_key,
    )
    await db.init()

    bot = Bot(token=config.bot_token)
    dp = Dispatcher()
    dp["db"] = db

    dp.include_router(admin.router)
    dp.include_router(user.router)

    asyncio.create_task(expired_lock_cleaner(db))
    asyncio.create_task(sms_poller_loop(bot, db))

    logging.info("Multi-Panel SMS/OTP Bot started successfully.")
    await dp.start_polling(bot)


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