import logging
import asyncio
import sys
import os
from aiogram import Bot, Dispatcher
from aiogram.client.default import DefaultBotProperties
from aiogram.fsm.storage.memory import MemoryStorage
from aiogram.utils.i18n import I18n
from config import BOT_TOKEN, INTERVAL_HOURS, DATABASE_PATH, LOCALES_PATH
from handlers import common, admin, user
from models.database import Database
from models.user import User
from models.admin import Admin
from middlewares.language import CustomI18nMiddleware
from middlewares.context import ContextMiddleware
from middlewares.flood import AntiFloodMiddleware
from apscheduler.schedulers.asyncio import AsyncIOScheduler
from apscheduler.triggers.interval import IntervalTrigger
from utils import backup

dp = Dispatcher(storage=MemoryStorage())
bot = Bot(token=BOT_TOKEN, default=DefaultBotProperties(parse_mode='HTML'))

async def main() -> None:
    # database
    db = Database(DATABASE_PATH)
    user_model = User(db)
    admin_model = Admin(db)

    #language
    i18n = I18n(path=LOCALES_PATH, default_locale="en", domain="messages")
    i18n_middleware = CustomI18nMiddleware(i18n=i18n, db=user_model)

    #backup tasks
    scheduler = AsyncIOScheduler()
    scheduler.add_job(
        backup.backup_database,
        IntervalTrigger(hours=INTERVAL_HOURS),
        id='backups_database',
        name='Backup Database',
        replace_existing=True
    )
    scheduler.start()

    dp.include_routers(common.router, admin.router, user.router)
    dp.update.middleware.register(i18n_middleware)
    dp.update.middleware.register(ContextMiddleware(db, user_model, admin_model))
    #dp.update.middleware.register(AntiFloodMiddleware())
    await bot.delete_webhook(drop_pending_updates=True)
    await dp.start_polling(bot, skip_updates=True)

def entrypoint():
    logging.basicConfig(level=logging.INFO, stream=sys.stdout)
    asyncio.run(main())

if __name__ == "__main__":
    entrypoint()