# 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.request_options import RequestOptions
from ....core.unchecked_base_model import construct_type
from ....errors.unprocessable_entity_error import UnprocessableEntityError
from ....types.conversation_initiation_source import ConversationInitiationSource
from ....types.conversation_product import ConversationProduct
from ....types.evaluation_success_result import EvaluationSuccessResult
from ....types.message_search_sort_by import MessageSearchSortBy
from ....types.messages_search_response import MessagesSearchResponse
from .types.messages_text_search_request_summary_mode import MessagesTextSearchRequestSummaryMode


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

    def text_search(
        self,
        *,
        text_query: str,
        agent_id: typing.Optional[str] = None,
        call_successful: typing.Optional[EvaluationSuccessResult] = None,
        call_start_before_unix: typing.Optional[int] = None,
        call_start_after_unix: typing.Optional[int] = None,
        call_duration_min_secs: typing.Optional[int] = None,
        call_duration_max_secs: typing.Optional[int] = None,
        rating_max: typing.Optional[int] = None,
        rating_min: typing.Optional[int] = None,
        has_feedback_comment: typing.Optional[bool] = None,
        user_id: typing.Optional[str] = None,
        evaluation_params: typing.Optional[typing.Union[str, typing.Sequence[str]]] = None,
        data_collection_params: typing.Optional[typing.Union[str, typing.Sequence[str]]] = None,
        tool_names: typing.Optional[typing.Union[str, typing.Sequence[str]]] = None,
        tool_names_successful: typing.Optional[typing.Union[str, typing.Sequence[str]]] = None,
        tool_names_errored: typing.Optional[typing.Union[str, typing.Sequence[str]]] = None,
        main_languages: typing.Optional[typing.Union[str, typing.Sequence[str]]] = None,
        page_size: typing.Optional[int] = None,
        summary_mode: typing.Optional[MessagesTextSearchRequestSummaryMode] = None,
        conversation_initiation_source: typing.Optional[ConversationInitiationSource] = None,
        text_only: typing.Optional[bool] = None,
        conversation_product_type: typing.Optional[ConversationProduct] = None,
        branch_id: typing.Optional[str] = None,
        topic_ids: typing.Optional[typing.Union[str, typing.Sequence[str]]] = None,
        sort_by: typing.Optional[MessageSearchSortBy] = None,
        cursor: typing.Optional[str] = None,
        request_options: typing.Optional[RequestOptions] = None,
    ) -> HttpResponse[MessagesSearchResponse]:
        """
        Search through conversation transcript messages by full-text and fuzzy search

        Parameters
        ----------
        text_query : str
            The search query text for full-text and fuzzy matching

        agent_id : typing.Optional[str]
            Agent id (agent_…) or speech engine external id (seng_), resolved to the same underlying resource.

        call_successful : typing.Optional[EvaluationSuccessResult]
            The result of the success evaluation

        call_start_before_unix : typing.Optional[int]
            Unix timestamp (in seconds) to filter conversations up to this start date.

        call_start_after_unix : typing.Optional[int]
            Unix timestamp (in seconds) to filter conversations after to this start date.

        call_duration_min_secs : typing.Optional[int]
            Minimum call duration in seconds.

        call_duration_max_secs : typing.Optional[int]
            Maximum call duration in seconds.

        rating_max : typing.Optional[int]
            Maximum overall rating (1-5).

        rating_min : typing.Optional[int]
            Minimum overall rating (1-5).

        has_feedback_comment : typing.Optional[bool]
            Filter conversations with user feedback comments.

        user_id : typing.Optional[str]
            Filter conversations by the user ID who initiated them.

        evaluation_params : typing.Optional[typing.Union[str, typing.Sequence[str]]]
            Evaluation filters. Repeat param. Format: criteria_id:result. Example: eval=value_framing:success

        data_collection_params : typing.Optional[typing.Union[str, typing.Sequence[str]]]
            Data collection filters. Repeat param. Format: id:op:value where op is one of eq|neq|gt|gte|lt|lte|in|exists|missing. For in, pipe-delimit values.

        tool_names : typing.Optional[typing.Union[str, typing.Sequence[str]]]
            Filter conversations by tool names used during the call.

        tool_names_successful : typing.Optional[typing.Union[str, typing.Sequence[str]]]
            Filter conversations by tool names that had successful calls.

        tool_names_errored : typing.Optional[typing.Union[str, typing.Sequence[str]]]
            Filter conversations by tool names that had errored calls.

        main_languages : typing.Optional[typing.Union[str, typing.Sequence[str]]]
            Filter conversations by detected main language (language code).

        page_size : typing.Optional[int]
            Number of results per page. Max 50.

        summary_mode : typing.Optional[MessagesTextSearchRequestSummaryMode]
            Whether to include transcript summaries in the response.

        conversation_initiation_source : typing.Optional[ConversationInitiationSource]

        text_only : typing.Optional[bool]

        conversation_product_type : typing.Optional[ConversationProduct]
            Restrict results to a single conversation product surface.

        branch_id : typing.Optional[str]
            Filter conversations by branch ID.

        topic_ids : typing.Optional[typing.Union[str, typing.Sequence[str]]]
            Filter conversations by topic IDs assigned during topic discovery.

        sort_by : typing.Optional[MessageSearchSortBy]
            Sort order for search results. 'search_score' sorts by search score, 'created_at' sorts by conversation start time.

        cursor : typing.Optional[str]
            Used for fetching next page. Cursor is returned in the response.

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

        Returns
        -------
        HttpResponse[MessagesSearchResponse]
            Successful Response
        """
        _response = self._client_wrapper.httpx_client.request(
            "v1/convai/conversations/messages/text-search",
            method="GET",
            params={
                "text_query": text_query,
                "agent_id": agent_id,
                "call_successful": call_successful,
                "call_start_before_unix": call_start_before_unix,
                "call_start_after_unix": call_start_after_unix,
                "call_duration_min_secs": call_duration_min_secs,
                "call_duration_max_secs": call_duration_max_secs,
                "rating_max": rating_max,
                "rating_min": rating_min,
                "has_feedback_comment": has_feedback_comment,
                "user_id": user_id,
                "evaluation_params": evaluation_params,
                "data_collection_params": data_collection_params,
                "tool_names": tool_names,
                "tool_names_successful": tool_names_successful,
                "tool_names_errored": tool_names_errored,
                "main_languages": main_languages,
                "page_size": page_size,
                "summary_mode": summary_mode,
                "conversation_initiation_source": conversation_initiation_source,
                "text_only": text_only,
                "conversation_product_type": conversation_product_type,
                "branch_id": branch_id,
                "topic_ids": topic_ids,
                "sort_by": sort_by,
                "cursor": cursor,
            },
            request_options=request_options,
        )
        try:
            if 200 <= _response.status_code < 300:
                _data = typing.cast(
                    MessagesSearchResponse,
                    construct_type(
                        type_=MessagesSearchResponse,  # 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 search(
        self,
        *,
        text_query: str,
        agent_id: typing.Optional[str] = None,
        page_size: typing.Optional[int] = None,
        cursor: typing.Optional[str] = None,
        request_options: typing.Optional[RequestOptions] = None,
    ) -> HttpResponse[MessagesSearchResponse]:
        """
        Search conversation transcripts by semantic similarity to surface relevant messages based on meaning and intent, rather than exact keyword matches

        Parameters
        ----------
        text_query : str
            The search query text for semantic similarity matching

        agent_id : typing.Optional[str]
            Agent id (agent_…) or speech engine external id (seng_), resolved to the same underlying resource.

        page_size : typing.Optional[int]
            Number of results per page. Max 50.

        cursor : typing.Optional[str]
            Used for fetching next page. Cursor is returned in the response.

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

        Returns
        -------
        HttpResponse[MessagesSearchResponse]
            Successful Response
        """
        _response = self._client_wrapper.httpx_client.request(
            "v1/convai/conversations/messages/smart-search",
            method="GET",
            params={
                "text_query": text_query,
                "agent_id": agent_id,
                "page_size": page_size,
                "cursor": cursor,
            },
            request_options=request_options,
        )
        try:
            if 200 <= _response.status_code < 300:
                _data = typing.cast(
                    MessagesSearchResponse,
                    construct_type(
                        type_=MessagesSearchResponse,  # 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 AsyncRawMessagesClient:
    def __init__(self, *, client_wrapper: AsyncClientWrapper):
        self._client_wrapper = client_wrapper

    async def text_search(
        self,
        *,
        text_query: str,
        agent_id: typing.Optional[str] = None,
        call_successful: typing.Optional[EvaluationSuccessResult] = None,
        call_start_before_unix: typing.Optional[int] = None,
        call_start_after_unix: typing.Optional[int] = None,
        call_duration_min_secs: typing.Optional[int] = None,
        call_duration_max_secs: typing.Optional[int] = None,
        rating_max: typing.Optional[int] = None,
        rating_min: typing.Optional[int] = None,
        has_feedback_comment: typing.Optional[bool] = None,
        user_id: typing.Optional[str] = None,
        evaluation_params: typing.Optional[typing.Union[str, typing.Sequence[str]]] = None,
        data_collection_params: typing.Optional[typing.Union[str, typing.Sequence[str]]] = None,
        tool_names: typing.Optional[typing.Union[str, typing.Sequence[str]]] = None,
        tool_names_successful: typing.Optional[typing.Union[str, typing.Sequence[str]]] = None,
        tool_names_errored: typing.Optional[typing.Union[str, typing.Sequence[str]]] = None,
        main_languages: typing.Optional[typing.Union[str, typing.Sequence[str]]] = None,
        page_size: typing.Optional[int] = None,
        summary_mode: typing.Optional[MessagesTextSearchRequestSummaryMode] = None,
        conversation_initiation_source: typing.Optional[ConversationInitiationSource] = None,
        text_only: typing.Optional[bool] = None,
        conversation_product_type: typing.Optional[ConversationProduct] = None,
        branch_id: typing.Optional[str] = None,
        topic_ids: typing.Optional[typing.Union[str, typing.Sequence[str]]] = None,
        sort_by: typing.Optional[MessageSearchSortBy] = None,
        cursor: typing.Optional[str] = None,
        request_options: typing.Optional[RequestOptions] = None,
    ) -> AsyncHttpResponse[MessagesSearchResponse]:
        """
        Search through conversation transcript messages by full-text and fuzzy search

        Parameters
        ----------
        text_query : str
            The search query text for full-text and fuzzy matching

        agent_id : typing.Optional[str]
            Agent id (agent_…) or speech engine external id (seng_), resolved to the same underlying resource.

        call_successful : typing.Optional[EvaluationSuccessResult]
            The result of the success evaluation

        call_start_before_unix : typing.Optional[int]
            Unix timestamp (in seconds) to filter conversations up to this start date.

        call_start_after_unix : typing.Optional[int]
            Unix timestamp (in seconds) to filter conversations after to this start date.

        call_duration_min_secs : typing.Optional[int]
            Minimum call duration in seconds.

        call_duration_max_secs : typing.Optional[int]
            Maximum call duration in seconds.

        rating_max : typing.Optional[int]
            Maximum overall rating (1-5).

        rating_min : typing.Optional[int]
            Minimum overall rating (1-5).

        has_feedback_comment : typing.Optional[bool]
            Filter conversations with user feedback comments.

        user_id : typing.Optional[str]
            Filter conversations by the user ID who initiated them.

        evaluation_params : typing.Optional[typing.Union[str, typing.Sequence[str]]]
            Evaluation filters. Repeat param. Format: criteria_id:result. Example: eval=value_framing:success

        data_collection_params : typing.Optional[typing.Union[str, typing.Sequence[str]]]
            Data collection filters. Repeat param. Format: id:op:value where op is one of eq|neq|gt|gte|lt|lte|in|exists|missing. For in, pipe-delimit values.

        tool_names : typing.Optional[typing.Union[str, typing.Sequence[str]]]
            Filter conversations by tool names used during the call.

        tool_names_successful : typing.Optional[typing.Union[str, typing.Sequence[str]]]
            Filter conversations by tool names that had successful calls.

        tool_names_errored : typing.Optional[typing.Union[str, typing.Sequence[str]]]
            Filter conversations by tool names that had errored calls.

        main_languages : typing.Optional[typing.Union[str, typing.Sequence[str]]]
            Filter conversations by detected main language (language code).

        page_size : typing.Optional[int]
            Number of results per page. Max 50.

        summary_mode : typing.Optional[MessagesTextSearchRequestSummaryMode]
            Whether to include transcript summaries in the response.

        conversation_initiation_source : typing.Optional[ConversationInitiationSource]

        text_only : typing.Optional[bool]

        conversation_product_type : typing.Optional[ConversationProduct]
            Restrict results to a single conversation product surface.

        branch_id : typing.Optional[str]
            Filter conversations by branch ID.

        topic_ids : typing.Optional[typing.Union[str, typing.Sequence[str]]]
            Filter conversations by topic IDs assigned during topic discovery.

        sort_by : typing.Optional[MessageSearchSortBy]
            Sort order for search results. 'search_score' sorts by search score, 'created_at' sorts by conversation start time.

        cursor : typing.Optional[str]
            Used for fetching next page. Cursor is returned in the response.

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

        Returns
        -------
        AsyncHttpResponse[MessagesSearchResponse]
            Successful Response
        """
        _response = await self._client_wrapper.httpx_client.request(
            "v1/convai/conversations/messages/text-search",
            method="GET",
            params={
                "text_query": text_query,
                "agent_id": agent_id,
                "call_successful": call_successful,
                "call_start_before_unix": call_start_before_unix,
                "call_start_after_unix": call_start_after_unix,
                "call_duration_min_secs": call_duration_min_secs,
                "call_duration_max_secs": call_duration_max_secs,
                "rating_max": rating_max,
                "rating_min": rating_min,
                "has_feedback_comment": has_feedback_comment,
                "user_id": user_id,
                "evaluation_params": evaluation_params,
                "data_collection_params": data_collection_params,
                "tool_names": tool_names,
                "tool_names_successful": tool_names_successful,
                "tool_names_errored": tool_names_errored,
                "main_languages": main_languages,
                "page_size": page_size,
                "summary_mode": summary_mode,
                "conversation_initiation_source": conversation_initiation_source,
                "text_only": text_only,
                "conversation_product_type": conversation_product_type,
                "branch_id": branch_id,
                "topic_ids": topic_ids,
                "sort_by": sort_by,
                "cursor": cursor,
            },
            request_options=request_options,
        )
        try:
            if 200 <= _response.status_code < 300:
                _data = typing.cast(
                    MessagesSearchResponse,
                    construct_type(
                        type_=MessagesSearchResponse,  # 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 search(
        self,
        *,
        text_query: str,
        agent_id: typing.Optional[str] = None,
        page_size: typing.Optional[int] = None,
        cursor: typing.Optional[str] = None,
        request_options: typing.Optional[RequestOptions] = None,
    ) -> AsyncHttpResponse[MessagesSearchResponse]:
        """
        Search conversation transcripts by semantic similarity to surface relevant messages based on meaning and intent, rather than exact keyword matches

        Parameters
        ----------
        text_query : str
            The search query text for semantic similarity matching

        agent_id : typing.Optional[str]
            Agent id (agent_…) or speech engine external id (seng_), resolved to the same underlying resource.

        page_size : typing.Optional[int]
            Number of results per page. Max 50.

        cursor : typing.Optional[str]
            Used for fetching next page. Cursor is returned in the response.

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

        Returns
        -------
        AsyncHttpResponse[MessagesSearchResponse]
            Successful Response
        """
        _response = await self._client_wrapper.httpx_client.request(
            "v1/convai/conversations/messages/smart-search",
            method="GET",
            params={
                "text_query": text_query,
                "agent_id": agent_id,
                "page_size": page_size,
                "cursor": cursor,
            },
            request_options=request_options,
        )
        try:
            if 200 <= _response.status_code < 300:
                _data = typing.cast(
                    MessagesSearchResponse,
                    construct_type(
                        type_=MessagesSearchResponse,  # 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)
