from logging.config import dictConfig

from fastapi import FastAPI
from fastapi.responses import JSONResponse
from fastapi.routing import APIRoute

from intranet.trip.ext_api.src import middlewares
from intranet.trip.ext_api.src.config import settings
from intranet.trip.ext_api.src.logging import LOGGING_CONFIG
from intranet.trip.ext_api.src.router import api_router
from intranet.trip.ext_api.src.lib.trip.exceptions import TripError


dictConfig(LOGGING_CONFIG)


def generate_operation_ids(app):
    for route in app.routes:
        if isinstance(route, APIRoute):
            route.operation_id = route.name


def bind_middlewares(app):
    app.middleware('http')(middlewares.authentication)


def get_app():
    app = FastAPI(
        title='trip',
        openapi_url='/api/openapi.json',
        docs_url='/api/docs',
        redoc_url='/api/redoc',
    )
    app.include_router(api_router)
    generate_operation_ids(app)

    bind_middlewares(app)

    async def unhandled_exception_handler(request, exc):
        message = str(exc.content) if settings.ENV_TYPE != 'production' else 'Unhandled exception'
        return JSONResponse(
            status_code=exc.status_code,
            content={'detail': message},
        )

    app.exception_handler(TripError)(unhandled_exception_handler)
    return app


app = get_app()
