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

import typing
from json.decoder import JSONDecodeError

from ..core.api_error import ApiError
from ..core.client_wrapper import AsyncClientWrapper, SyncClientWrapper
from ..core.http_response import AsyncHttpResponse, HttpResponse
from ..core.pydantic_utilities import parse_obj_as
from ..core.request_options import RequestOptions
from ..errors.unprocessable_entity_error import UnprocessableEntityError
from ..types.http_validation_error import HttpValidationError
from ..types.publish_raw_event_response import PublishRawEventResponse

# this is used as the default value for optional parameters
OMIT = typing.cast(typing.Any, ...)


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

    def publish_raw_event(
        self,
        *,
        raw_event: typing.Dict[str, typing.Any],
        sdk_type: str,
        sdk_version: str,
        task_id: str,
        idempotency_key: typing.Optional[str] = OMIT,
        request_options: typing.Optional[RequestOptions] = None,
    ) -> HttpResponse[PublishRawEventResponse]:
        """
        Publish a raw SDK event for transformation and streaming.

            This endpoint replaces the deprecated `/stream-events` endpoint.
            Events are transformed via SDK-specific adapters (based on `sdk_type` and `sdk_version`)
            and the resulting stream parts are published to Redis for real-time consumption.

            Messages that should be stored (e.g., AssistantMessage, UserMessage) are
            automatically persisted to MongoDB for later retrieval.

            **Supported SDK Types:**
            - `claude`: Claude Agent SDK messages (StreamEvent, AssistantMessage, etc.)
            - `codex`: Codex SDK thread events (`item.*`, `turn.*`, `thread.*`)
            - `terminal_use`: Direct UIMessage format (Vercel-compatible)

            **What gets stored:**
            - AssistantMessage, UserMessage, ResultMessage, SystemMessage

            **What does NOT get stored:**
            - StreamEvent (ephemeral streaming deltas)

            Requires `update` permission on the task.

        Parameters
        ----------
        raw_event : typing.Dict[str, typing.Any]
            The raw SDK event payload

        sdk_type : str
            SDK type identifier (e.g., 'claude', 'codex', 'terminal_use')

        sdk_version : str
            SDK version in semver format (e.g., '0.1.22')

        task_id : str
            Task ID to publish the event to

        idempotency_key : typing.Optional[str]
            Optional idempotency key for request-level deduplication

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

        Returns
        -------
        HttpResponse[PublishRawEventResponse]
            Successful Response
        """
        _request_options_with_retries_disabled: typing.Optional[RequestOptions] = (
            {**request_options, "max_retries": 0} if request_options is not None else {"max_retries": 0}
        )
        _response = self._client_wrapper.httpx_client.request(
            "raw-events",
            method="POST",
            json={
                "idempotency_key": idempotency_key,
                "raw_event": raw_event,
                "sdk_type": sdk_type,
                "sdk_version": sdk_version,
                "task_id": task_id,
            },
            headers={
                "content-type": "application/json",
            },
            request_options=_request_options_with_retries_disabled,
            omit=OMIT,
        )
        try:
            if 200 <= _response.status_code < 300:
                _data = typing.cast(
                    PublishRawEventResponse,
                    parse_obj_as(
                        type_=PublishRawEventResponse,  # type: ignore
                        object_=_response.json(),
                    ),
                )
                return HttpResponse(response=_response, data=_data)
            if _response.status_code == 422:
                raise UnprocessableEntityError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        HttpValidationError,
                        parse_obj_as(
                            type_=HttpValidationError,  # 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)
        raise ApiError(status_code=_response.status_code, headers=dict(_response.headers), body=_response_json)


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

    async def publish_raw_event(
        self,
        *,
        raw_event: typing.Dict[str, typing.Any],
        sdk_type: str,
        sdk_version: str,
        task_id: str,
        idempotency_key: typing.Optional[str] = OMIT,
        request_options: typing.Optional[RequestOptions] = None,
    ) -> AsyncHttpResponse[PublishRawEventResponse]:
        """
        Publish a raw SDK event for transformation and streaming.

            This endpoint replaces the deprecated `/stream-events` endpoint.
            Events are transformed via SDK-specific adapters (based on `sdk_type` and `sdk_version`)
            and the resulting stream parts are published to Redis for real-time consumption.

            Messages that should be stored (e.g., AssistantMessage, UserMessage) are
            automatically persisted to MongoDB for later retrieval.

            **Supported SDK Types:**
            - `claude`: Claude Agent SDK messages (StreamEvent, AssistantMessage, etc.)
            - `codex`: Codex SDK thread events (`item.*`, `turn.*`, `thread.*`)
            - `terminal_use`: Direct UIMessage format (Vercel-compatible)

            **What gets stored:**
            - AssistantMessage, UserMessage, ResultMessage, SystemMessage

            **What does NOT get stored:**
            - StreamEvent (ephemeral streaming deltas)

            Requires `update` permission on the task.

        Parameters
        ----------
        raw_event : typing.Dict[str, typing.Any]
            The raw SDK event payload

        sdk_type : str
            SDK type identifier (e.g., 'claude', 'codex', 'terminal_use')

        sdk_version : str
            SDK version in semver format (e.g., '0.1.22')

        task_id : str
            Task ID to publish the event to

        idempotency_key : typing.Optional[str]
            Optional idempotency key for request-level deduplication

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

        Returns
        -------
        AsyncHttpResponse[PublishRawEventResponse]
            Successful Response
        """
        _request_options_with_retries_disabled: typing.Optional[RequestOptions] = (
            {**request_options, "max_retries": 0} if request_options is not None else {"max_retries": 0}
        )
        _response = await self._client_wrapper.httpx_client.request(
            "raw-events",
            method="POST",
            json={
                "idempotency_key": idempotency_key,
                "raw_event": raw_event,
                "sdk_type": sdk_type,
                "sdk_version": sdk_version,
                "task_id": task_id,
            },
            headers={
                "content-type": "application/json",
            },
            request_options=_request_options_with_retries_disabled,
            omit=OMIT,
        )
        try:
            if 200 <= _response.status_code < 300:
                _data = typing.cast(
                    PublishRawEventResponse,
                    parse_obj_as(
                        type_=PublishRawEventResponse,  # type: ignore
                        object_=_response.json(),
                    ),
                )
                return AsyncHttpResponse(response=_response, data=_data)
            if _response.status_code == 422:
                raise UnprocessableEntityError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        HttpValidationError,
                        parse_obj_as(
                            type_=HttpValidationError,  # 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)
        raise ApiError(status_code=_response.status_code, headers=dict(_response.headers), body=_response_json)
