import logging
import asyncio
import sys
import platform
from aiogram import Bot, Dispatcher
from dotenv import load_dotenv
import os
from handlers.user import router as user_router
from handlers.admin import router as admin_router
from database.base import init_db
from utils.pay_providers import get_available_providers
from utils.scheduler import setup_scheduler
from vpns.marz import marzban_service
from utils.media_cache import save_media_cache

# Configure logging with more detailed format
logging.basicConfig(
    format="%(asctime)s - %(name)s - %(levelname)s - %(message)s", 
    level=logging.INFO,
    handlers=[
        logging.StreamHandler(),
        logging.FileHandler("bot.log")
    ]
)
logger = logging.getLogger(__name__)

# Set specific log levels
logging.getLogger("aiogram").setLevel(logging.INFO)
logging.getLogger("utils").setLevel(logging.INFO)
logging.getLogger("vpns").setLevel(logging.INFO)
logging.getLogger("handlers").setLevel(logging.INFO)
logging.getLogger("payments").setLevel(logging.INFO)

load_dotenv()

def setup_event_loop():
    if sys.platform != 'win32' and platform.python_implementation() == 'CPython':
        try:
            import uvloop
            uvloop.install()
            logger.info("uvloop has been enabled")
        except ImportError:
            logger.warning("uvloop is not installed, using default event loop")
    else:
        logger.info("Running on Windows or non-CPython implementation, using default event loop")

async def main():
    # Initialize database
    await init_db()

    # Check creds of marzban
    try:
        token = await marzban_service._get_token()
        if token is None:
            logger.error("Invalid credentials for marzban")
            return
    except Exception as e:
        logger.error(f"Error checking marzban creds: {e}")
        return
    await marzban_service.get_countries()
    
    # Initialize bot and dispatcher
    bot = Bot(token=os.getenv("BOT_TOKEN"))
    bot_username = (await bot.get_me()).username
    await get_available_providers(bot_username)

    dp = Dispatcher()

    # Include routers
    dp.include_router(admin_router)
    dp.include_router(user_router)

    # Initialize scheduler
    scheduler = setup_scheduler(bot)
    scheduler.start()


    logger.info("Bot started")
    
    try:
        # Start polling
        await dp.start_polling(bot)
    finally:
        # Save media cache
        save_media_cache()
        logger.info("Bot stopped")

def entrypoint():
    setup_event_loop()
    asyncio.run(main())

if __name__ == "__main__":
    entrypoint()
