from rest_framework.response import Response
from rest_framework.views import exception_handler


def custom_exception_handler(exc, context):
    """Wrap DRF errors in the standard envelope; map MCP outage to 503."""
    from apps.authentication.mcp_client import MCPServiceError

    if isinstance(exc, MCPServiceError):
        return Response(
            {"success": False, "message": "MFA service unavailable. Try again later.", "errors": None},
            status=503,
        )

    response = exception_handler(exc, context)
    if response is not None:
        detail = response.data
        message = "Request failed"

        if isinstance(detail, dict):
            if "detail" in detail:
                message = str(detail["detail"])
            else:
                first_msgs = []
                for field, msgs in detail.items():
                    if isinstance(msgs, list) and msgs:
                        first_msgs.append(str(msgs[0]))
                    elif isinstance(msgs, str):
                        first_msgs.append(msgs)
                if first_msgs:
                    message = first_msgs[0]
        elif isinstance(detail, list) and detail:
            message = str(detail[0])

        response.data = {"success": False, "message": str(message), "errors": detail}
    return response
