import os
from pathlib import Path

from fastapi import FastAPI, HTTPException
from fastapi.exceptions import RequestValidationError
from fastapi.middleware.cors import CORSMiddleware
from fastapi.staticfiles import StaticFiles

from src.core.config import settings
from src.core.exceptions import APIException, APIErrorHandler, HttpErrorHandler, ValidationErrorHandler
from src.utils.io import create_uploads_directory

app: FastAPI = FastAPI(
    title=settings.APP_TITLE,
    description=settings.APP_DESCRIPTION,
    version=settings.APP_VERSION,
    debug=settings.DEBUG,
)

# Register Exception Handlers
app.add_exception_handler(APIException, APIErrorHandler)
app.add_exception_handler(HTTPException, HttpErrorHandler)
app.add_exception_handler(RequestValidationError, ValidationErrorHandler)

origins = settings.CORS_ORIGINS.split(",")

# MIDDLEWARES
app.add_middleware(
    CORSMiddleware,
    allow_origins=origins,
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)

# Register all routers via the single combined router
from src.core.router import include_routers

include_routers(app)


### APP EVENTS
@app.on_event("startup")
async def startup():
    """
    Anything that needs to be done while app starts
    """
    print("*******API STARTED*******")


@app.on_event("shutdown")
async def on_app_shutdown():
    """
    Anything that needs to be done while app shutdown
    """
    print("*******API CLOSED*******")


create_uploads_directory()
project_root = Path(os.getcwd())
project_root_absolute = project_root.resolve()

# Handle UPLOADS_DIR path regardless of whether it has a leading slash or not
uploads_path_parts = settings.UPLOADS_DIR.strip("/").split("/")
static_root_absolute = project_root_absolute / uploads_path_parts[0]

app.mount(
    settings.STATIC_FILES_PATH,
    StaticFiles(directory=static_root_absolute),
    name="uploads",
)