import asyncio
import contextlib
import logging
from logging import Logger
from os import getpid

from libbot.utils import config_get

# Import required for uvicorn
from api.app import app  # noqa
from classes.pycord_bot import PycordBot
from modules.extensions_loader import dynamic_import_from_src
from modules.scheduler import scheduler

logging.basicConfig(
    level=logging.DEBUG if config_get("debug") else logging.INFO,
    format="%(name)s.%(funcName)s | %(levelname)s | %(message)s",
    datefmt="[%X]",
)

logger: Logger = logging.getLogger(__name__)

# Try to import the module that improves performance
# and ignore errors when module is not installed
with contextlib.suppress(ImportError):
    import uvloop

    uvloop.install()


async def main():
    bot = PycordBot(scheduler=scheduler)

    bot.load_extension("cogs")

    # Import API modules
    dynamic_import_from_src("api/extensions", star_import=True)

    try:
        await bot.start(config_get("bot_token", "bot"))
    except KeyboardInterrupt:
        logger.warning("Forcefully shutting down with PID %s...", getpid())
        await bot.close()


asyncio.create_task(main())