from rest_framework.views import exception_handler
from rest_framework.exceptions import APIException, NotAuthenticated, AuthenticationFailed, PermissionDenied
from rest_framework.response import Response
from rest_framework import status

def format_error_response(code, message, fields=None, status_code=status.HTTP_400_BAD_REQUEST):
    return Response({
        "error": {
            "code": code,
            "message": message,
            "fields": fields or {}
        }
    }, status=status_code)

def custom_exception_handler(exc, context):
    response = exception_handler(exc, context)

    if response is not None:
        code = getattr(exc, 'default_code', 'error')
        message = str(exc.detail) if hasattr(exc, 'detail') and isinstance(exc.detail, (str, bytes)) else 'An error occurred.'
        fields = {}

        if isinstance(response.data, dict):
            # Check for standard rest_framework structure or field errors
            if 'detail' in response.data:
                message = str(response.data['detail'])
                if hasattr(exc, 'get_codes'):
                    codes = exc.get_codes()
                    if isinstance(codes, str):
                        code = codes
                    elif isinstance(codes, dict) and 'detail' in codes:
                        code = str(codes['detail'])
            else:
                code = 'validation_error'
                message = 'Validation failed.'
                for k, v in response.data.items():
                    if isinstance(v, list) and v:
                        fields[k] = str(v[0])
                    else:
                        fields[k] = str(v)

        elif isinstance(response.data, list):
            code = 'validation_error'
            message = str(response.data[0]) if response.data else 'Validation error.'

        if isinstance(exc, (NotAuthenticated, AuthenticationFailed)):
            code = 'not_authenticated'
        elif isinstance(exc, PermissionDenied):
            if not getattr(exc, 'custom_code', None):
                code = 'permission_denied'
            else:
                code = exc.custom_code

        response.data = {
            "error": {
                "code": getattr(exc, 'custom_code', code),
                "message": getattr(exc, 'custom_message', message),
                "fields": fields
            }
        }
        return response

    return None
