# coding: utf-8

"""
    Webui restAPI

    The purpose of the API is to use, monitor and maintain our Charger over the Websolution. Conventions:  - All values use SI units. - All ids are natural numbers 

    The version of the OpenAPI document: 1.0.0
    Generated by: https://openapi-generator.tech
"""
import os
import logging
from datetime import datetime
from pathlib import Path

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

from server.apis.account_management_api import router as AccountManagementApiRouter
from server.apis.action_api import router as ActionApiRouter
from server.apis.authentication_api import router as AuthenticationApiRouter
from server.apis.base_config_api import router as BaseConfigHandlingApiRouter
from server.apis.certificates_api import router as CertificatesApiRouter
from server.apis.config_api import router as ConfigHandlingApiRouter
from server.apis.custom_graphics_api import router as CustomGraphicsHandlingApiRouter
from server.apis.ipk_api import router as IpkApiRouter
from server.apis.info_api import router as InfoApiRouter
from server.apis.logs_api import router as LogsApiRouter
from server.apis.promotion_screen_api import router as PromotionScreenHandlingApiRouter
from server.apis.rauc_api import router as RaucApiRouter
from server.apis.tokens_api import router as TokensApiRouter
from server.apis import sqliteClient
from server.utils.app_data import setup_app_data
from server.utils.password import applyCredentialUpgrades
from server.data.definitions import MIGRATION_DIR

logger = logging.getLogger("webui.startup")

APPLICATION_NAME = "Webui RESTful API"

app = FastAPI(
    title=APPLICATION_NAME,
    description="The purpose of the API is to use, monitor and maintain our Charger over the Websolution. Conventions:  - All values use SI units. - All ids are natural numbers ",
    version="1.0.15",
)
app.add_middleware(CorrelationIdMiddleware)
app.add_middleware(
    CORSMiddleware,
    allow_origins=["*"],
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
    expose_headers=["Content-Disposition"],
)


app.include_router(AccountManagementApiRouter)
app.include_router(ActionApiRouter)
app.include_router(AuthenticationApiRouter)
app.include_router(BaseConfigHandlingApiRouter)
app.include_router(CertificatesApiRouter)
app.include_router(ConfigHandlingApiRouter)
app.include_router(CustomGraphicsHandlingApiRouter)
app.include_router(InfoApiRouter)
app.include_router(IpkApiRouter)
app.include_router(LogsApiRouter)
app.include_router(PromotionScreenHandlingApiRouter)
app.include_router(RaucApiRouter)
app.include_router(TokensApiRouter)


@app.on_event("startup")
async def app_startup() -> None:
    """Handles app startup."""
    logger.info("=" * 72)
    logger.info(f"{APPLICATION_NAME} starting")
    logger.info(f"{datetime.now().strftime('%Y-%m-%d %H:%M:%S')}")
    logger.info("=" * 72)

    await setup_app_data()
    # use environ var for now to define migration folder
    migrationDir = os.environ.get(MIGRATION_DIR)
    migrationPath = Path(migrationDir) if migrationDir else None
    await sqliteClient.applyMigrations(migrationsPath=migrationPath)

    # apply credential upgrade
    await sqliteClient.withConnection(applyCredentialUpgrades)

    sqliteClient.startLoadTablesTask()
    await sqliteClient.loadTablesTask
