import os
import logging
import asyncio

from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware

from .api import other, game
from .db import init_db
from .point_gen import aiohttp_client, points

logging.config.fileConfig('logging.conf', disable_existing_loggers=False)

app = FastAPI()

app.include_router(other)
app.include_router(game, prefix="/game")


app.add_middleware(
    CORSMiddleware,
    allow_origins=["http://localhost:3000", "https://kirkleon.ddns.net", "https://hiram.services"],
    allow_methods=["*"],
    allow_headers=["*"],
)


restocking_task = None


@app.on_event("startup")
def startup():
    init_db(os.environ.get("SQLALCHEMY_URL", "sqlite:////tmp/terrassumptions.db"), connect_args={"check_same_thread": False})
    restocking_task = asyncio.create_task(points.restock_all())


@app.on_event("shutdown")
async def shutdown_event():
    await aiohttp_client.close()
    if restocking_task is not None and not restocking_task.done():
        restocking_task.cancel()
