import asyncio
import logging

from tenacity import after_log, before_log, retry, stop_after_attempt, wait_fixed
from tortoise import Tortoise

from service.config import TORTOISE_ORM
from service.utils.logging import init_logging

init_logging()
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger("service")

max_tries = 2  # 25 * 1  # 5 minutes
wait_seconds = 5


@retry(
    stop=stop_after_attempt(max_tries),
    wait=wait_fixed(wait_seconds),
    before=before_log(logger, logging.INFO),
    after=after_log(logger, logging.WARN),
)
async def init() -> None:
    try:
        await Tortoise.init(TORTOISE_ORM)
    except Exception as e:
        logger.error(e)
        raise e


@retry(
    stop=stop_after_attempt(max_tries),
    wait=wait_fixed(wait_seconds),
    before=before_log(logger, logging.INFO),
    after=after_log(logger, logging.WARN),
)
async def init_db() -> None:
    try:
        await Tortoise.init(TORTOISE_ORM)
    except Exception as e:
        logger.exception(e)
        raise e


def main() -> None:
    logger.info("Initializing service")
    loop = asyncio.get_event_loop()
    loop.run_until_complete(init_db())
    logger.info("Service finished initializing")


if __name__ == "__main__":
    main()
