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

import contextlib
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.jsonable_encoder import jsonable_encoder
from ...core.parse_error import ParsingError
from ...core.request_options import RequestOptions
from ...core.serialization import convert_and_respect_annotation_metadata
from ...core.unchecked_base_model import construct_type
from ...errors.unprocessable_entity_error import UnprocessableEntityError
from ...types.batch_call_detailed_response import BatchCallDetailedResponse
from ...types.batch_call_response import BatchCallResponse
from ...types.batch_call_whats_app_params import BatchCallWhatsAppParams
from ...types.outbound_call_recipient import OutboundCallRecipient
from ...types.telephony_call_config import TelephonyCallConfig
from ...types.workspace_batch_calls_response import WorkspaceBatchCallsResponse
from pydantic import ValidationError

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


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

    @contextlib.contextmanager
    def export(
        self, batch_id: str, *, request_options: typing.Optional[RequestOptions] = None
    ) -> typing.Iterator[HttpResponse[typing.Iterator[bytes]]]:
        """
        Download all recipients and conversation results for a terminal batch call as CSV.

        Parameters
        ----------
        batch_id : str

        request_options : typing.Optional[RequestOptions]
            Request-specific configuration. You can pass in configuration such as `chunk_size`, and more to customize the request and response.

        Returns
        -------
        typing.Iterator[HttpResponse[typing.Iterator[bytes]]]
            Batch call results CSV.
        """
        with self._client_wrapper.httpx_client.stream(
            f"v1/convai/batch-calling/{jsonable_encoder(batch_id)}/export",
            method="GET",
            request_options=request_options,
        ) as _response:

            def _stream() -> HttpResponse[typing.Iterator[bytes]]:
                try:
                    if 200 <= _response.status_code < 300:
                        _chunk_size = request_options.get("chunk_size", 1024) if request_options is not None else 1024
                        return HttpResponse(
                            response=_response, data=(_chunk for _chunk in _response.iter_bytes(chunk_size=_chunk_size))
                        )
                    _response.read()
                    if _response.status_code == 422:
                        raise UnprocessableEntityError(
                            headers=dict(_response.headers),
                            body=typing.cast(
                                typing.Any,
                                construct_type(
                                    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()

    def create(
        self,
        *,
        call_name: str,
        agent_id: str,
        recipients: typing.Sequence[OutboundCallRecipient],
        scheduled_time_unix: typing.Optional[int] = OMIT,
        agent_phone_number_id: typing.Optional[str] = OMIT,
        whatsapp_params: typing.Optional[BatchCallWhatsAppParams] = OMIT,
        timezone: typing.Optional[str] = OMIT,
        branch_id: typing.Optional[str] = OMIT,
        environment: typing.Optional[str] = OMIT,
        telephony_call_config: typing.Optional[TelephonyCallConfig] = OMIT,
        target_concurrency_limit: typing.Optional[int] = OMIT,
        request_options: typing.Optional[RequestOptions] = None,
    ) -> HttpResponse[BatchCallResponse]:
        """
        Submit a batch call request to schedule calls for multiple recipients.

        Parameters
        ----------
        call_name : str

        agent_id : str

        recipients : typing.Sequence[OutboundCallRecipient]

        scheduled_time_unix : typing.Optional[int]

        agent_phone_number_id : typing.Optional[str]

        whatsapp_params : typing.Optional[BatchCallWhatsAppParams]

        timezone : typing.Optional[str]

        branch_id : typing.Optional[str]

        environment : typing.Optional[str]

        telephony_call_config : typing.Optional[TelephonyCallConfig]

        target_concurrency_limit : typing.Optional[int]
            Maximum number of simultaneous calls for this batch. When set, dispatch is governed by this limit rather than workspace/agent capacity percentages.

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

        Returns
        -------
        HttpResponse[BatchCallResponse]
            Successful Response
        """
        _response = self._client_wrapper.httpx_client.request(
            "v1/convai/batch-calling/submit",
            method="POST",
            json={
                "call_name": call_name,
                "agent_id": agent_id,
                "recipients": convert_and_respect_annotation_metadata(
                    object_=recipients, annotation=typing.Sequence[OutboundCallRecipient], direction="write"
                ),
                "scheduled_time_unix": scheduled_time_unix,
                "agent_phone_number_id": agent_phone_number_id,
                "whatsapp_params": convert_and_respect_annotation_metadata(
                    object_=whatsapp_params, annotation=BatchCallWhatsAppParams, direction="write"
                ),
                "timezone": timezone,
                "branch_id": branch_id,
                "environment": environment,
                "telephony_call_config": convert_and_respect_annotation_metadata(
                    object_=telephony_call_config, annotation=TelephonyCallConfig, direction="write"
                ),
                "target_concurrency_limit": target_concurrency_limit,
            },
            headers={
                "content-type": "application/json",
            },
            request_options=request_options,
            omit=OMIT,
        )
        try:
            if 200 <= _response.status_code < 300:
                _data = typing.cast(
                    BatchCallResponse,
                    construct_type(
                        type_=BatchCallResponse,  # 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(
                        typing.Any,
                        construct_type(
                            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)

    def list(
        self,
        *,
        limit: typing.Optional[int] = None,
        last_doc: typing.Optional[str] = None,
        agent_id: typing.Optional[str] = None,
        request_options: typing.Optional[RequestOptions] = None,
    ) -> HttpResponse[WorkspaceBatchCallsResponse]:
        """
        Get all batch calls for the current workspace.

        Parameters
        ----------
        limit : typing.Optional[int]

        last_doc : typing.Optional[str]

        agent_id : typing.Optional[str]
            Filter batch calls to a single agent.

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

        Returns
        -------
        HttpResponse[WorkspaceBatchCallsResponse]
            Successful Response
        """
        _response = self._client_wrapper.httpx_client.request(
            "v1/convai/batch-calling/workspace",
            method="GET",
            params={
                "limit": limit,
                "last_doc": last_doc,
                "agent_id": agent_id,
            },
            request_options=request_options,
        )
        try:
            if 200 <= _response.status_code < 300:
                _data = typing.cast(
                    WorkspaceBatchCallsResponse,
                    construct_type(
                        type_=WorkspaceBatchCallsResponse,  # 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(
                        typing.Any,
                        construct_type(
                            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)

    def get(
        self, batch_id: str, *, request_options: typing.Optional[RequestOptions] = None
    ) -> HttpResponse[BatchCallDetailedResponse]:
        """
        Get detailed information about a batch call including all recipients.

        Parameters
        ----------
        batch_id : str

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

        Returns
        -------
        HttpResponse[BatchCallDetailedResponse]
            Successful Response
        """
        _response = self._client_wrapper.httpx_client.request(
            f"v1/convai/batch-calling/{jsonable_encoder(batch_id)}",
            method="GET",
            request_options=request_options,
        )
        try:
            if 200 <= _response.status_code < 300:
                _data = typing.cast(
                    BatchCallDetailedResponse,
                    construct_type(
                        type_=BatchCallDetailedResponse,  # 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(
                        typing.Any,
                        construct_type(
                            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)

    def delete(self, batch_id: str, *, request_options: typing.Optional[RequestOptions] = None) -> HttpResponse[None]:
        """
        Permanently delete a batch call and all recipient records. Conversations remain in history.

        Parameters
        ----------
        batch_id : str

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

        Returns
        -------
        HttpResponse[None]
        """
        _response = self._client_wrapper.httpx_client.request(
            f"v1/convai/batch-calling/{jsonable_encoder(batch_id)}",
            method="DELETE",
            request_options=request_options,
        )
        try:
            if 200 <= _response.status_code < 300:
                return HttpResponse(response=_response, data=None)
            if _response.status_code == 422:
                raise UnprocessableEntityError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        typing.Any,
                        construct_type(
                            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)

    def cancel(
        self, batch_id: str, *, request_options: typing.Optional[RequestOptions] = None
    ) -> HttpResponse[BatchCallResponse]:
        """
        Cancel a running batch call and set all recipients to cancelled status.

        Parameters
        ----------
        batch_id : str

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

        Returns
        -------
        HttpResponse[BatchCallResponse]
            Successful Response
        """
        _response = self._client_wrapper.httpx_client.request(
            f"v1/convai/batch-calling/{jsonable_encoder(batch_id)}/cancel",
            method="POST",
            request_options=request_options,
        )
        try:
            if 200 <= _response.status_code < 300:
                _data = typing.cast(
                    BatchCallResponse,
                    construct_type(
                        type_=BatchCallResponse,  # 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(
                        typing.Any,
                        construct_type(
                            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)

    def retry(
        self, batch_id: str, *, request_options: typing.Optional[RequestOptions] = None
    ) -> HttpResponse[BatchCallResponse]:
        """
        Retry a batch call, calling failed and no-response recipients again.

        Parameters
        ----------
        batch_id : str

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

        Returns
        -------
        HttpResponse[BatchCallResponse]
            Successful Response
        """
        _response = self._client_wrapper.httpx_client.request(
            f"v1/convai/batch-calling/{jsonable_encoder(batch_id)}/retry",
            method="POST",
            request_options=request_options,
        )
        try:
            if 200 <= _response.status_code < 300:
                _data = typing.cast(
                    BatchCallResponse,
                    construct_type(
                        type_=BatchCallResponse,  # 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(
                        typing.Any,
                        construct_type(
                            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)


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

    @contextlib.asynccontextmanager
    async def export(
        self, batch_id: str, *, request_options: typing.Optional[RequestOptions] = None
    ) -> typing.AsyncIterator[AsyncHttpResponse[typing.AsyncIterator[bytes]]]:
        """
        Download all recipients and conversation results for a terminal batch call as CSV.

        Parameters
        ----------
        batch_id : str

        request_options : typing.Optional[RequestOptions]
            Request-specific configuration. You can pass in configuration such as `chunk_size`, and more to customize the request and response.

        Returns
        -------
        typing.AsyncIterator[AsyncHttpResponse[typing.AsyncIterator[bytes]]]
            Batch call results CSV.
        """
        async with self._client_wrapper.httpx_client.stream(
            f"v1/convai/batch-calling/{jsonable_encoder(batch_id)}/export",
            method="GET",
            request_options=request_options,
        ) as _response:

            async def _stream() -> AsyncHttpResponse[typing.AsyncIterator[bytes]]:
                try:
                    if 200 <= _response.status_code < 300:
                        _chunk_size = request_options.get("chunk_size", 1024) if request_options is not None else 1024
                        return AsyncHttpResponse(
                            response=_response,
                            data=(_chunk async for _chunk in _response.aiter_bytes(chunk_size=_chunk_size)),
                        )
                    await _response.aread()
                    if _response.status_code == 422:
                        raise UnprocessableEntityError(
                            headers=dict(_response.headers),
                            body=typing.cast(
                                typing.Any,
                                construct_type(
                                    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()

    async def create(
        self,
        *,
        call_name: str,
        agent_id: str,
        recipients: typing.Sequence[OutboundCallRecipient],
        scheduled_time_unix: typing.Optional[int] = OMIT,
        agent_phone_number_id: typing.Optional[str] = OMIT,
        whatsapp_params: typing.Optional[BatchCallWhatsAppParams] = OMIT,
        timezone: typing.Optional[str] = OMIT,
        branch_id: typing.Optional[str] = OMIT,
        environment: typing.Optional[str] = OMIT,
        telephony_call_config: typing.Optional[TelephonyCallConfig] = OMIT,
        target_concurrency_limit: typing.Optional[int] = OMIT,
        request_options: typing.Optional[RequestOptions] = None,
    ) -> AsyncHttpResponse[BatchCallResponse]:
        """
        Submit a batch call request to schedule calls for multiple recipients.

        Parameters
        ----------
        call_name : str

        agent_id : str

        recipients : typing.Sequence[OutboundCallRecipient]

        scheduled_time_unix : typing.Optional[int]

        agent_phone_number_id : typing.Optional[str]

        whatsapp_params : typing.Optional[BatchCallWhatsAppParams]

        timezone : typing.Optional[str]

        branch_id : typing.Optional[str]

        environment : typing.Optional[str]

        telephony_call_config : typing.Optional[TelephonyCallConfig]

        target_concurrency_limit : typing.Optional[int]
            Maximum number of simultaneous calls for this batch. When set, dispatch is governed by this limit rather than workspace/agent capacity percentages.

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

        Returns
        -------
        AsyncHttpResponse[BatchCallResponse]
            Successful Response
        """
        _response = await self._client_wrapper.httpx_client.request(
            "v1/convai/batch-calling/submit",
            method="POST",
            json={
                "call_name": call_name,
                "agent_id": agent_id,
                "recipients": convert_and_respect_annotation_metadata(
                    object_=recipients, annotation=typing.Sequence[OutboundCallRecipient], direction="write"
                ),
                "scheduled_time_unix": scheduled_time_unix,
                "agent_phone_number_id": agent_phone_number_id,
                "whatsapp_params": convert_and_respect_annotation_metadata(
                    object_=whatsapp_params, annotation=BatchCallWhatsAppParams, direction="write"
                ),
                "timezone": timezone,
                "branch_id": branch_id,
                "environment": environment,
                "telephony_call_config": convert_and_respect_annotation_metadata(
                    object_=telephony_call_config, annotation=TelephonyCallConfig, direction="write"
                ),
                "target_concurrency_limit": target_concurrency_limit,
            },
            headers={
                "content-type": "application/json",
            },
            request_options=request_options,
            omit=OMIT,
        )
        try:
            if 200 <= _response.status_code < 300:
                _data = typing.cast(
                    BatchCallResponse,
                    construct_type(
                        type_=BatchCallResponse,  # 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(
                        typing.Any,
                        construct_type(
                            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)

    async def list(
        self,
        *,
        limit: typing.Optional[int] = None,
        last_doc: typing.Optional[str] = None,
        agent_id: typing.Optional[str] = None,
        request_options: typing.Optional[RequestOptions] = None,
    ) -> AsyncHttpResponse[WorkspaceBatchCallsResponse]:
        """
        Get all batch calls for the current workspace.

        Parameters
        ----------
        limit : typing.Optional[int]

        last_doc : typing.Optional[str]

        agent_id : typing.Optional[str]
            Filter batch calls to a single agent.

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

        Returns
        -------
        AsyncHttpResponse[WorkspaceBatchCallsResponse]
            Successful Response
        """
        _response = await self._client_wrapper.httpx_client.request(
            "v1/convai/batch-calling/workspace",
            method="GET",
            params={
                "limit": limit,
                "last_doc": last_doc,
                "agent_id": agent_id,
            },
            request_options=request_options,
        )
        try:
            if 200 <= _response.status_code < 300:
                _data = typing.cast(
                    WorkspaceBatchCallsResponse,
                    construct_type(
                        type_=WorkspaceBatchCallsResponse,  # 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(
                        typing.Any,
                        construct_type(
                            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)

    async def get(
        self, batch_id: str, *, request_options: typing.Optional[RequestOptions] = None
    ) -> AsyncHttpResponse[BatchCallDetailedResponse]:
        """
        Get detailed information about a batch call including all recipients.

        Parameters
        ----------
        batch_id : str

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

        Returns
        -------
        AsyncHttpResponse[BatchCallDetailedResponse]
            Successful Response
        """
        _response = await self._client_wrapper.httpx_client.request(
            f"v1/convai/batch-calling/{jsonable_encoder(batch_id)}",
            method="GET",
            request_options=request_options,
        )
        try:
            if 200 <= _response.status_code < 300:
                _data = typing.cast(
                    BatchCallDetailedResponse,
                    construct_type(
                        type_=BatchCallDetailedResponse,  # 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(
                        typing.Any,
                        construct_type(
                            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)

    async def delete(
        self, batch_id: str, *, request_options: typing.Optional[RequestOptions] = None
    ) -> AsyncHttpResponse[None]:
        """
        Permanently delete a batch call and all recipient records. Conversations remain in history.

        Parameters
        ----------
        batch_id : str

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

        Returns
        -------
        AsyncHttpResponse[None]
        """
        _response = await self._client_wrapper.httpx_client.request(
            f"v1/convai/batch-calling/{jsonable_encoder(batch_id)}",
            method="DELETE",
            request_options=request_options,
        )
        try:
            if 200 <= _response.status_code < 300:
                return AsyncHttpResponse(response=_response, data=None)
            if _response.status_code == 422:
                raise UnprocessableEntityError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        typing.Any,
                        construct_type(
                            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)

    async def cancel(
        self, batch_id: str, *, request_options: typing.Optional[RequestOptions] = None
    ) -> AsyncHttpResponse[BatchCallResponse]:
        """
        Cancel a running batch call and set all recipients to cancelled status.

        Parameters
        ----------
        batch_id : str

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

        Returns
        -------
        AsyncHttpResponse[BatchCallResponse]
            Successful Response
        """
        _response = await self._client_wrapper.httpx_client.request(
            f"v1/convai/batch-calling/{jsonable_encoder(batch_id)}/cancel",
            method="POST",
            request_options=request_options,
        )
        try:
            if 200 <= _response.status_code < 300:
                _data = typing.cast(
                    BatchCallResponse,
                    construct_type(
                        type_=BatchCallResponse,  # 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(
                        typing.Any,
                        construct_type(
                            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)

    async def retry(
        self, batch_id: str, *, request_options: typing.Optional[RequestOptions] = None
    ) -> AsyncHttpResponse[BatchCallResponse]:
        """
        Retry a batch call, calling failed and no-response recipients again.

        Parameters
        ----------
        batch_id : str

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

        Returns
        -------
        AsyncHttpResponse[BatchCallResponse]
            Successful Response
        """
        _response = await self._client_wrapper.httpx_client.request(
            f"v1/convai/batch-calling/{jsonable_encoder(batch_id)}/retry",
            method="POST",
            request_options=request_options,
        )
        try:
            if 200 <= _response.status_code < 300:
                _data = typing.cast(
                    BatchCallResponse,
                    construct_type(
                        type_=BatchCallResponse,  # 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(
                        typing.Any,
                        construct_type(
                            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)
