from fastapi import Request, status
from fastapi.exceptions import RequestValidationError
from fastapi.responses import JSONResponse
from core.exceptions import AppException
from core.logging import get_logger

logger = get_logger(__name__)


async def app_exception_handler(request: Request, exc: AppException) -> JSONResponse:
    logger.warning(
        "app_exception_handled",
        path=request.url.path,
        method=request.method,
        error_code=exc.error_code,
        message=exc.message,
    )
    return JSONResponse(
        status_code=exc.status_code,
        content={
            "success": False,
            "message": exc.message,
            "error": {
                "code": exc.error_code,
                "message": exc.message,
                "details": exc.details,
            },
        },
    )


async def validation_exception_handler(request: Request, exc: RequestValidationError) -> JSONResponse:
    raw_errors = exc.errors()
    sanitized_errors = []
    for err in raw_errors:
        err_copy = dict(err)
        if isinstance(err_copy.get("input"), bytes):
            err_copy["input"] = err_copy["input"].decode("utf-8", errors="replace")
        sanitized_errors.append(err_copy)

    first_msg = sanitized_errors[0]["msg"] if sanitized_errors else "Validation failed"
    return JSONResponse(
        status_code=status.HTTP_422_UNPROCESSABLE_ENTITY,
        content={
            "success": False,
            "message": f"Validation error: {first_msg}",
            "error": {
                "code": "VALIDATION_ERROR",
                "message": first_msg,
                "details": {"validation_errors": sanitized_errors},
            },
        },
    )


async def generic_exception_handler(request: Request, exc: Exception) -> JSONResponse:
    logger.error(
        "unhandled_server_error",
        path=request.url.path,
        method=request.method,
        error=str(exc),
        exc_info=True,
    )
    return JSONResponse(
        status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
        content={
            "success": False,
            "message": "An unexpected internal server error occurred",
            "error": {
                "code": "INTERNAL_SERVER_ERROR",
                "message": "An unexpected internal error occurred. Please contact support.",
            },
        },
    )
