# main.py
from fastapi import FastAPI, Request
from fastapi.middleware.cors import CORSMiddleware
from fastapi.responses import JSONResponse
import logging

from app.core.config import Settings
from app.api.v1 import get_routers
from app.core.logger_config import setup_logger
from app.exceptions import DomainError
from app.exceptions.http_map import DOMAIN_TO_HTTP

# Configurar logging
logging.basicConfig(level=logging.INFO)
logger = setup_logger()
settings = Settings()


def create_app() -> FastAPI:
    app = FastAPI(
        title=settings.APP_TITLE,
        description=settings.APP_DESCRIPTION,
        version=settings.APP_VERSION,
    )

    # Configuración CORS
    app.add_middleware(
        CORSMiddleware,
        allow_origins=[settings.ALLOW_ORIGINS],
        allow_credentials=True,
        allow_methods=["*"],
        allow_headers=["*"],
    )

    # ── Handlers globales ──────────────────────────────────────────────────────
    @app.exception_handler(DomainError)
    async def domain_error_handler(request: Request, exc: DomainError):
        logger.debug(f"[{type(exc).__name__}] {request.url}: {exc.message}")
        return JSONResponse(
            status_code=DOMAIN_TO_HTTP.get(type(exc), 400),
            content={"success": False, "message": exc.message, "data": exc.data},
        )

    @app.exception_handler(Exception)
    async def unhandled_exception_handler(request: Request, exc: Exception):
        logger.exception(f"Error inesperado en {request.url}: {str(exc)}")
        return JSONResponse(
            status_code=500,
            content={"success": False, "message": "Ocurrió un error interno", "data": None},
        )
    # ──────────────────────────────────────────────────────────────────────────

    @app.get('/')
    def initial():
        return "Hello World!"

    for router in get_routers():
        app.include_router(router, prefix="/v1")
        logger.info(f"Router cargado: {router.prefix}")

    return app


app = create_app()

if __name__ == "__main__":
    import uvicorn
    uvicorn.run(settings.NAME_APP, host=settings.HOSTING, port=settings.PORT, reload=settings.RELOAD)
