import asyncio
import logging
from aiogram import Bot, Dispatcher
from utils.sqlite_storage import SQLiteStorage

# ── Initialize professional logger FIRST, before any other imports ──────────
from utils.logger import setup_logging, get_logger
setup_logging(level=logging.DEBUG)
logger = get_logger(__name__)
# ────────────────────────────────────────────────────────────────────────────

from config import BOT_TOKEN
from database.db import init_db
from middlewares.db_middleware import DbMiddleware

from handlers.common import router as common_router
from handlers.client import router as client_router
from handlers.freelancer import router as freelancer_router
from handlers.admin import router as admin_router
from handlers.inline_query import router as inline_router

async def main():
    await init_db()

    # Load dynamic admins from settings database
    try:
        from database.db import get_setting
        import config
        dynamic_admins_str = await get_setting("dynamic_admin_ids", "")
        if dynamic_admins_str:
            dynamic_admin_ids = [int(x.strip()) for x in dynamic_admins_str.split(",") if x.strip()]
            for admin_id in dynamic_admin_ids:
                if admin_id not in config.ADMIN_IDS:
                    config.ADMIN_IDS.append(admin_id)
            logger.info(f"Loaded dynamic admins: {dynamic_admin_ids}. Total admins: {config.ADMIN_IDS}")
    except Exception as e:
        logger.error(f"Error loading dynamic admins: {e}")

    # Run monthly connects grant check on startup
    from database.db import check_and_grant_monthly_connects
    try:
        await check_and_grant_monthly_connects()
    except Exception as e:
        logger.error(f"Error in startup monthly connects grant: {e}")

    # Start background task to check and grant connects daily
    async def monthly_grant_checker():
        while True:
            await asyncio.sleep(86400) # Check once every 24 hours
            try:
                await check_and_grant_monthly_connects()
            except Exception as e:
                logger.error(f"Error in background monthly connects grant check: {e}")
                
    asyncio.create_task(monthly_grant_checker())

    from middlewares.antiflood_middleware import AntiFloodMiddleware
    from utils.web_server import start_web_server
    
    bot = Bot(token=BOT_TOKEN)
    
    # Automatically upload welcome banner to cache welcome_banner_file_id if empty
    try:
        from database.db import get_setting, update_setting
        import os
        from aiogram.types import FSInputFile
        import config
        
        async def init_welcome_banner():
            await asyncio.sleep(3) # Wait for bot initialization
            file_id = await get_setting("welcome_banner_file_id", "")
            if not file_id:
                banner_path = "assets/welcome_banner.png"
                if os.path.exists(banner_path) and config.ADMIN_IDS:
                    for admin_id in config.ADMIN_IDS:
                        try:
                            photo_file = FSInputFile(banner_path)
                            sent_msg = await bot.send_photo(
                                chat_id=admin_id,
                                photo=photo_file,
                                caption="🔄 در حال راه‌اندازی و کش کردن بنر خوش‌آمدگویی ربات..."
                            )
                            if sent_msg.photo:
                                new_file_id = sent_msg.photo[-1].file_id
                                await update_setting("welcome_banner_file_id", new_file_id)
                                logger.info(f"Welcome banner successfully uploaded and cached. File ID: {new_file_id}")
                                try:
                                    await bot.delete_message(chat_id=admin_id, message_id=sent_msg.message_id)
                                except Exception:
                                    pass
                                break
                        except Exception as ex:
                            logger.warning(f"Could not upload welcome banner to admin {admin_id}: {ex}")
        
        asyncio.create_task(init_welcome_banner())
    except Exception as e:
        logger.error(f"Error starting welcome banner initialization checker: {e}")
        
    asyncio.create_task(start_web_server(bot))
    
    # Start background task to check deadlines
    async def deadline_alert_worker():
        # Check immediately on startup (wait 5 seconds for bot setup)
        await asyncio.sleep(5)
        try:
            from utils.deadline_alerts import check_deadlines
            await check_deadlines(bot)
        except Exception as e:
            logger.error(f"Error in initial deadline alert check: {e}")
            
        while True:
            await asyncio.sleep(3600) # Check once every hour
            try:
                from utils.deadline_alerts import check_deadlines
                await check_deadlines(bot)
            except Exception as e:
                logger.error(f"Error in deadline alert worker: {e}")
                
    asyncio.create_task(deadline_alert_worker())
    
    dp = Dispatcher(storage=SQLiteStorage())
    
    dp.message.outer_middleware(AntiFloodMiddleware(time_limit=1.0))
    dp.callback_query.outer_middleware(AntiFloodMiddleware(time_limit=1.0))

    dp.message.outer_middleware(DbMiddleware())
    dp.callback_query.outer_middleware(DbMiddleware())

    # Order matters: common first (handles /start + back), then specific routers
    dp.include_router(common_router)
    dp.include_router(client_router)
    dp.include_router(freelancer_router)
    dp.include_router(admin_router)
    dp.include_router(inline_router)

    logger.info("🚀 Xlancer Bot is starting...")
    await dp.start_polling(bot, allowed_updates=["message", "callback_query", "inline_query", "poll_answer", "poll", "chat_join_request"])

if __name__ == "__main__":
    try:
        asyncio.run(main())
    except (KeyboardInterrupt, SystemExit):
        logger.info("Bot stopped.")
