import uvicorn
import routers

from fastapi.middleware.cors import CORSMiddleware
from fastapi import Request, HTTPException, status
from fastapi.responses import JSONResponse

from api_objects.errors.errorMessages import EXCEPTION_DICTS, ERRORS_DICT, ERRORS_LANG
from api_objects.errors.errorHandlers import (
    HTTPExceptionEvyos,
    HTTPExceptionAnyHandler,
    HTTPExceptionEvyosHandler,
)

from middlewares.token_middleware import AuthHeaderMiddleware
from application.create_file import create_app
from prometheus_fastapi_instrumentator import Instrumentator

app = create_app(routers=routers)
Instrumentator().instrument(app=app).expose(app=app)

app.add_middleware(
    CORSMiddleware,
    **{
        "allow_origins": ["*"],
        "allow_credentials": True,
        "allow_methods": ["*"],
        "allow_headers": ["*"],
    },
)
app.add_middleware(AuthHeaderMiddleware)

# Initialize Exception and ExceptionInstance handlers
CustomExceptionHandler = HTTPExceptionEvyosHandler(
    **dict(
        statuses=status,
        exceptions=HTTPException,
        response_model=JSONResponse,
        exceptions_dict=EXCEPTION_DICTS,
        errors_dict=ERRORS_DICT,
        error_language_dict=ERRORS_LANG,
    )
)
CustomExceptionAnyHandler = HTTPExceptionAnyHandler(response_model=JSONResponse)

# Register error handlers with bound methods
app.add_exception_handler(HTTPExceptionEvyos, CustomExceptionHandler.handle_exception)
app.add_exception_handler(Exception, CustomExceptionAnyHandler.any_exception_handler)

if __name__ == "__main__":
    uvicorn_config = {
        "app": "app:app",
        "host": "0.0.0.0",
        "port": 41575,
        "log_level": "info",
        "reload": True,
    }
    uvicorn.Server(uvicorn.Config(**uvicorn_config)).run()
