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

import typing
from json.decoder import JSONDecodeError

from ..commons.errors.bad_request_error import BadRequestError
from ..commons.errors.not_found_error import NotFoundError
from ..commons.errors.server_error import ServerError
from ..commons.types.entity_id_base import EntityIdBase
from ..commons.types.error_message import ErrorMessage
from ..commons.types.precondition import Precondition
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.pydantic_utilities import parse_obj_as
from ..core.request_options import RequestOptions
from ..core.serialization import convert_and_respect_annotation_metadata
from .types.segment_field import SegmentField
from .types.segment_response import SegmentResponse
from .types.segment_status import SegmentStatus
from .types.segments_search_response import SegmentsSearchResponse

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


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

    def search(
        self,
        *,
        sort: typing.Optional[SegmentField] = OMIT,
        page: typing.Optional[int] = OMIT,
        size: typing.Optional[int] = OMIT,
        sort_desc: typing.Optional[bool] = OMIT,
        request_options: typing.Optional[RequestOptions] = None,
    ) -> HttpResponse[SegmentsSearchResponse]:
        """
        Parameters
        ----------
        sort : typing.Optional[SegmentField]
            The field to sort by, defaults to created timestamp

        page : typing.Optional[int]
            Page number to return, defaults to 0

        size : typing.Optional[int]
            The size of the page to return, defaults to 20

        sort_desc : typing.Optional[bool]
            Whether to sort descending, defaults to true

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

        Returns
        -------
        HttpResponse[SegmentsSearchResponse]
        """
        _response = self._client_wrapper.httpx_client.request(
            "v1/segments",
            method="POST",
            json={
                "sort": sort,
                "page": page,
                "size": size,
                "sortDesc": sort_desc,
            },
            request_options=request_options,
            omit=OMIT,
        )
        try:
            if 200 <= _response.status_code < 300:
                _data = typing.cast(
                    SegmentsSearchResponse,
                    parse_obj_as(
                        type_=SegmentsSearchResponse,  # type: ignore
                        object_=_response.json(),
                    ),
                )
                return HttpResponse(response=_response, data=_data)
            if _response.status_code == 404:
                raise NotFoundError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        ErrorMessage,
                        parse_obj_as(
                            type_=ErrorMessage,  # type: ignore
                            object_=_response.json(),
                        ),
                    ),
                )
            if _response.status_code == 400:
                raise BadRequestError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        ErrorMessage,
                        parse_obj_as(
                            type_=ErrorMessage,  # type: ignore
                            object_=_response.json(),
                        ),
                    ),
                )
            if _response.status_code == 500:
                raise ServerError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        ErrorMessage,
                        parse_obj_as(
                            type_=ErrorMessage,  # 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 create_or_update(
        self,
        *,
        segment_id: EntityIdBase,
        name: str,
        precondition: Precondition,
        request_options: typing.Optional[RequestOptions] = None,
    ) -> HttpResponse[SegmentResponse]:
        """
        Update a segment or create it if it doesn't exist.

        Parameters
        ----------
        segment_id : EntityIdBase
            ID that uniquely identifies this segment

        name : str
            The name of the segment.

        precondition : Precondition
            The precondition that must be met for a conversation message to be included in the segment.

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

        Returns
        -------
        HttpResponse[SegmentResponse]
        """
        _response = self._client_wrapper.httpx_client.request(
            "v1/segments",
            method="PUT",
            json={
                "segmentId": convert_and_respect_annotation_metadata(
                    object_=segment_id, annotation=EntityIdBase, direction="write"
                ),
                "name": name,
                "precondition": convert_and_respect_annotation_metadata(
                    object_=precondition, annotation=Precondition, direction="write"
                ),
            },
            request_options=request_options,
            omit=OMIT,
        )
        try:
            if 200 <= _response.status_code < 300:
                _data = typing.cast(
                    SegmentResponse,
                    parse_obj_as(
                        type_=SegmentResponse,  # type: ignore
                        object_=_response.json(),
                    ),
                )
                return HttpResponse(response=_response, data=_data)
            if _response.status_code == 404:
                raise NotFoundError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        ErrorMessage,
                        parse_obj_as(
                            type_=ErrorMessage,  # type: ignore
                            object_=_response.json(),
                        ),
                    ),
                )
            if _response.status_code == 400:
                raise BadRequestError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        ErrorMessage,
                        parse_obj_as(
                            type_=ErrorMessage,  # type: ignore
                            object_=_response.json(),
                        ),
                    ),
                )
            if _response.status_code == 500:
                raise ServerError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        ErrorMessage,
                        parse_obj_as(
                            type_=ErrorMessage,  # 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,
        segment_reference_id: str,
        *,
        app_id: typing.Optional[str] = None,
        request_options: typing.Optional[RequestOptions] = None,
    ) -> HttpResponse[SegmentResponse]:
        """
        Get a segment by its supplied ID

        Parameters
        ----------
        segment_reference_id : str
            The reference ID of the segment to get. All other entity ID fields are inferred from the request.

        app_id : typing.Optional[str]
            The App ID of the segment to get. If not provided, the ID of the calling app will be used.

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

        Returns
        -------
        HttpResponse[SegmentResponse]
        """
        _response = self._client_wrapper.httpx_client.request(
            f"v1/segments/{jsonable_encoder(segment_reference_id)}",
            method="GET",
            params={
                "appId": app_id,
            },
            request_options=request_options,
        )
        try:
            if 200 <= _response.status_code < 300:
                _data = typing.cast(
                    SegmentResponse,
                    parse_obj_as(
                        type_=SegmentResponse,  # type: ignore
                        object_=_response.json(),
                    ),
                )
                return HttpResponse(response=_response, data=_data)
            if _response.status_code == 404:
                raise NotFoundError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        ErrorMessage,
                        parse_obj_as(
                            type_=ErrorMessage,  # type: ignore
                            object_=_response.json(),
                        ),
                    ),
                )
            if _response.status_code == 400:
                raise BadRequestError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        ErrorMessage,
                        parse_obj_as(
                            type_=ErrorMessage,  # type: ignore
                            object_=_response.json(),
                        ),
                    ),
                )
            if _response.status_code == 500:
                raise ServerError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        ErrorMessage,
                        parse_obj_as(
                            type_=ErrorMessage,  # 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 patch(
        self,
        segment_reference_id: str,
        *,
        app_id: typing.Optional[str] = OMIT,
        name: typing.Optional[str] = OMIT,
        precondition: typing.Optional[Precondition] = OMIT,
        status: typing.Optional[SegmentStatus] = OMIT,
        request_options: typing.Optional[RequestOptions] = None,
    ) -> HttpResponse[SegmentResponse]:
        """
        Update mutable segment fields

        The `appId` field can be provided to update a segment owned by a different app.
        All other fields will overwrite the existing value on the segment only if provided.

        Parameters
        ----------
        segment_reference_id : str
            The reference ID of the segment to update. All other entity ID fields are inferred from the request.

        app_id : typing.Optional[str]
            The App ID of the segment to update. If not provided, the ID of the calling app will be used.

        name : typing.Optional[str]
            The name of the segment.

        precondition : typing.Optional[Precondition]
            The precondition that must be met for a conversation message to be included in the segment.

        status : typing.Optional[SegmentStatus]
            The status of the segment. Segments can only be deactivated if they are not set on any actions or active knowledge bases.

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

        Returns
        -------
        HttpResponse[SegmentResponse]
            The updated segment
        """
        _response = self._client_wrapper.httpx_client.request(
            f"v1/segments/{jsonable_encoder(segment_reference_id)}",
            method="PATCH",
            json={
                "appId": app_id,
                "name": name,
                "precondition": convert_and_respect_annotation_metadata(
                    object_=precondition, annotation=Precondition, direction="write"
                ),
                "status": status,
            },
            headers={
                "content-type": "application/merge-patch+json",
            },
            request_options=request_options,
            omit=OMIT,
        )
        try:
            if 200 <= _response.status_code < 300:
                _data = typing.cast(
                    SegmentResponse,
                    parse_obj_as(
                        type_=SegmentResponse,  # type: ignore
                        object_=_response.json(),
                    ),
                )
                return HttpResponse(response=_response, data=_data)
            if _response.status_code == 404:
                raise NotFoundError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        ErrorMessage,
                        parse_obj_as(
                            type_=ErrorMessage,  # type: ignore
                            object_=_response.json(),
                        ),
                    ),
                )
            if _response.status_code == 400:
                raise BadRequestError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        ErrorMessage,
                        parse_obj_as(
                            type_=ErrorMessage,  # type: ignore
                            object_=_response.json(),
                        ),
                    ),
                )
            if _response.status_code == 500:
                raise ServerError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        ErrorMessage,
                        parse_obj_as(
                            type_=ErrorMessage,  # 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 AsyncRawSegmentsClient:
    def __init__(self, *, client_wrapper: AsyncClientWrapper):
        self._client_wrapper = client_wrapper

    async def search(
        self,
        *,
        sort: typing.Optional[SegmentField] = OMIT,
        page: typing.Optional[int] = OMIT,
        size: typing.Optional[int] = OMIT,
        sort_desc: typing.Optional[bool] = OMIT,
        request_options: typing.Optional[RequestOptions] = None,
    ) -> AsyncHttpResponse[SegmentsSearchResponse]:
        """
        Parameters
        ----------
        sort : typing.Optional[SegmentField]
            The field to sort by, defaults to created timestamp

        page : typing.Optional[int]
            Page number to return, defaults to 0

        size : typing.Optional[int]
            The size of the page to return, defaults to 20

        sort_desc : typing.Optional[bool]
            Whether to sort descending, defaults to true

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

        Returns
        -------
        AsyncHttpResponse[SegmentsSearchResponse]
        """
        _response = await self._client_wrapper.httpx_client.request(
            "v1/segments",
            method="POST",
            json={
                "sort": sort,
                "page": page,
                "size": size,
                "sortDesc": sort_desc,
            },
            request_options=request_options,
            omit=OMIT,
        )
        try:
            if 200 <= _response.status_code < 300:
                _data = typing.cast(
                    SegmentsSearchResponse,
                    parse_obj_as(
                        type_=SegmentsSearchResponse,  # type: ignore
                        object_=_response.json(),
                    ),
                )
                return AsyncHttpResponse(response=_response, data=_data)
            if _response.status_code == 404:
                raise NotFoundError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        ErrorMessage,
                        parse_obj_as(
                            type_=ErrorMessage,  # type: ignore
                            object_=_response.json(),
                        ),
                    ),
                )
            if _response.status_code == 400:
                raise BadRequestError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        ErrorMessage,
                        parse_obj_as(
                            type_=ErrorMessage,  # type: ignore
                            object_=_response.json(),
                        ),
                    ),
                )
            if _response.status_code == 500:
                raise ServerError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        ErrorMessage,
                        parse_obj_as(
                            type_=ErrorMessage,  # 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 create_or_update(
        self,
        *,
        segment_id: EntityIdBase,
        name: str,
        precondition: Precondition,
        request_options: typing.Optional[RequestOptions] = None,
    ) -> AsyncHttpResponse[SegmentResponse]:
        """
        Update a segment or create it if it doesn't exist.

        Parameters
        ----------
        segment_id : EntityIdBase
            ID that uniquely identifies this segment

        name : str
            The name of the segment.

        precondition : Precondition
            The precondition that must be met for a conversation message to be included in the segment.

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

        Returns
        -------
        AsyncHttpResponse[SegmentResponse]
        """
        _response = await self._client_wrapper.httpx_client.request(
            "v1/segments",
            method="PUT",
            json={
                "segmentId": convert_and_respect_annotation_metadata(
                    object_=segment_id, annotation=EntityIdBase, direction="write"
                ),
                "name": name,
                "precondition": convert_and_respect_annotation_metadata(
                    object_=precondition, annotation=Precondition, direction="write"
                ),
            },
            request_options=request_options,
            omit=OMIT,
        )
        try:
            if 200 <= _response.status_code < 300:
                _data = typing.cast(
                    SegmentResponse,
                    parse_obj_as(
                        type_=SegmentResponse,  # type: ignore
                        object_=_response.json(),
                    ),
                )
                return AsyncHttpResponse(response=_response, data=_data)
            if _response.status_code == 404:
                raise NotFoundError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        ErrorMessage,
                        parse_obj_as(
                            type_=ErrorMessage,  # type: ignore
                            object_=_response.json(),
                        ),
                    ),
                )
            if _response.status_code == 400:
                raise BadRequestError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        ErrorMessage,
                        parse_obj_as(
                            type_=ErrorMessage,  # type: ignore
                            object_=_response.json(),
                        ),
                    ),
                )
            if _response.status_code == 500:
                raise ServerError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        ErrorMessage,
                        parse_obj_as(
                            type_=ErrorMessage,  # 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,
        segment_reference_id: str,
        *,
        app_id: typing.Optional[str] = None,
        request_options: typing.Optional[RequestOptions] = None,
    ) -> AsyncHttpResponse[SegmentResponse]:
        """
        Get a segment by its supplied ID

        Parameters
        ----------
        segment_reference_id : str
            The reference ID of the segment to get. All other entity ID fields are inferred from the request.

        app_id : typing.Optional[str]
            The App ID of the segment to get. If not provided, the ID of the calling app will be used.

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

        Returns
        -------
        AsyncHttpResponse[SegmentResponse]
        """
        _response = await self._client_wrapper.httpx_client.request(
            f"v1/segments/{jsonable_encoder(segment_reference_id)}",
            method="GET",
            params={
                "appId": app_id,
            },
            request_options=request_options,
        )
        try:
            if 200 <= _response.status_code < 300:
                _data = typing.cast(
                    SegmentResponse,
                    parse_obj_as(
                        type_=SegmentResponse,  # type: ignore
                        object_=_response.json(),
                    ),
                )
                return AsyncHttpResponse(response=_response, data=_data)
            if _response.status_code == 404:
                raise NotFoundError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        ErrorMessage,
                        parse_obj_as(
                            type_=ErrorMessage,  # type: ignore
                            object_=_response.json(),
                        ),
                    ),
                )
            if _response.status_code == 400:
                raise BadRequestError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        ErrorMessage,
                        parse_obj_as(
                            type_=ErrorMessage,  # type: ignore
                            object_=_response.json(),
                        ),
                    ),
                )
            if _response.status_code == 500:
                raise ServerError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        ErrorMessage,
                        parse_obj_as(
                            type_=ErrorMessage,  # 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 patch(
        self,
        segment_reference_id: str,
        *,
        app_id: typing.Optional[str] = OMIT,
        name: typing.Optional[str] = OMIT,
        precondition: typing.Optional[Precondition] = OMIT,
        status: typing.Optional[SegmentStatus] = OMIT,
        request_options: typing.Optional[RequestOptions] = None,
    ) -> AsyncHttpResponse[SegmentResponse]:
        """
        Update mutable segment fields

        The `appId` field can be provided to update a segment owned by a different app.
        All other fields will overwrite the existing value on the segment only if provided.

        Parameters
        ----------
        segment_reference_id : str
            The reference ID of the segment to update. All other entity ID fields are inferred from the request.

        app_id : typing.Optional[str]
            The App ID of the segment to update. If not provided, the ID of the calling app will be used.

        name : typing.Optional[str]
            The name of the segment.

        precondition : typing.Optional[Precondition]
            The precondition that must be met for a conversation message to be included in the segment.

        status : typing.Optional[SegmentStatus]
            The status of the segment. Segments can only be deactivated if they are not set on any actions or active knowledge bases.

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

        Returns
        -------
        AsyncHttpResponse[SegmentResponse]
            The updated segment
        """
        _response = await self._client_wrapper.httpx_client.request(
            f"v1/segments/{jsonable_encoder(segment_reference_id)}",
            method="PATCH",
            json={
                "appId": app_id,
                "name": name,
                "precondition": convert_and_respect_annotation_metadata(
                    object_=precondition, annotation=Precondition, direction="write"
                ),
                "status": status,
            },
            headers={
                "content-type": "application/merge-patch+json",
            },
            request_options=request_options,
            omit=OMIT,
        )
        try:
            if 200 <= _response.status_code < 300:
                _data = typing.cast(
                    SegmentResponse,
                    parse_obj_as(
                        type_=SegmentResponse,  # type: ignore
                        object_=_response.json(),
                    ),
                )
                return AsyncHttpResponse(response=_response, data=_data)
            if _response.status_code == 404:
                raise NotFoundError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        ErrorMessage,
                        parse_obj_as(
                            type_=ErrorMessage,  # type: ignore
                            object_=_response.json(),
                        ),
                    ),
                )
            if _response.status_code == 400:
                raise BadRequestError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        ErrorMessage,
                        parse_obj_as(
                            type_=ErrorMessage,  # type: ignore
                            object_=_response.json(),
                        ),
                    ),
                )
            if _response.status_code == 500:
                raise ServerError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        ErrorMessage,
                        parse_obj_as(
                            type_=ErrorMessage,  # 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)
