from rest_framework.views import exception_handler


def api_exception_handler(exc, context):
    """
    Normalises DRF error responses to `{"error": "<message>"}`, matching the
    shape the existing clients expect (they read `result.error`).
    """
    response = exception_handler(exc, context)
    if response is None:
        return None

    data = response.data
    message = None

    if isinstance(data, dict):
        if 'detail' in data:
            message = str(data['detail'])
        else:
            # Surface the first field error, prefixed with the field name.
            for field, value in data.items():
                if isinstance(value, (list, tuple)) and value:
                    message = f'{field}: {value[0]}' if field != 'non_field_errors' \
                        else str(value[0])
                else:
                    message = str(value)
                break
    elif isinstance(data, list) and data:
        message = str(data[0])

    response.data = {'error': message or 'Request failed'}
    return response
