import logging

from fastapi import FastAPI, HTTPException, Request, status
from fastapi.exceptions import RequestValidationError
from fastapi.responses import JSONResponse

from app.core.config import get_settings
from app.core.logging import configure_logging
from app.routers import encuesta, events, health, install, mbia, webhook, workflow
from app.services.conversation_builder import controlled_error

configure_logging()
logger = logging.getLogger(__name__)
settings = get_settings()

app = FastAPI(
    title=settings.app_name,
    version="1.0.0",
    description="API conversacional para Freshchat/Freshworks Automations.",
)


@app.exception_handler(HTTPException)
async def http_exception_handler(request: Request, exc: HTTPException) -> JSONResponse:
    message = exc.detail if isinstance(exc.detail, str) else "Error HTTP."
    return JSONResponse(
        status_code=exc.status_code,
        content=controlled_error(message),
    )


@app.exception_handler(RequestValidationError)
async def validation_exception_handler(request: Request, exc: RequestValidationError) -> JSONResponse:
    validation_errors = [
        {
            "loc": error.get("loc"),
            "msg": error.get("msg"),
            "type": error.get("type"),
        }
        for error in exc.errors()
    ]
    return JSONResponse(
        status_code=status.HTTP_422_UNPROCESSABLE_ENTITY,
        content={
            **controlled_error("El JSON enviado no cumple con el esquema requerido."),
            "validation_errors": validation_errors,
        },
    )


@app.exception_handler(Exception)
async def unhandled_exception_handler(request: Request, exc: Exception) -> JSONResponse:
    logger.exception("Unhandled error on %s %s", request.method, request.url.path)
    return JSONResponse(
        status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
        content=controlled_error("Ocurrió un error técnico al procesar la solicitud."),
    )


app.include_router(health.router)
app.include_router(install.router)
app.include_router(workflow.router)
app.include_router(workflow.render_router)
app.include_router(mbia.router)
app.include_router(encuesta.router)
app.include_router(events.router)
app.include_router(webhook.router)
