# This file was auto-generated by Fern from our API Definition.

import contextlib
import json
import typing
from json.decoder import JSONDecodeError
from logging import warning

from ..core.api_error import ApiError
from ..core.client_wrapper import AsyncClientWrapper, SyncClientWrapper
from ..core.http_response import AsyncHttpResponse, HttpResponse
from ..core.http_sse._api import EventSource
from ..core.parse_error import ParsingError
from ..core.pydantic_utilities import parse_obj_as
from ..core.request_options import RequestOptions
from ..errors.bad_request_error import BadRequestError
from ..errors.forbidden_error import ForbiddenError
from ..errors.gone_error import GoneError
from ..errors.not_found_error import NotFoundError
from ..errors.too_many_requests_error import TooManyRequestsError
from ..errors.unauthorized_error import UnauthorizedError
from ..types.event_stream_cloud_event_connection_created import EventStreamCloudEventConnectionCreated
from ..types.event_stream_cloud_event_connection_deleted import EventStreamCloudEventConnectionDeleted
from ..types.event_stream_cloud_event_connection_updated import EventStreamCloudEventConnectionUpdated
from ..types.event_stream_cloud_event_error_message import EventStreamCloudEventErrorMessage
from ..types.event_stream_cloud_event_group_created import EventStreamCloudEventGroupCreated
from ..types.event_stream_cloud_event_group_deleted import EventStreamCloudEventGroupDeleted
from ..types.event_stream_cloud_event_group_member_added import EventStreamCloudEventGroupMemberAdded
from ..types.event_stream_cloud_event_group_member_deleted import EventStreamCloudEventGroupMemberDeleted
from ..types.event_stream_cloud_event_group_role_assigned import EventStreamCloudEventGroupRoleAssigned
from ..types.event_stream_cloud_event_group_role_deleted import EventStreamCloudEventGroupRoleDeleted
from ..types.event_stream_cloud_event_group_updated import EventStreamCloudEventGroupUpdated
from ..types.event_stream_cloud_event_offset_only_message import EventStreamCloudEventOffsetOnlyMessage
from ..types.event_stream_cloud_event_org_connection_added import EventStreamCloudEventOrgConnectionAdded
from ..types.event_stream_cloud_event_org_connection_removed import EventStreamCloudEventOrgConnectionRemoved
from ..types.event_stream_cloud_event_org_connection_updated import EventStreamCloudEventOrgConnectionUpdated
from ..types.event_stream_cloud_event_org_created import EventStreamCloudEventOrgCreated
from ..types.event_stream_cloud_event_org_deleted import EventStreamCloudEventOrgDeleted
from ..types.event_stream_cloud_event_org_group_role_assigned import EventStreamCloudEventOrgGroupRoleAssigned
from ..types.event_stream_cloud_event_org_group_role_deleted import EventStreamCloudEventOrgGroupRoleDeleted
from ..types.event_stream_cloud_event_org_member_added import EventStreamCloudEventOrgMemberAdded
from ..types.event_stream_cloud_event_org_member_deleted import EventStreamCloudEventOrgMemberDeleted
from ..types.event_stream_cloud_event_org_member_role_assigned import EventStreamCloudEventOrgMemberRoleAssigned
from ..types.event_stream_cloud_event_org_member_role_deleted import EventStreamCloudEventOrgMemberRoleDeleted
from ..types.event_stream_cloud_event_org_updated import EventStreamCloudEventOrgUpdated
from ..types.event_stream_cloud_event_user_created import EventStreamCloudEventUserCreated
from ..types.event_stream_cloud_event_user_deleted import EventStreamCloudEventUserDeleted
from ..types.event_stream_cloud_event_user_updated import EventStreamCloudEventUserUpdated
from ..types.event_stream_subscribe_events_event_type_enum import EventStreamSubscribeEventsEventTypeEnum
from ..types.event_stream_subscribe_events_response_content import EventStreamSubscribeEventsResponseContent
from pydantic import ValidationError


class RawEventsClient:
    def __init__(self, *, client_wrapper: SyncClientWrapper):
        self._client_wrapper = client_wrapper

    @contextlib.contextmanager
    def subscribe(
        self,
        *,
        from_: typing.Optional[str] = None,
        from_timestamp: typing.Optional[str] = None,
        event_type: typing.Optional[
            typing.Union[
                EventStreamSubscribeEventsEventTypeEnum, typing.Sequence[EventStreamSubscribeEventsEventTypeEnum]
            ]
        ] = None,
        request_options: typing.Optional[RequestOptions] = None,
    ) -> typing.Iterator[HttpResponse[typing.Iterator[EventStreamSubscribeEventsResponseContent]]]:
        """
        Subscribe to events via Server-Sent Events (SSE)

        Parameters
        ----------
        from_ : typing.Optional[str]
            Opaque token representing position in the stream. If not provided, stream will start from the latest events.

        from_timestamp : typing.Optional[str]
            RFC-3339 timestamp indicating where to start streaming events from. This should only be used on the initial query when a cursor may not be available. Subsequent requests should use the cursor (from) as it will be more accurate.

        event_type : typing.Optional[typing.Union[EventStreamSubscribeEventsEventTypeEnum, typing.Sequence[EventStreamSubscribeEventsEventTypeEnum]]]
            Event type(s) to listen for. Specify multiple times for multiple types (e.g., ?event_type=user.created&event_type=user.updated). If not provided, all event types will be streamed.

        request_options : typing.Optional[RequestOptions]
            Request-specific configuration.

        Yields
        ------
        typing.Iterator[HttpResponse[typing.Iterator[EventStreamSubscribeEventsResponseContent]]]
            Event stream successfully established.
        """
        with self._client_wrapper.httpx_client.stream(
            "events",
            method="GET",
            params={
                "from": from_,
                "from_timestamp": from_timestamp,
                "event_type": event_type,
            },
            request_options=request_options,
        ) as _response:

            def _stream() -> HttpResponse[typing.Iterator[EventStreamSubscribeEventsResponseContent]]:
                try:
                    if 200 <= _response.status_code < 300:

                        def _iter():
                            _event_source = EventSource(_response)
                            for _sse in _event_source.iter_sse():
                                if _sse.data == None:
                                    return
                                if _sse.event == "connection.created":
                                    try:
                                        yield typing.cast(
                                            EventStreamCloudEventConnectionCreated,
                                            parse_obj_as(
                                                type_=EventStreamCloudEventConnectionCreated,  # type: ignore
                                                object_=json.loads(_sse.data),
                                            ),
                                        )
                                    except Exception as e:
                                        warning(f"Failed to parse SSE event 'connection.created': {e}, sse: {_sse!r}")
                                elif _sse.event == "connection.deleted":
                                    try:
                                        yield typing.cast(
                                            EventStreamCloudEventConnectionDeleted,
                                            parse_obj_as(
                                                type_=EventStreamCloudEventConnectionDeleted,  # type: ignore
                                                object_=json.loads(_sse.data),
                                            ),
                                        )
                                    except Exception as e:
                                        warning(f"Failed to parse SSE event 'connection.deleted': {e}, sse: {_sse!r}")
                                elif _sse.event == "connection.updated":
                                    try:
                                        yield typing.cast(
                                            EventStreamCloudEventConnectionUpdated,
                                            parse_obj_as(
                                                type_=EventStreamCloudEventConnectionUpdated,  # type: ignore
                                                object_=json.loads(_sse.data),
                                            ),
                                        )
                                    except Exception as e:
                                        warning(f"Failed to parse SSE event 'connection.updated': {e}, sse: {_sse!r}")
                                elif _sse.event == "group.created":
                                    try:
                                        yield typing.cast(
                                            EventStreamCloudEventGroupCreated,
                                            parse_obj_as(
                                                type_=EventStreamCloudEventGroupCreated,  # type: ignore
                                                object_=json.loads(_sse.data),
                                            ),
                                        )
                                    except Exception as e:
                                        warning(f"Failed to parse SSE event 'group.created': {e}, sse: {_sse!r}")
                                elif _sse.event == "group.deleted":
                                    try:
                                        yield typing.cast(
                                            EventStreamCloudEventGroupDeleted,
                                            parse_obj_as(
                                                type_=EventStreamCloudEventGroupDeleted,  # type: ignore
                                                object_=json.loads(_sse.data),
                                            ),
                                        )
                                    except Exception as e:
                                        warning(f"Failed to parse SSE event 'group.deleted': {e}, sse: {_sse!r}")
                                elif _sse.event == "group.member.added":
                                    try:
                                        yield typing.cast(
                                            EventStreamCloudEventGroupMemberAdded,
                                            parse_obj_as(
                                                type_=EventStreamCloudEventGroupMemberAdded,  # type: ignore
                                                object_=json.loads(_sse.data),
                                            ),
                                        )
                                    except Exception as e:
                                        warning(f"Failed to parse SSE event 'group.member.added': {e}, sse: {_sse!r}")
                                elif _sse.event == "group.member.deleted":
                                    try:
                                        yield typing.cast(
                                            EventStreamCloudEventGroupMemberDeleted,
                                            parse_obj_as(
                                                type_=EventStreamCloudEventGroupMemberDeleted,  # type: ignore
                                                object_=json.loads(_sse.data),
                                            ),
                                        )
                                    except Exception as e:
                                        warning(f"Failed to parse SSE event 'group.member.deleted': {e}, sse: {_sse!r}")
                                elif _sse.event == "group.role.assigned":
                                    try:
                                        yield typing.cast(
                                            EventStreamCloudEventGroupRoleAssigned,
                                            parse_obj_as(
                                                type_=EventStreamCloudEventGroupRoleAssigned,  # type: ignore
                                                object_=json.loads(_sse.data),
                                            ),
                                        )
                                    except Exception as e:
                                        warning(f"Failed to parse SSE event 'group.role.assigned': {e}, sse: {_sse!r}")
                                elif _sse.event == "group.role.deleted":
                                    try:
                                        yield typing.cast(
                                            EventStreamCloudEventGroupRoleDeleted,
                                            parse_obj_as(
                                                type_=EventStreamCloudEventGroupRoleDeleted,  # type: ignore
                                                object_=json.loads(_sse.data),
                                            ),
                                        )
                                    except Exception as e:
                                        warning(f"Failed to parse SSE event 'group.role.deleted': {e}, sse: {_sse!r}")
                                elif _sse.event == "group.updated":
                                    try:
                                        yield typing.cast(
                                            EventStreamCloudEventGroupUpdated,
                                            parse_obj_as(
                                                type_=EventStreamCloudEventGroupUpdated,  # type: ignore
                                                object_=json.loads(_sse.data),
                                            ),
                                        )
                                    except Exception as e:
                                        warning(f"Failed to parse SSE event 'group.updated': {e}, sse: {_sse!r}")
                                elif _sse.event == "organization.connection.added":
                                    try:
                                        yield typing.cast(
                                            EventStreamCloudEventOrgConnectionAdded,
                                            parse_obj_as(
                                                type_=EventStreamCloudEventOrgConnectionAdded,  # type: ignore
                                                object_=json.loads(_sse.data),
                                            ),
                                        )
                                    except Exception as e:
                                        warning(
                                            f"Failed to parse SSE event 'organization.connection.added': {e}, sse: {_sse!r}"
                                        )
                                elif _sse.event == "organization.connection.removed":
                                    try:
                                        yield typing.cast(
                                            EventStreamCloudEventOrgConnectionRemoved,
                                            parse_obj_as(
                                                type_=EventStreamCloudEventOrgConnectionRemoved,  # type: ignore
                                                object_=json.loads(_sse.data),
                                            ),
                                        )
                                    except Exception as e:
                                        warning(
                                            f"Failed to parse SSE event 'organization.connection.removed': {e}, sse: {_sse!r}"
                                        )
                                elif _sse.event == "organization.connection.updated":
                                    try:
                                        yield typing.cast(
                                            EventStreamCloudEventOrgConnectionUpdated,
                                            parse_obj_as(
                                                type_=EventStreamCloudEventOrgConnectionUpdated,  # type: ignore
                                                object_=json.loads(_sse.data),
                                            ),
                                        )
                                    except Exception as e:
                                        warning(
                                            f"Failed to parse SSE event 'organization.connection.updated': {e}, sse: {_sse!r}"
                                        )
                                elif _sse.event == "organization.created":
                                    try:
                                        yield typing.cast(
                                            EventStreamCloudEventOrgCreated,
                                            parse_obj_as(
                                                type_=EventStreamCloudEventOrgCreated,  # type: ignore
                                                object_=json.loads(_sse.data),
                                            ),
                                        )
                                    except Exception as e:
                                        warning(f"Failed to parse SSE event 'organization.created': {e}, sse: {_sse!r}")
                                elif _sse.event == "organization.deleted":
                                    try:
                                        yield typing.cast(
                                            EventStreamCloudEventOrgDeleted,
                                            parse_obj_as(
                                                type_=EventStreamCloudEventOrgDeleted,  # type: ignore
                                                object_=json.loads(_sse.data),
                                            ),
                                        )
                                    except Exception as e:
                                        warning(f"Failed to parse SSE event 'organization.deleted': {e}, sse: {_sse!r}")
                                elif _sse.event == "organization.group.role.assigned":
                                    try:
                                        yield typing.cast(
                                            EventStreamCloudEventOrgGroupRoleAssigned,
                                            parse_obj_as(
                                                type_=EventStreamCloudEventOrgGroupRoleAssigned,  # type: ignore
                                                object_=json.loads(_sse.data),
                                            ),
                                        )
                                    except Exception as e:
                                        warning(
                                            f"Failed to parse SSE event 'organization.group.role.assigned': {e}, sse: {_sse!r}"
                                        )
                                elif _sse.event == "organization.group.role.deleted":
                                    try:
                                        yield typing.cast(
                                            EventStreamCloudEventOrgGroupRoleDeleted,
                                            parse_obj_as(
                                                type_=EventStreamCloudEventOrgGroupRoleDeleted,  # type: ignore
                                                object_=json.loads(_sse.data),
                                            ),
                                        )
                                    except Exception as e:
                                        warning(
                                            f"Failed to parse SSE event 'organization.group.role.deleted': {e}, sse: {_sse!r}"
                                        )
                                elif _sse.event == "organization.member.added":
                                    try:
                                        yield typing.cast(
                                            EventStreamCloudEventOrgMemberAdded,
                                            parse_obj_as(
                                                type_=EventStreamCloudEventOrgMemberAdded,  # type: ignore
                                                object_=json.loads(_sse.data),
                                            ),
                                        )
                                    except Exception as e:
                                        warning(
                                            f"Failed to parse SSE event 'organization.member.added': {e}, sse: {_sse!r}"
                                        )
                                elif _sse.event == "organization.member.deleted":
                                    try:
                                        yield typing.cast(
                                            EventStreamCloudEventOrgMemberDeleted,
                                            parse_obj_as(
                                                type_=EventStreamCloudEventOrgMemberDeleted,  # type: ignore
                                                object_=json.loads(_sse.data),
                                            ),
                                        )
                                    except Exception as e:
                                        warning(
                                            f"Failed to parse SSE event 'organization.member.deleted': {e}, sse: {_sse!r}"
                                        )
                                elif _sse.event == "organization.member.role.assigned":
                                    try:
                                        yield typing.cast(
                                            EventStreamCloudEventOrgMemberRoleAssigned,
                                            parse_obj_as(
                                                type_=EventStreamCloudEventOrgMemberRoleAssigned,  # type: ignore
                                                object_=json.loads(_sse.data),
                                            ),
                                        )
                                    except Exception as e:
                                        warning(
                                            f"Failed to parse SSE event 'organization.member.role.assigned': {e}, sse: {_sse!r}"
                                        )
                                elif _sse.event == "organization.member.role.deleted":
                                    try:
                                        yield typing.cast(
                                            EventStreamCloudEventOrgMemberRoleDeleted,
                                            parse_obj_as(
                                                type_=EventStreamCloudEventOrgMemberRoleDeleted,  # type: ignore
                                                object_=json.loads(_sse.data),
                                            ),
                                        )
                                    except Exception as e:
                                        warning(
                                            f"Failed to parse SSE event 'organization.member.role.deleted': {e}, sse: {_sse!r}"
                                        )
                                elif _sse.event == "organization.updated":
                                    try:
                                        yield typing.cast(
                                            EventStreamCloudEventOrgUpdated,
                                            parse_obj_as(
                                                type_=EventStreamCloudEventOrgUpdated,  # type: ignore
                                                object_=json.loads(_sse.data),
                                            ),
                                        )
                                    except Exception as e:
                                        warning(f"Failed to parse SSE event 'organization.updated': {e}, sse: {_sse!r}")
                                elif _sse.event == "user.created":
                                    try:
                                        yield typing.cast(
                                            EventStreamCloudEventUserCreated,
                                            parse_obj_as(
                                                type_=EventStreamCloudEventUserCreated,  # type: ignore
                                                object_=json.loads(_sse.data),
                                            ),
                                        )
                                    except Exception as e:
                                        warning(f"Failed to parse SSE event 'user.created': {e}, sse: {_sse!r}")
                                elif _sse.event == "user.deleted":
                                    try:
                                        yield typing.cast(
                                            EventStreamCloudEventUserDeleted,
                                            parse_obj_as(
                                                type_=EventStreamCloudEventUserDeleted,  # type: ignore
                                                object_=json.loads(_sse.data),
                                            ),
                                        )
                                    except Exception as e:
                                        warning(f"Failed to parse SSE event 'user.deleted': {e}, sse: {_sse!r}")
                                elif _sse.event == "user.updated":
                                    try:
                                        yield typing.cast(
                                            EventStreamCloudEventUserUpdated,
                                            parse_obj_as(
                                                type_=EventStreamCloudEventUserUpdated,  # type: ignore
                                                object_=json.loads(_sse.data),
                                            ),
                                        )
                                    except Exception as e:
                                        warning(f"Failed to parse SSE event 'user.updated': {e}, sse: {_sse!r}")
                                elif _sse.event == "error":
                                    try:
                                        yield typing.cast(
                                            EventStreamCloudEventErrorMessage,
                                            parse_obj_as(
                                                type_=EventStreamCloudEventErrorMessage,  # type: ignore
                                                object_=json.loads(_sse.data),
                                            ),
                                        )
                                    except Exception as e:
                                        warning(f"Failed to parse SSE event 'error': {e}, sse: {_sse!r}")
                                elif _sse.event == "offset-only":
                                    try:
                                        yield typing.cast(
                                            EventStreamCloudEventOffsetOnlyMessage,
                                            parse_obj_as(
                                                type_=EventStreamCloudEventOffsetOnlyMessage,  # type: ignore
                                                object_=json.loads(_sse.data),
                                            ),
                                        )
                                    except Exception as e:
                                        warning(f"Failed to parse SSE event 'offset-only': {e}, sse: {_sse!r}")
                            return

                        return HttpResponse(response=_response, data=_iter())
                    _response.read()
                    if _response.status_code == 400:
                        raise BadRequestError(
                            headers=dict(_response.headers),
                            body=typing.cast(
                                typing.Any,
                                parse_obj_as(
                                    type_=typing.Any,  # type: ignore
                                    object_=_response.json(),
                                ),
                            ),
                        )
                    if _response.status_code == 401:
                        raise UnauthorizedError(
                            headers=dict(_response.headers),
                            body=typing.cast(
                                typing.Any,
                                parse_obj_as(
                                    type_=typing.Any,  # type: ignore
                                    object_=_response.json(),
                                ),
                            ),
                        )
                    if _response.status_code == 403:
                        raise ForbiddenError(
                            headers=dict(_response.headers),
                            body=typing.cast(
                                typing.Any,
                                parse_obj_as(
                                    type_=typing.Any,  # type: ignore
                                    object_=_response.json(),
                                ),
                            ),
                        )
                    if _response.status_code == 404:
                        raise NotFoundError(
                            headers=dict(_response.headers),
                            body=typing.cast(
                                typing.Any,
                                parse_obj_as(
                                    type_=typing.Any,  # type: ignore
                                    object_=_response.json(),
                                ),
                            ),
                        )
                    if _response.status_code == 410:
                        raise GoneError(
                            headers=dict(_response.headers),
                            body=typing.cast(
                                typing.Any,
                                parse_obj_as(
                                    type_=typing.Any,  # type: ignore
                                    object_=_response.json(),
                                ),
                            ),
                        )
                    if _response.status_code == 429:
                        raise TooManyRequestsError(
                            headers=dict(_response.headers),
                            body=typing.cast(
                                typing.Any,
                                parse_obj_as(
                                    type_=typing.Any,  # type: ignore
                                    object_=_response.json(),
                                ),
                            ),
                        )
                    _response_json = _response.json()
                except JSONDecodeError:
                    raise ApiError(
                        status_code=_response.status_code, headers=dict(_response.headers), body=_response.text
                    )
                except ValidationError as e:
                    raise ParsingError(
                        status_code=_response.status_code,
                        headers=dict(_response.headers),
                        body=_response.json(),
                        cause=e,
                    )
                raise ApiError(status_code=_response.status_code, headers=dict(_response.headers), body=_response_json)

            yield _stream()


class AsyncRawEventsClient:
    def __init__(self, *, client_wrapper: AsyncClientWrapper):
        self._client_wrapper = client_wrapper

    @contextlib.asynccontextmanager
    async def subscribe(
        self,
        *,
        from_: typing.Optional[str] = None,
        from_timestamp: typing.Optional[str] = None,
        event_type: typing.Optional[
            typing.Union[
                EventStreamSubscribeEventsEventTypeEnum, typing.Sequence[EventStreamSubscribeEventsEventTypeEnum]
            ]
        ] = None,
        request_options: typing.Optional[RequestOptions] = None,
    ) -> typing.AsyncIterator[AsyncHttpResponse[typing.AsyncIterator[EventStreamSubscribeEventsResponseContent]]]:
        """
        Subscribe to events via Server-Sent Events (SSE)

        Parameters
        ----------
        from_ : typing.Optional[str]
            Opaque token representing position in the stream. If not provided, stream will start from the latest events.

        from_timestamp : typing.Optional[str]
            RFC-3339 timestamp indicating where to start streaming events from. This should only be used on the initial query when a cursor may not be available. Subsequent requests should use the cursor (from) as it will be more accurate.

        event_type : typing.Optional[typing.Union[EventStreamSubscribeEventsEventTypeEnum, typing.Sequence[EventStreamSubscribeEventsEventTypeEnum]]]
            Event type(s) to listen for. Specify multiple times for multiple types (e.g., ?event_type=user.created&event_type=user.updated). If not provided, all event types will be streamed.

        request_options : typing.Optional[RequestOptions]
            Request-specific configuration.

        Yields
        ------
        typing.AsyncIterator[AsyncHttpResponse[typing.AsyncIterator[EventStreamSubscribeEventsResponseContent]]]
            Event stream successfully established.
        """
        async with self._client_wrapper.httpx_client.stream(
            "events",
            method="GET",
            params={
                "from": from_,
                "from_timestamp": from_timestamp,
                "event_type": event_type,
            },
            request_options=request_options,
        ) as _response:

            async def _stream() -> AsyncHttpResponse[typing.AsyncIterator[EventStreamSubscribeEventsResponseContent]]:
                try:
                    if 200 <= _response.status_code < 300:

                        async def _iter():
                            _event_source = EventSource(_response)
                            async for _sse in _event_source.aiter_sse():
                                if _sse.data == None:
                                    return
                                if _sse.event == "connection.created":
                                    try:
                                        yield typing.cast(
                                            EventStreamCloudEventConnectionCreated,
                                            parse_obj_as(
                                                type_=EventStreamCloudEventConnectionCreated,  # type: ignore
                                                object_=json.loads(_sse.data),
                                            ),
                                        )
                                    except Exception as e:
                                        warning(f"Failed to parse SSE event 'connection.created': {e}, sse: {_sse!r}")
                                elif _sse.event == "connection.deleted":
                                    try:
                                        yield typing.cast(
                                            EventStreamCloudEventConnectionDeleted,
                                            parse_obj_as(
                                                type_=EventStreamCloudEventConnectionDeleted,  # type: ignore
                                                object_=json.loads(_sse.data),
                                            ),
                                        )
                                    except Exception as e:
                                        warning(f"Failed to parse SSE event 'connection.deleted': {e}, sse: {_sse!r}")
                                elif _sse.event == "connection.updated":
                                    try:
                                        yield typing.cast(
                                            EventStreamCloudEventConnectionUpdated,
                                            parse_obj_as(
                                                type_=EventStreamCloudEventConnectionUpdated,  # type: ignore
                                                object_=json.loads(_sse.data),
                                            ),
                                        )
                                    except Exception as e:
                                        warning(f"Failed to parse SSE event 'connection.updated': {e}, sse: {_sse!r}")
                                elif _sse.event == "group.created":
                                    try:
                                        yield typing.cast(
                                            EventStreamCloudEventGroupCreated,
                                            parse_obj_as(
                                                type_=EventStreamCloudEventGroupCreated,  # type: ignore
                                                object_=json.loads(_sse.data),
                                            ),
                                        )
                                    except Exception as e:
                                        warning(f"Failed to parse SSE event 'group.created': {e}, sse: {_sse!r}")
                                elif _sse.event == "group.deleted":
                                    try:
                                        yield typing.cast(
                                            EventStreamCloudEventGroupDeleted,
                                            parse_obj_as(
                                                type_=EventStreamCloudEventGroupDeleted,  # type: ignore
                                                object_=json.loads(_sse.data),
                                            ),
                                        )
                                    except Exception as e:
                                        warning(f"Failed to parse SSE event 'group.deleted': {e}, sse: {_sse!r}")
                                elif _sse.event == "group.member.added":
                                    try:
                                        yield typing.cast(
                                            EventStreamCloudEventGroupMemberAdded,
                                            parse_obj_as(
                                                type_=EventStreamCloudEventGroupMemberAdded,  # type: ignore
                                                object_=json.loads(_sse.data),
                                            ),
                                        )
                                    except Exception as e:
                                        warning(f"Failed to parse SSE event 'group.member.added': {e}, sse: {_sse!r}")
                                elif _sse.event == "group.member.deleted":
                                    try:
                                        yield typing.cast(
                                            EventStreamCloudEventGroupMemberDeleted,
                                            parse_obj_as(
                                                type_=EventStreamCloudEventGroupMemberDeleted,  # type: ignore
                                                object_=json.loads(_sse.data),
                                            ),
                                        )
                                    except Exception as e:
                                        warning(f"Failed to parse SSE event 'group.member.deleted': {e}, sse: {_sse!r}")
                                elif _sse.event == "group.role.assigned":
                                    try:
                                        yield typing.cast(
                                            EventStreamCloudEventGroupRoleAssigned,
                                            parse_obj_as(
                                                type_=EventStreamCloudEventGroupRoleAssigned,  # type: ignore
                                                object_=json.loads(_sse.data),
                                            ),
                                        )
                                    except Exception as e:
                                        warning(f"Failed to parse SSE event 'group.role.assigned': {e}, sse: {_sse!r}")
                                elif _sse.event == "group.role.deleted":
                                    try:
                                        yield typing.cast(
                                            EventStreamCloudEventGroupRoleDeleted,
                                            parse_obj_as(
                                                type_=EventStreamCloudEventGroupRoleDeleted,  # type: ignore
                                                object_=json.loads(_sse.data),
                                            ),
                                        )
                                    except Exception as e:
                                        warning(f"Failed to parse SSE event 'group.role.deleted': {e}, sse: {_sse!r}")
                                elif _sse.event == "group.updated":
                                    try:
                                        yield typing.cast(
                                            EventStreamCloudEventGroupUpdated,
                                            parse_obj_as(
                                                type_=EventStreamCloudEventGroupUpdated,  # type: ignore
                                                object_=json.loads(_sse.data),
                                            ),
                                        )
                                    except Exception as e:
                                        warning(f"Failed to parse SSE event 'group.updated': {e}, sse: {_sse!r}")
                                elif _sse.event == "organization.connection.added":
                                    try:
                                        yield typing.cast(
                                            EventStreamCloudEventOrgConnectionAdded,
                                            parse_obj_as(
                                                type_=EventStreamCloudEventOrgConnectionAdded,  # type: ignore
                                                object_=json.loads(_sse.data),
                                            ),
                                        )
                                    except Exception as e:
                                        warning(
                                            f"Failed to parse SSE event 'organization.connection.added': {e}, sse: {_sse!r}"
                                        )
                                elif _sse.event == "organization.connection.removed":
                                    try:
                                        yield typing.cast(
                                            EventStreamCloudEventOrgConnectionRemoved,
                                            parse_obj_as(
                                                type_=EventStreamCloudEventOrgConnectionRemoved,  # type: ignore
                                                object_=json.loads(_sse.data),
                                            ),
                                        )
                                    except Exception as e:
                                        warning(
                                            f"Failed to parse SSE event 'organization.connection.removed': {e}, sse: {_sse!r}"
                                        )
                                elif _sse.event == "organization.connection.updated":
                                    try:
                                        yield typing.cast(
                                            EventStreamCloudEventOrgConnectionUpdated,
                                            parse_obj_as(
                                                type_=EventStreamCloudEventOrgConnectionUpdated,  # type: ignore
                                                object_=json.loads(_sse.data),
                                            ),
                                        )
                                    except Exception as e:
                                        warning(
                                            f"Failed to parse SSE event 'organization.connection.updated': {e}, sse: {_sse!r}"
                                        )
                                elif _sse.event == "organization.created":
                                    try:
                                        yield typing.cast(
                                            EventStreamCloudEventOrgCreated,
                                            parse_obj_as(
                                                type_=EventStreamCloudEventOrgCreated,  # type: ignore
                                                object_=json.loads(_sse.data),
                                            ),
                                        )
                                    except Exception as e:
                                        warning(f"Failed to parse SSE event 'organization.created': {e}, sse: {_sse!r}")
                                elif _sse.event == "organization.deleted":
                                    try:
                                        yield typing.cast(
                                            EventStreamCloudEventOrgDeleted,
                                            parse_obj_as(
                                                type_=EventStreamCloudEventOrgDeleted,  # type: ignore
                                                object_=json.loads(_sse.data),
                                            ),
                                        )
                                    except Exception as e:
                                        warning(f"Failed to parse SSE event 'organization.deleted': {e}, sse: {_sse!r}")
                                elif _sse.event == "organization.group.role.assigned":
                                    try:
                                        yield typing.cast(
                                            EventStreamCloudEventOrgGroupRoleAssigned,
                                            parse_obj_as(
                                                type_=EventStreamCloudEventOrgGroupRoleAssigned,  # type: ignore
                                                object_=json.loads(_sse.data),
                                            ),
                                        )
                                    except Exception as e:
                                        warning(
                                            f"Failed to parse SSE event 'organization.group.role.assigned': {e}, sse: {_sse!r}"
                                        )
                                elif _sse.event == "organization.group.role.deleted":
                                    try:
                                        yield typing.cast(
                                            EventStreamCloudEventOrgGroupRoleDeleted,
                                            parse_obj_as(
                                                type_=EventStreamCloudEventOrgGroupRoleDeleted,  # type: ignore
                                                object_=json.loads(_sse.data),
                                            ),
                                        )
                                    except Exception as e:
                                        warning(
                                            f"Failed to parse SSE event 'organization.group.role.deleted': {e}, sse: {_sse!r}"
                                        )
                                elif _sse.event == "organization.member.added":
                                    try:
                                        yield typing.cast(
                                            EventStreamCloudEventOrgMemberAdded,
                                            parse_obj_as(
                                                type_=EventStreamCloudEventOrgMemberAdded,  # type: ignore
                                                object_=json.loads(_sse.data),
                                            ),
                                        )
                                    except Exception as e:
                                        warning(
                                            f"Failed to parse SSE event 'organization.member.added': {e}, sse: {_sse!r}"
                                        )
                                elif _sse.event == "organization.member.deleted":
                                    try:
                                        yield typing.cast(
                                            EventStreamCloudEventOrgMemberDeleted,
                                            parse_obj_as(
                                                type_=EventStreamCloudEventOrgMemberDeleted,  # type: ignore
                                                object_=json.loads(_sse.data),
                                            ),
                                        )
                                    except Exception as e:
                                        warning(
                                            f"Failed to parse SSE event 'organization.member.deleted': {e}, sse: {_sse!r}"
                                        )
                                elif _sse.event == "organization.member.role.assigned":
                                    try:
                                        yield typing.cast(
                                            EventStreamCloudEventOrgMemberRoleAssigned,
                                            parse_obj_as(
                                                type_=EventStreamCloudEventOrgMemberRoleAssigned,  # type: ignore
                                                object_=json.loads(_sse.data),
                                            ),
                                        )
                                    except Exception as e:
                                        warning(
                                            f"Failed to parse SSE event 'organization.member.role.assigned': {e}, sse: {_sse!r}"
                                        )
                                elif _sse.event == "organization.member.role.deleted":
                                    try:
                                        yield typing.cast(
                                            EventStreamCloudEventOrgMemberRoleDeleted,
                                            parse_obj_as(
                                                type_=EventStreamCloudEventOrgMemberRoleDeleted,  # type: ignore
                                                object_=json.loads(_sse.data),
                                            ),
                                        )
                                    except Exception as e:
                                        warning(
                                            f"Failed to parse SSE event 'organization.member.role.deleted': {e}, sse: {_sse!r}"
                                        )
                                elif _sse.event == "organization.updated":
                                    try:
                                        yield typing.cast(
                                            EventStreamCloudEventOrgUpdated,
                                            parse_obj_as(
                                                type_=EventStreamCloudEventOrgUpdated,  # type: ignore
                                                object_=json.loads(_sse.data),
                                            ),
                                        )
                                    except Exception as e:
                                        warning(f"Failed to parse SSE event 'organization.updated': {e}, sse: {_sse!r}")
                                elif _sse.event == "user.created":
                                    try:
                                        yield typing.cast(
                                            EventStreamCloudEventUserCreated,
                                            parse_obj_as(
                                                type_=EventStreamCloudEventUserCreated,  # type: ignore
                                                object_=json.loads(_sse.data),
                                            ),
                                        )
                                    except Exception as e:
                                        warning(f"Failed to parse SSE event 'user.created': {e}, sse: {_sse!r}")
                                elif _sse.event == "user.deleted":
                                    try:
                                        yield typing.cast(
                                            EventStreamCloudEventUserDeleted,
                                            parse_obj_as(
                                                type_=EventStreamCloudEventUserDeleted,  # type: ignore
                                                object_=json.loads(_sse.data),
                                            ),
                                        )
                                    except Exception as e:
                                        warning(f"Failed to parse SSE event 'user.deleted': {e}, sse: {_sse!r}")
                                elif _sse.event == "user.updated":
                                    try:
                                        yield typing.cast(
                                            EventStreamCloudEventUserUpdated,
                                            parse_obj_as(
                                                type_=EventStreamCloudEventUserUpdated,  # type: ignore
                                                object_=json.loads(_sse.data),
                                            ),
                                        )
                                    except Exception as e:
                                        warning(f"Failed to parse SSE event 'user.updated': {e}, sse: {_sse!r}")
                                elif _sse.event == "error":
                                    try:
                                        yield typing.cast(
                                            EventStreamCloudEventErrorMessage,
                                            parse_obj_as(
                                                type_=EventStreamCloudEventErrorMessage,  # type: ignore
                                                object_=json.loads(_sse.data),
                                            ),
                                        )
                                    except Exception as e:
                                        warning(f"Failed to parse SSE event 'error': {e}, sse: {_sse!r}")
                                elif _sse.event == "offset-only":
                                    try:
                                        yield typing.cast(
                                            EventStreamCloudEventOffsetOnlyMessage,
                                            parse_obj_as(
                                                type_=EventStreamCloudEventOffsetOnlyMessage,  # type: ignore
                                                object_=json.loads(_sse.data),
                                            ),
                                        )
                                    except Exception as e:
                                        warning(f"Failed to parse SSE event 'offset-only': {e}, sse: {_sse!r}")
                            return

                        return AsyncHttpResponse(response=_response, data=_iter())
                    await _response.aread()
                    if _response.status_code == 400:
                        raise BadRequestError(
                            headers=dict(_response.headers),
                            body=typing.cast(
                                typing.Any,
                                parse_obj_as(
                                    type_=typing.Any,  # type: ignore
                                    object_=_response.json(),
                                ),
                            ),
                        )
                    if _response.status_code == 401:
                        raise UnauthorizedError(
                            headers=dict(_response.headers),
                            body=typing.cast(
                                typing.Any,
                                parse_obj_as(
                                    type_=typing.Any,  # type: ignore
                                    object_=_response.json(),
                                ),
                            ),
                        )
                    if _response.status_code == 403:
                        raise ForbiddenError(
                            headers=dict(_response.headers),
                            body=typing.cast(
                                typing.Any,
                                parse_obj_as(
                                    type_=typing.Any,  # type: ignore
                                    object_=_response.json(),
                                ),
                            ),
                        )
                    if _response.status_code == 404:
                        raise NotFoundError(
                            headers=dict(_response.headers),
                            body=typing.cast(
                                typing.Any,
                                parse_obj_as(
                                    type_=typing.Any,  # type: ignore
                                    object_=_response.json(),
                                ),
                            ),
                        )
                    if _response.status_code == 410:
                        raise GoneError(
                            headers=dict(_response.headers),
                            body=typing.cast(
                                typing.Any,
                                parse_obj_as(
                                    type_=typing.Any,  # type: ignore
                                    object_=_response.json(),
                                ),
                            ),
                        )
                    if _response.status_code == 429:
                        raise TooManyRequestsError(
                            headers=dict(_response.headers),
                            body=typing.cast(
                                typing.Any,
                                parse_obj_as(
                                    type_=typing.Any,  # type: ignore
                                    object_=_response.json(),
                                ),
                            ),
                        )
                    _response_json = _response.json()
                except JSONDecodeError:
                    raise ApiError(
                        status_code=_response.status_code, headers=dict(_response.headers), body=_response.text
                    )
                except ValidationError as e:
                    raise ParsingError(
                        status_code=_response.status_code,
                        headers=dict(_response.headers),
                        body=_response.json(),
                        cause=e,
                    )
                raise ApiError(status_code=_response.status_code, headers=dict(_response.headers), body=_response_json)

            yield await _stream()
