# 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.pagination import AsyncPager, BaseHttpResponse, SyncPager
from ..core.pydantic_utilities import parse_obj_as
from ..core.request_options import RequestOptions
from ..core.serialization import convert_and_respect_annotation_metadata
from ..errors.bad_request_error import BadRequestError
from ..types.index_schema import IndexSchema
from .types.indexes_create_request_models_item import IndexesCreateRequestModelsItem
from .types.indexes_create_response import IndexesCreateResponse
from .types.indexes_list_response import IndexesListResponse

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


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

    def list(
        self,
        *,
        page: typing.Optional[int] = None,
        page_limit: typing.Optional[int] = None,
        sort_by: typing.Optional[str] = None,
        sort_option: typing.Optional[str] = None,
        index_name: typing.Optional[str] = None,
        model_options: typing.Optional[str] = None,
        model_family: typing.Optional[str] = None,
        created_at: typing.Optional[str] = None,
        updated_at: typing.Optional[str] = None,
        request_options: typing.Optional[RequestOptions] = None,
    ) -> SyncPager[IndexSchema]:
        """
        This method returns a list of the indexes in your account. The platform returns indexes sorted by creation date, with the oldest indexes at the top of the list.

        Parameters
        ----------
        page : typing.Optional[int]
            A number that identifies the page to retrieve.

            **Default**: `1`.

        page_limit : typing.Optional[int]
            The number of items to return on each page.

            **Default**: `10`.
            **Max**: `50`.

        sort_by : typing.Optional[str]
            The field to sort on. The following options are available:
            - `updated_at`: Sorts by the time, in the RFC 3339 format ("YYYY-MM-DDTHH:mm:ssZ"), when the item was updated.
            - `created_at`: Sorts by the time, in the RFC 3339 format ("YYYY-MM-DDTHH:mm:ssZ"), when the item was created.

            **Default**: `created_at`.

        sort_option : typing.Optional[str]
            The sorting direction. The following options are available:
            - `asc`
            - `desc`

            **Default**: `desc`.

        index_name : typing.Optional[str]
            Filter by the name of an index.

        model_options : typing.Optional[str]
            Filter by the model options. When filtering by multiple model options, the values must be comma-separated.

        model_family : typing.Optional[str]
            Filter by the model family. This parameter can take one of the following values: `marengo` or `pegasus`. You can specify a single value.

        created_at : typing.Optional[str]
            Filter indexes by the creation date and time, in the RFC 3339 format ("YYYY-MM-DDTHH:mm:ssZ"). The platform returns the indexes that were created on the specified date at or after the given time.

        updated_at : typing.Optional[str]
            Filter indexes by the last update date and time, in the RFC 3339 format ("YYYY-MM-DDTHH:mm:ssZ"). The platform returns the indexes that were last updated on the specified date at or after the given time.

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

        Returns
        -------
        SyncPager[IndexSchema]
            The indexes have successfully been retrieved.
        """
        page = page if page is not None else 1

        _response = self._client_wrapper.httpx_client.request(
            "indexes",
            method="GET",
            params={
                "page": page,
                "page_limit": page_limit,
                "sort_by": sort_by,
                "sort_option": sort_option,
                "index_name": index_name,
                "model_options": model_options,
                "model_family": model_family,
                "created_at": created_at,
                "updated_at": updated_at,
            },
            request_options=request_options,
        )
        try:
            if 200 <= _response.status_code < 300:
                _parsed_response = typing.cast(
                    IndexesListResponse,
                    parse_obj_as(
                        type_=IndexesListResponse,  # type: ignore
                        object_=_response.json(),
                    ),
                )
                _items = _parsed_response.data
                _has_next = True
                _get_next = lambda: self.list(
                    page=page + 1,
                    page_limit=page_limit,
                    sort_by=sort_by,
                    sort_option=sort_option,
                    index_name=index_name,
                    model_options=model_options,
                    model_family=model_family,
                    created_at=created_at,
                    updated_at=updated_at,
                    request_options=request_options,
                )
                return SyncPager(
                    has_next=_has_next, items=_items, get_next=_get_next, response=BaseHttpResponse(response=_response)
                )
            if _response.status_code == 400:
                raise BadRequestError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        typing.Optional[typing.Any],
                        parse_obj_as(
                            type_=typing.Optional[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 create(
        self,
        *,
        index_name: str,
        models: typing.Sequence[IndexesCreateRequestModelsItem],
        addons: typing.Optional[typing.Sequence[str]] = OMIT,
        request_options: typing.Optional[RequestOptions] = None,
    ) -> HttpResponse[IndexesCreateResponse]:
        """
        This method creates an index.

        Parameters
        ----------
        index_name : str
            The name of the index. Make sure you use a succinct and descriptive name.

        models : typing.Sequence[IndexesCreateRequestModelsItem]
            An array that specifies the [video understanding models](/v1.3/docs/concepts/models) and the [model options](/v1.3/docs/concepts/modalities#model-options) to be enabled for this index. Models determine what tasks you can perform with your videos. Model options determine which modalities the platform analyzes.

        addons : typing.Optional[typing.Sequence[str]]
            An array specifying which add-ons should be enabled. Each entry in the array is an addon, and the following values are supported:
            - `thumbnail`: Enables thumbnail generation.

            If you don't provide this parameter, no add-ons will be enabled.

            <Note title="Notes">
            - You can only enable addons when using the Marengo video understanding model.
            - You cannot disable an add-on once the index has been created.
            </Note>

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

        Returns
        -------
        HttpResponse[IndexesCreateResponse]
            An index has successfully been created
        """
        _response = self._client_wrapper.httpx_client.request(
            "indexes",
            method="POST",
            json={
                "index_name": index_name,
                "models": convert_and_respect_annotation_metadata(
                    object_=models, annotation=typing.Sequence[IndexesCreateRequestModelsItem], direction="write"
                ),
                "addons": addons,
            },
            headers={
                "content-type": "application/json",
            },
            request_options=request_options,
            omit=OMIT,
        )
        try:
            if 200 <= _response.status_code < 300:
                _data = typing.cast(
                    IndexesCreateResponse,
                    parse_obj_as(
                        type_=IndexesCreateResponse,  # 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.Optional[typing.Any],
                        parse_obj_as(
                            type_=typing.Optional[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 retrieve(
        self, index_id: str, *, request_options: typing.Optional[RequestOptions] = None
    ) -> HttpResponse[IndexSchema]:
        """
        This method retrieves details about the specified index.

        Parameters
        ----------
        index_id : str
            Unique identifier of the index to retrieve.

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

        Returns
        -------
        HttpResponse[IndexSchema]
            The specified index has successfully been retrieved.
        """
        _response = self._client_wrapper.httpx_client.request(
            f"indexes/{jsonable_encoder(index_id)}",
            method="GET",
            request_options=request_options,
        )
        try:
            if 200 <= _response.status_code < 300:
                _data = typing.cast(
                    IndexSchema,
                    parse_obj_as(
                        type_=IndexSchema,  # 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.Optional[typing.Any],
                        parse_obj_as(
                            type_=typing.Optional[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 update(
        self, index_id: str, *, index_name: str, request_options: typing.Optional[RequestOptions] = None
    ) -> HttpResponse[None]:
        """
        This method updates the name of the specified index.

        Parameters
        ----------
        index_id : str
            Unique identifier of the index to update.

        index_name : str
            The name of the index.

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

        Returns
        -------
        HttpResponse[None]
        """
        _response = self._client_wrapper.httpx_client.request(
            f"indexes/{jsonable_encoder(index_id)}",
            method="PUT",
            json={
                "index_name": index_name,
            },
            headers={
                "content-type": "application/json",
            },
            request_options=request_options,
            omit=OMIT,
        )
        try:
            if 200 <= _response.status_code < 300:
                return HttpResponse(response=_response, data=None)
            if _response.status_code == 400:
                raise BadRequestError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        typing.Optional[typing.Any],
                        parse_obj_as(
                            type_=typing.Optional[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, index_id: str, *, request_options: typing.Optional[RequestOptions] = None) -> HttpResponse[None]:
        """
        This method deletes the specified index and all the videos within it. This action cannot be undone.

        Parameters
        ----------
        index_id : str
            Unique identifier of the index to delete.

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

        Returns
        -------
        HttpResponse[None]
        """
        _response = self._client_wrapper.httpx_client.request(
            f"indexes/{jsonable_encoder(index_id)}",
            method="DELETE",
            request_options=request_options,
        )
        try:
            if 200 <= _response.status_code < 300:
                return HttpResponse(response=_response, data=None)
            if _response.status_code == 400:
                raise BadRequestError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        typing.Optional[typing.Any],
                        parse_obj_as(
                            type_=typing.Optional[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 AsyncRawIndexesClient:
    def __init__(self, *, client_wrapper: AsyncClientWrapper):
        self._client_wrapper = client_wrapper

    async def list(
        self,
        *,
        page: typing.Optional[int] = None,
        page_limit: typing.Optional[int] = None,
        sort_by: typing.Optional[str] = None,
        sort_option: typing.Optional[str] = None,
        index_name: typing.Optional[str] = None,
        model_options: typing.Optional[str] = None,
        model_family: typing.Optional[str] = None,
        created_at: typing.Optional[str] = None,
        updated_at: typing.Optional[str] = None,
        request_options: typing.Optional[RequestOptions] = None,
    ) -> AsyncPager[IndexSchema]:
        """
        This method returns a list of the indexes in your account. The platform returns indexes sorted by creation date, with the oldest indexes at the top of the list.

        Parameters
        ----------
        page : typing.Optional[int]
            A number that identifies the page to retrieve.

            **Default**: `1`.

        page_limit : typing.Optional[int]
            The number of items to return on each page.

            **Default**: `10`.
            **Max**: `50`.

        sort_by : typing.Optional[str]
            The field to sort on. The following options are available:
            - `updated_at`: Sorts by the time, in the RFC 3339 format ("YYYY-MM-DDTHH:mm:ssZ"), when the item was updated.
            - `created_at`: Sorts by the time, in the RFC 3339 format ("YYYY-MM-DDTHH:mm:ssZ"), when the item was created.

            **Default**: `created_at`.

        sort_option : typing.Optional[str]
            The sorting direction. The following options are available:
            - `asc`
            - `desc`

            **Default**: `desc`.

        index_name : typing.Optional[str]
            Filter by the name of an index.

        model_options : typing.Optional[str]
            Filter by the model options. When filtering by multiple model options, the values must be comma-separated.

        model_family : typing.Optional[str]
            Filter by the model family. This parameter can take one of the following values: `marengo` or `pegasus`. You can specify a single value.

        created_at : typing.Optional[str]
            Filter indexes by the creation date and time, in the RFC 3339 format ("YYYY-MM-DDTHH:mm:ssZ"). The platform returns the indexes that were created on the specified date at or after the given time.

        updated_at : typing.Optional[str]
            Filter indexes by the last update date and time, in the RFC 3339 format ("YYYY-MM-DDTHH:mm:ssZ"). The platform returns the indexes that were last updated on the specified date at or after the given time.

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

        Returns
        -------
        AsyncPager[IndexSchema]
            The indexes have successfully been retrieved.
        """
        page = page if page is not None else 1

        _response = await self._client_wrapper.httpx_client.request(
            "indexes",
            method="GET",
            params={
                "page": page,
                "page_limit": page_limit,
                "sort_by": sort_by,
                "sort_option": sort_option,
                "index_name": index_name,
                "model_options": model_options,
                "model_family": model_family,
                "created_at": created_at,
                "updated_at": updated_at,
            },
            request_options=request_options,
        )
        try:
            if 200 <= _response.status_code < 300:
                _parsed_response = typing.cast(
                    IndexesListResponse,
                    parse_obj_as(
                        type_=IndexesListResponse,  # type: ignore
                        object_=_response.json(),
                    ),
                )
                _items = _parsed_response.data
                _has_next = True

                async def _get_next():
                    return await self.list(
                        page=page + 1,
                        page_limit=page_limit,
                        sort_by=sort_by,
                        sort_option=sort_option,
                        index_name=index_name,
                        model_options=model_options,
                        model_family=model_family,
                        created_at=created_at,
                        updated_at=updated_at,
                        request_options=request_options,
                    )

                return AsyncPager(
                    has_next=_has_next, items=_items, get_next=_get_next, response=BaseHttpResponse(response=_response)
                )
            if _response.status_code == 400:
                raise BadRequestError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        typing.Optional[typing.Any],
                        parse_obj_as(
                            type_=typing.Optional[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 create(
        self,
        *,
        index_name: str,
        models: typing.Sequence[IndexesCreateRequestModelsItem],
        addons: typing.Optional[typing.Sequence[str]] = OMIT,
        request_options: typing.Optional[RequestOptions] = None,
    ) -> AsyncHttpResponse[IndexesCreateResponse]:
        """
        This method creates an index.

        Parameters
        ----------
        index_name : str
            The name of the index. Make sure you use a succinct and descriptive name.

        models : typing.Sequence[IndexesCreateRequestModelsItem]
            An array that specifies the [video understanding models](/v1.3/docs/concepts/models) and the [model options](/v1.3/docs/concepts/modalities#model-options) to be enabled for this index. Models determine what tasks you can perform with your videos. Model options determine which modalities the platform analyzes.

        addons : typing.Optional[typing.Sequence[str]]
            An array specifying which add-ons should be enabled. Each entry in the array is an addon, and the following values are supported:
            - `thumbnail`: Enables thumbnail generation.

            If you don't provide this parameter, no add-ons will be enabled.

            <Note title="Notes">
            - You can only enable addons when using the Marengo video understanding model.
            - You cannot disable an add-on once the index has been created.
            </Note>

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

        Returns
        -------
        AsyncHttpResponse[IndexesCreateResponse]
            An index has successfully been created
        """
        _response = await self._client_wrapper.httpx_client.request(
            "indexes",
            method="POST",
            json={
                "index_name": index_name,
                "models": convert_and_respect_annotation_metadata(
                    object_=models, annotation=typing.Sequence[IndexesCreateRequestModelsItem], direction="write"
                ),
                "addons": addons,
            },
            headers={
                "content-type": "application/json",
            },
            request_options=request_options,
            omit=OMIT,
        )
        try:
            if 200 <= _response.status_code < 300:
                _data = typing.cast(
                    IndexesCreateResponse,
                    parse_obj_as(
                        type_=IndexesCreateResponse,  # 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.Optional[typing.Any],
                        parse_obj_as(
                            type_=typing.Optional[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 retrieve(
        self, index_id: str, *, request_options: typing.Optional[RequestOptions] = None
    ) -> AsyncHttpResponse[IndexSchema]:
        """
        This method retrieves details about the specified index.

        Parameters
        ----------
        index_id : str
            Unique identifier of the index to retrieve.

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

        Returns
        -------
        AsyncHttpResponse[IndexSchema]
            The specified index has successfully been retrieved.
        """
        _response = await self._client_wrapper.httpx_client.request(
            f"indexes/{jsonable_encoder(index_id)}",
            method="GET",
            request_options=request_options,
        )
        try:
            if 200 <= _response.status_code < 300:
                _data = typing.cast(
                    IndexSchema,
                    parse_obj_as(
                        type_=IndexSchema,  # 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.Optional[typing.Any],
                        parse_obj_as(
                            type_=typing.Optional[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 update(
        self, index_id: str, *, index_name: str, request_options: typing.Optional[RequestOptions] = None
    ) -> AsyncHttpResponse[None]:
        """
        This method updates the name of the specified index.

        Parameters
        ----------
        index_id : str
            Unique identifier of the index to update.

        index_name : str
            The name of the index.

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

        Returns
        -------
        AsyncHttpResponse[None]
        """
        _response = await self._client_wrapper.httpx_client.request(
            f"indexes/{jsonable_encoder(index_id)}",
            method="PUT",
            json={
                "index_name": index_name,
            },
            headers={
                "content-type": "application/json",
            },
            request_options=request_options,
            omit=OMIT,
        )
        try:
            if 200 <= _response.status_code < 300:
                return AsyncHttpResponse(response=_response, data=None)
            if _response.status_code == 400:
                raise BadRequestError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        typing.Optional[typing.Any],
                        parse_obj_as(
                            type_=typing.Optional[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, index_id: str, *, request_options: typing.Optional[RequestOptions] = None
    ) -> AsyncHttpResponse[None]:
        """
        This method deletes the specified index and all the videos within it. This action cannot be undone.

        Parameters
        ----------
        index_id : str
            Unique identifier of the index to delete.

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

        Returns
        -------
        AsyncHttpResponse[None]
        """
        _response = await self._client_wrapper.httpx_client.request(
            f"indexes/{jsonable_encoder(index_id)}",
            method="DELETE",
            request_options=request_options,
        )
        try:
            if 200 <= _response.status_code < 300:
                return AsyncHttpResponse(response=_response, data=None)
            if _response.status_code == 400:
                raise BadRequestError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        typing.Optional[typing.Any],
                        parse_obj_as(
                            type_=typing.Optional[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)
