# 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.jsonable_encoder import jsonable_encoder
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

# 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

    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)
        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)
        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)
        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)
        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)
        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)
        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

    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)
        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)
        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)
        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)
        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)
        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)
        raise ApiError(status_code=_response.status_code, headers=dict(_response.headers), body=_response_json)
