import logging
from fastapi import FastAPI, HTTPException, Header, Request
from fastapi.exceptions import RequestValidationError
from fastapi.responses import JSONResponse
import uvicorn
import api.delivery as delivery_api
import api.routes as routes_api
import api.drivers as drivers_api
from starlette import status
from resources import strings

log: logging.Logger = logging.getLogger('development')
app: FastAPI = FastAPI(
    title = strings.TITLE[0],
    description = strings.DESCRIPTION,
    summary = strings.SUMMARY,
    version = strings.VERSION,
    contact = strings.CONTACT[0],
    license_info = strings.LICENSE_INFO[0],
)

app.include_router(delivery_api.router,
                   prefix="/deliveries", tags=['delivery'])
app.include_router(drivers_api.router, prefix="/driver", tags=['driver'])
app.include_router(routes_api.router, prefix="/route", tags=['route'])


def run_server(host: str = "127.0.0.1", port: int = 21000):
    uvicorn.run(app, host=host, port=port)


@app.get("/", responses={status.HTTP_401_UNAUTHORIZED:{"description":strings.GENERIC_PROHIBITED}})
def read_item():
    raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED,
                        detail=strings.GENERIC_PROHIBITED)

# Return status of the DB perhaps
@app.get("/healthcheck", responses={501:{"description":strings.GENERIC_NOT_IMPLEMENTED}})
def check():
    raise HTTPException(status_code=status.HTTP_501_NOT_IMPLEMENTED,
                        detail=strings.GENERIC_NOT_IMPLEMENTED)


@app.exception_handler(RequestValidationError)
async def validation_exception_handler(request: Request, exc: RequestValidationError):
    exc_str = f'{exc}'.replace('\n', ' ').replace('   ', ' ')
    logging.error(f"{request}: {exc_str}")
    content = {'status_code': status.HTTP_422_UNPROCESSABLE_ENTITY,
               'message': strings.GENERIC_INVALID_DATA_ERROR, 'data': None}
    return JSONResponse(content=content, status_code=status.HTTP_422_UNPROCESSABLE_ENTITY)
