
import os
from fastapi import FastAPI, APIRouter, Depends, HTTPException, Request
from fastapi.middleware.cors import CORSMiddleware
from fastapi.exceptions import RequestValidationError
from fastapi.responses import JSONResponse
from dotenv import load_dotenv
from routers.auth import router as auth_router
from routers.folders import router as folder_router
# from routers.documents import router as document_router
from routers.chromadoc import router as document_router
from routers.search import router as search_router

load_dotenv()
app = FastAPI()

allow_origins=[os.getenv("FRONT_APP_URL")]
# Add CORS middleware
app.add_middleware(
    CORSMiddleware,
    allow_origins=["*"],  # Replace with your frontend URL
    allow_credentials=True,
    allow_methods=["*"],  # Allows all methods like GET, POST, PUT, etc.
    allow_headers=["*"],  # Allows all headers
)

# Custom validation error handler
@app.exception_handler(RequestValidationError)
async def custom_validation_exception_handler(request: Request, exc: RequestValidationError):
    errors = [
        {
            "field": ".".join(str(loc) for loc in error["loc"]),
            "message": error["msg"],
            "type": error["type"],
        }
        for error in exc.errors()
    ]
    
    return JSONResponse(
        status_code=400,
        content={
            "status": 400,
            "message": errors[0]['message'],
            "field": errors[0]['field']
        },
    )

@app.exception_handler(HTTPException)
async def custom_http_exception_handler(request, exc: HTTPException):
    if exc.status_code == 403 and exc.detail == "Not authenticated":
        return JSONResponse(
            status_code=401,
            content={"status": 401, "message": "Missing API Token"},
        )
    return JSONResponse(
        status_code=exc.status_code,
        content={"status": exc.status_code, "message": exc.detail}
    )

app.include_router(auth_router, prefix="/users")
app.include_router(folder_router, prefix="/folders")
app.include_router(document_router, prefix="/documents")
app.include_router(search_router, prefix="/search")