from pathlib import Path
import sys; sys.path.extend([str(Path(__file__).parent / 'utils' / 'some_sdk')])

from contextlib import asynccontextmanager

from fastapi import FastAPI
from tortoise import Tortoise

from app.core.exceptions import SettingNotFound
from app.core.init_app import (
    init_data,
    tear_down,
    make_middlewares,
    register_exceptions,
    register_routers,
    mount_static_and_config_swagger
)

try:
    from app.settings.config import settings
except ImportError:
    raise SettingNotFound("Can not import settings")


@asynccontextmanager
async def lifespan(app: FastAPI):
    await init_data()
    yield
    await Tortoise.close_connections()
    await tear_down()


def create_app() -> FastAPI:
    app = FastAPI(
        title=settings.APP_TITLE,
        description=settings.APP_DESCRIPTION,
        version=settings.VERSION,
        openapi_url="/api/openapi.json",
        docs_url="/api/api-docs",
        middleware=make_middlewares(),
        lifespan=lifespan,
    )
    register_exceptions(app)
    register_routers(app, prefix="/api")
    mount_static_and_config_swagger(app)
    return app


app = create_app()
