# 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.unchecked_base_model import construct_type
from ..errors.bad_request_error import BadRequestError
from ..errors.internal_server_error import InternalServerError
from ..errors.unauthorized_error import UnauthorizedError
from .types.get_conversation_id_response import GetConversationIdResponse
from .types.get_conversation_request_call_types import GetConversationRequestCallTypes
from .types.get_conversation_response import GetConversationResponse
from .types.post_conversation_search_response import PostConversationSearchResponse

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


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

    def get_all_conversation_logs(
        self,
        *,
        page: typing.Optional[int] = None,
        limit: typing.Optional[int] = None,
        agent_ids: typing.Optional[str] = None,
        campaign_ids: typing.Optional[str] = None,
        call_types: typing.Optional[GetConversationRequestCallTypes] = None,
        search: typing.Optional[str] = None,
        status_filter: typing.Optional[str] = None,
        disconnect_reason_filter: typing.Optional[str] = None,
        call_attempt_filter: typing.Optional[str] = None,
        duration_filter: typing.Optional[str] = None,
        request_options: typing.Optional[RequestOptions] = None,
    ) -> HttpResponse[GetConversationResponse]:
        """
        Retrieve paginated conversation logs with support for various filters. Returns call logs for agents belonging to the authenticated user's organization.

        Parameters
        ----------
        page : typing.Optional[int]
            Page number for pagination

        limit : typing.Optional[int]
            Number of items per page

        agent_ids : typing.Optional[str]
            Comma-separated list of agent IDs to filter by

        campaign_ids : typing.Optional[str]
            Comma-separated list of campaign IDs to filter by

        call_types : typing.Optional[GetConversationRequestCallTypes]
            Comma-separated list of call types to filter by

        search : typing.Optional[str]
            Search query to filter by callId, fromNumber, or toNumber

        status_filter : typing.Optional[str]
            Comma-separated list of call statuses to filter by.
            Available statuses: pending, in_progress, completed, failed, no_answer, cancelled, busy

        disconnect_reason_filter : typing.Optional[str]
            Comma-separated list of disconnect reasons to filter by.
            Available reasons: user_hangup, agent_hangup, connection_error, timeout, system_error, transfer_complete

        call_attempt_filter : typing.Optional[str]
            Comma-separated list of call attempt types to filter by.
            Available filters: initial (first attempt calls), retry (retry attempt calls), all (all calls)

        duration_filter : typing.Optional[str]
            Comma-separated list of duration ranges to filter by.
            Available ranges: 0-30 (0-30 seconds), 30-60 (30-60 seconds), 1-5 (1-5 minutes), 5+ (more than 5 minutes)

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

        Returns
        -------
        HttpResponse[GetConversationResponse]
            Successful response
        """
        _response = self._client_wrapper.httpx_client.request(
            "conversation",
            base_url=self._client_wrapper.get_environment().atoms,
            method="GET",
            params={
                "page": page,
                "limit": limit,
                "agentIds": agent_ids,
                "campaignIds": campaign_ids,
                "callTypes": call_types,
                "search": search,
                "statusFilter": status_filter,
                "disconnectReasonFilter": disconnect_reason_filter,
                "callAttemptFilter": call_attempt_filter,
                "durationFilter": duration_filter,
            },
            request_options=request_options,
        )
        try:
            if 200 <= _response.status_code < 300:
                _data = typing.cast(
                    GetConversationResponse,
                    construct_type(
                        type_=GetConversationResponse,  # type: ignore
                        object_=_response.json(),
                    ),
                )
                return HttpResponse(response=_response, data=_data)
            if _response.status_code == 400:
                raise BadRequestError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        typing.Any,
                        construct_type(
                            type_=typing.Any,  # type: ignore
                            object_=_response.json(),
                        ),
                    ),
                )
            if _response.status_code == 401:
                raise UnauthorizedError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        typing.Any,
                        construct_type(
                            type_=typing.Any,  # type: ignore
                            object_=_response.json(),
                        ),
                    ),
                )
            if _response.status_code == 500:
                raise InternalServerError(
                    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 search_conversation_logs_by_call_i_ds(
        self, *, call_ids: typing.Sequence[str], request_options: typing.Optional[RequestOptions] = None
    ) -> HttpResponse[PostConversationSearchResponse]:
        """
        Fetch specific conversation logs by their callIds. This endpoint allows you to retrieve up to 100 specific calls at once.
        Only returns calls that belong to agents in your organization (security check enforced).
        Unlike the GET /conversation endpoint, this endpoint can also return retry calls (non-root calls).

        Parameters
        ----------
        call_ids : typing.Sequence[str]
            Array of callIds to fetch

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

        Returns
        -------
        HttpResponse[PostConversationSearchResponse]
            Successful response
        """
        _response = self._client_wrapper.httpx_client.request(
            "conversation/search",
            base_url=self._client_wrapper.get_environment().atoms,
            method="POST",
            json={
                "callIds": call_ids,
            },
            headers={
                "content-type": "application/json",
            },
            request_options=request_options,
            omit=OMIT,
        )
        try:
            if 200 <= _response.status_code < 300:
                _data = typing.cast(
                    PostConversationSearchResponse,
                    construct_type(
                        type_=PostConversationSearchResponse,  # type: ignore
                        object_=_response.json(),
                    ),
                )
                return HttpResponse(response=_response, data=_data)
            if _response.status_code == 400:
                raise BadRequestError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        typing.Any,
                        construct_type(
                            type_=typing.Any,  # type: ignore
                            object_=_response.json(),
                        ),
                    ),
                )
            if _response.status_code == 401:
                raise UnauthorizedError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        typing.Any,
                        construct_type(
                            type_=typing.Any,  # type: ignore
                            object_=_response.json(),
                        ),
                    ),
                )
            if _response.status_code == 500:
                raise InternalServerError(
                    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_conversation_log_by_id(
        self, id: str, *, request_options: typing.Optional[RequestOptions] = None
    ) -> HttpResponse[GetConversationIdResponse]:
        """
        Retrieve detailed information about a specific conversation including transcript, events, and latency metrics.

        Parameters
        ----------
        id : str
            The callId of the conversation. You can get the callId from the conversation logs endpoint.

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

        Returns
        -------
        HttpResponse[GetConversationIdResponse]
            Successful response
        """
        _response = self._client_wrapper.httpx_client.request(
            f"conversation/{jsonable_encoder(id)}",
            base_url=self._client_wrapper.get_environment().atoms,
            method="GET",
            request_options=request_options,
        )
        try:
            if 200 <= _response.status_code < 300:
                _data = typing.cast(
                    GetConversationIdResponse,
                    construct_type(
                        type_=GetConversationIdResponse,  # type: ignore
                        object_=_response.json(),
                    ),
                )
                return HttpResponse(response=_response, data=_data)
            if _response.status_code == 400:
                raise BadRequestError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        typing.Any,
                        construct_type(
                            type_=typing.Any,  # type: ignore
                            object_=_response.json(),
                        ),
                    ),
                )
            if _response.status_code == 401:
                raise UnauthorizedError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        typing.Any,
                        construct_type(
                            type_=typing.Any,  # type: ignore
                            object_=_response.json(),
                        ),
                    ),
                )
            if _response.status_code == 500:
                raise InternalServerError(
                    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 AsyncRawLogsClient:
    def __init__(self, *, client_wrapper: AsyncClientWrapper):
        self._client_wrapper = client_wrapper

    async def get_all_conversation_logs(
        self,
        *,
        page: typing.Optional[int] = None,
        limit: typing.Optional[int] = None,
        agent_ids: typing.Optional[str] = None,
        campaign_ids: typing.Optional[str] = None,
        call_types: typing.Optional[GetConversationRequestCallTypes] = None,
        search: typing.Optional[str] = None,
        status_filter: typing.Optional[str] = None,
        disconnect_reason_filter: typing.Optional[str] = None,
        call_attempt_filter: typing.Optional[str] = None,
        duration_filter: typing.Optional[str] = None,
        request_options: typing.Optional[RequestOptions] = None,
    ) -> AsyncHttpResponse[GetConversationResponse]:
        """
        Retrieve paginated conversation logs with support for various filters. Returns call logs for agents belonging to the authenticated user's organization.

        Parameters
        ----------
        page : typing.Optional[int]
            Page number for pagination

        limit : typing.Optional[int]
            Number of items per page

        agent_ids : typing.Optional[str]
            Comma-separated list of agent IDs to filter by

        campaign_ids : typing.Optional[str]
            Comma-separated list of campaign IDs to filter by

        call_types : typing.Optional[GetConversationRequestCallTypes]
            Comma-separated list of call types to filter by

        search : typing.Optional[str]
            Search query to filter by callId, fromNumber, or toNumber

        status_filter : typing.Optional[str]
            Comma-separated list of call statuses to filter by.
            Available statuses: pending, in_progress, completed, failed, no_answer, cancelled, busy

        disconnect_reason_filter : typing.Optional[str]
            Comma-separated list of disconnect reasons to filter by.
            Available reasons: user_hangup, agent_hangup, connection_error, timeout, system_error, transfer_complete

        call_attempt_filter : typing.Optional[str]
            Comma-separated list of call attempt types to filter by.
            Available filters: initial (first attempt calls), retry (retry attempt calls), all (all calls)

        duration_filter : typing.Optional[str]
            Comma-separated list of duration ranges to filter by.
            Available ranges: 0-30 (0-30 seconds), 30-60 (30-60 seconds), 1-5 (1-5 minutes), 5+ (more than 5 minutes)

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

        Returns
        -------
        AsyncHttpResponse[GetConversationResponse]
            Successful response
        """
        _response = await self._client_wrapper.httpx_client.request(
            "conversation",
            base_url=self._client_wrapper.get_environment().atoms,
            method="GET",
            params={
                "page": page,
                "limit": limit,
                "agentIds": agent_ids,
                "campaignIds": campaign_ids,
                "callTypes": call_types,
                "search": search,
                "statusFilter": status_filter,
                "disconnectReasonFilter": disconnect_reason_filter,
                "callAttemptFilter": call_attempt_filter,
                "durationFilter": duration_filter,
            },
            request_options=request_options,
        )
        try:
            if 200 <= _response.status_code < 300:
                _data = typing.cast(
                    GetConversationResponse,
                    construct_type(
                        type_=GetConversationResponse,  # type: ignore
                        object_=_response.json(),
                    ),
                )
                return AsyncHttpResponse(response=_response, data=_data)
            if _response.status_code == 400:
                raise BadRequestError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        typing.Any,
                        construct_type(
                            type_=typing.Any,  # type: ignore
                            object_=_response.json(),
                        ),
                    ),
                )
            if _response.status_code == 401:
                raise UnauthorizedError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        typing.Any,
                        construct_type(
                            type_=typing.Any,  # type: ignore
                            object_=_response.json(),
                        ),
                    ),
                )
            if _response.status_code == 500:
                raise InternalServerError(
                    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 search_conversation_logs_by_call_i_ds(
        self, *, call_ids: typing.Sequence[str], request_options: typing.Optional[RequestOptions] = None
    ) -> AsyncHttpResponse[PostConversationSearchResponse]:
        """
        Fetch specific conversation logs by their callIds. This endpoint allows you to retrieve up to 100 specific calls at once.
        Only returns calls that belong to agents in your organization (security check enforced).
        Unlike the GET /conversation endpoint, this endpoint can also return retry calls (non-root calls).

        Parameters
        ----------
        call_ids : typing.Sequence[str]
            Array of callIds to fetch

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

        Returns
        -------
        AsyncHttpResponse[PostConversationSearchResponse]
            Successful response
        """
        _response = await self._client_wrapper.httpx_client.request(
            "conversation/search",
            base_url=self._client_wrapper.get_environment().atoms,
            method="POST",
            json={
                "callIds": call_ids,
            },
            headers={
                "content-type": "application/json",
            },
            request_options=request_options,
            omit=OMIT,
        )
        try:
            if 200 <= _response.status_code < 300:
                _data = typing.cast(
                    PostConversationSearchResponse,
                    construct_type(
                        type_=PostConversationSearchResponse,  # type: ignore
                        object_=_response.json(),
                    ),
                )
                return AsyncHttpResponse(response=_response, data=_data)
            if _response.status_code == 400:
                raise BadRequestError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        typing.Any,
                        construct_type(
                            type_=typing.Any,  # type: ignore
                            object_=_response.json(),
                        ),
                    ),
                )
            if _response.status_code == 401:
                raise UnauthorizedError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        typing.Any,
                        construct_type(
                            type_=typing.Any,  # type: ignore
                            object_=_response.json(),
                        ),
                    ),
                )
            if _response.status_code == 500:
                raise InternalServerError(
                    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_conversation_log_by_id(
        self, id: str, *, request_options: typing.Optional[RequestOptions] = None
    ) -> AsyncHttpResponse[GetConversationIdResponse]:
        """
        Retrieve detailed information about a specific conversation including transcript, events, and latency metrics.

        Parameters
        ----------
        id : str
            The callId of the conversation. You can get the callId from the conversation logs endpoint.

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

        Returns
        -------
        AsyncHttpResponse[GetConversationIdResponse]
            Successful response
        """
        _response = await self._client_wrapper.httpx_client.request(
            f"conversation/{jsonable_encoder(id)}",
            base_url=self._client_wrapper.get_environment().atoms,
            method="GET",
            request_options=request_options,
        )
        try:
            if 200 <= _response.status_code < 300:
                _data = typing.cast(
                    GetConversationIdResponse,
                    construct_type(
                        type_=GetConversationIdResponse,  # type: ignore
                        object_=_response.json(),
                    ),
                )
                return AsyncHttpResponse(response=_response, data=_data)
            if _response.status_code == 400:
                raise BadRequestError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        typing.Any,
                        construct_type(
                            type_=typing.Any,  # type: ignore
                            object_=_response.json(),
                        ),
                    ),
                )
            if _response.status_code == 401:
                raise UnauthorizedError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        typing.Any,
                        construct_type(
                            type_=typing.Any,  # type: ignore
                            object_=_response.json(),
                        ),
                    ),
                )
            if _response.status_code == 500:
                raise InternalServerError(
                    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)
