# 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.pagination import AsyncPager, 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 ..errors.forbidden_error import ForbiddenError
from ..types.bad_request_error_body import BadRequestErrorBody
from ..types.encoder import Encoder
from ..types.error import Error
from ..types.list_encoders_response import ListEncodersResponse
from ..types.remote_auth import RemoteAuth

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


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

    def list(
        self,
        *,
        filter: typing.Optional[str] = None,
        limit: typing.Optional[int] = None,
        page_key: typing.Optional[str] = None,
        request_timeout: typing.Optional[int] = None,
        request_timeout_millis: typing.Optional[int] = None,
        request_options: typing.Optional[RequestOptions] = None,
    ) -> HttpResponse[SyncPager[Encoder]]:
        """
        Encoders are used to store and retrieve from a corpus.

        Parameters
        ----------
        filter : typing.Optional[str]
            A regular expression against encoder names and descriptions.

        limit : typing.Optional[int]
            The maximum number of results to return in the list.

        page_key : typing.Optional[str]
            Used to retrieve the next page of encoders after the limit has been reached.

        request_timeout : typing.Optional[int]
            The API will make a best effort to complete the request in the specified seconds or time out.

        request_timeout_millis : typing.Optional[int]
            The API will make a best effort to complete the request in the specified milliseconds or time out.

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

        Returns
        -------
        HttpResponse[SyncPager[Encoder]]
            List of encoders.
        """
        _response = self._client_wrapper.httpx_client.request(
            "v2/encoders",
            base_url=self._client_wrapper.get_environment().default,
            method="GET",
            params={
                "filter": filter,
                "limit": limit,
                "page_key": page_key,
            },
            headers={
                "Request-Timeout": str(request_timeout) if request_timeout is not None else None,
                "Request-Timeout-Millis": str(request_timeout_millis) if request_timeout_millis is not None else None,
            },
            request_options=request_options,
        )
        try:
            if 200 <= _response.status_code < 300:
                _parsed_response = typing.cast(
                    ListEncodersResponse,
                    parse_obj_as(
                        type_=ListEncodersResponse,  # type: ignore
                        object_=_response.json(),
                    ),
                )
                _has_next = False
                _get_next = None
                if _parsed_response.metadata is not None:
                    _parsed_next = _parsed_response.metadata.page_key
                    _has_next = _parsed_next is not None and _parsed_next != ""
                    _get_next = lambda: self.list(
                        filter=filter,
                        limit=limit,
                        page_key=_parsed_next,
                        request_timeout=request_timeout,
                        request_timeout_millis=request_timeout_millis,
                        request_options=request_options,
                    )
                _items = _parsed_response.encoders
                return HttpResponse(
                    response=_response, data=SyncPager(has_next=_has_next, items=_items, get_next=_get_next)
                )
            if _response.status_code == 403:
                raise ForbiddenError(
                    typing.cast(
                        Error,
                        parse_obj_as(
                            type_=Error,  # type: ignore
                            object_=_response.json(),
                        ),
                    )
                )
            _response_json = _response.json()
        except JSONDecodeError:
            raise ApiError(status_code=_response.status_code, body=_response.text)
        raise ApiError(status_code=_response.status_code, body=_response_json)

    def create(
        self,
        *,
        name: str,
        description: str,
        uri: str,
        model: str,
        request_timeout: typing.Optional[int] = None,
        request_timeout_millis: typing.Optional[int] = None,
        output_dimensions: typing.Optional[int] = OMIT,
        auth: typing.Optional[RemoteAuth] = OMIT,
        request_options: typing.Optional[RequestOptions] = None,
    ) -> HttpResponse[Encoder]:
        """
        Create a new encoder.

        Parameters
        ----------
        name : str
            A unique name for the encoder

        description : str
            A description of what this encoder does

        uri : str
            The URI endpoint for the embedding API (can be OpenAI or any compatible embedding API endpoint)

        model : str
            The model name to use for embeddings

        request_timeout : typing.Optional[int]
            The API will make a best effort to complete the request in the specified seconds or time out.

        request_timeout_millis : typing.Optional[int]
            The API will make a best effort to complete the request in the specified milliseconds or time out.

        output_dimensions : typing.Optional[int]
            The number of dimensions in the output embedding vector. If provided and the model supports truncation,
            the response will be truncated to this number of dimensions.

        auth : typing.Optional[RemoteAuth]

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

        Returns
        -------
        HttpResponse[Encoder]
            The encoder has been created
        """
        _response = self._client_wrapper.httpx_client.request(
            "v2/encoders",
            base_url=self._client_wrapper.get_environment().default,
            method="POST",
            json={
                "name": name,
                "description": description,
                "output_dimensions": output_dimensions,
                "uri": uri,
                "model": model,
                "auth": convert_and_respect_annotation_metadata(object_=auth, annotation=RemoteAuth, direction="write"),
                "type": "openai-compatible",
            },
            headers={
                "Request-Timeout": str(request_timeout) if request_timeout is not None else None,
                "Request-Timeout-Millis": str(request_timeout_millis) if request_timeout_millis is not None else None,
            },
            request_options=request_options,
            omit=OMIT,
        )
        try:
            if 200 <= _response.status_code < 300:
                _data = typing.cast(
                    Encoder,
                    parse_obj_as(
                        type_=Encoder,  # type: ignore
                        object_=_response.json(),
                    ),
                )
                return HttpResponse(response=_response, data=_data)
            if _response.status_code == 400:
                raise BadRequestError(
                    typing.cast(
                        BadRequestErrorBody,
                        parse_obj_as(
                            type_=BadRequestErrorBody,  # type: ignore
                            object_=_response.json(),
                        ),
                    )
                )
            if _response.status_code == 403:
                raise ForbiddenError(
                    typing.cast(
                        Error,
                        parse_obj_as(
                            type_=Error,  # type: ignore
                            object_=_response.json(),
                        ),
                    )
                )
            _response_json = _response.json()
        except JSONDecodeError:
            raise ApiError(status_code=_response.status_code, body=_response.text)
        raise ApiError(status_code=_response.status_code, body=_response_json)


class AsyncRawEncodersClient:
    def __init__(self, *, client_wrapper: AsyncClientWrapper):
        self._client_wrapper = client_wrapper

    async def list(
        self,
        *,
        filter: typing.Optional[str] = None,
        limit: typing.Optional[int] = None,
        page_key: typing.Optional[str] = None,
        request_timeout: typing.Optional[int] = None,
        request_timeout_millis: typing.Optional[int] = None,
        request_options: typing.Optional[RequestOptions] = None,
    ) -> AsyncHttpResponse[AsyncPager[Encoder]]:
        """
        Encoders are used to store and retrieve from a corpus.

        Parameters
        ----------
        filter : typing.Optional[str]
            A regular expression against encoder names and descriptions.

        limit : typing.Optional[int]
            The maximum number of results to return in the list.

        page_key : typing.Optional[str]
            Used to retrieve the next page of encoders after the limit has been reached.

        request_timeout : typing.Optional[int]
            The API will make a best effort to complete the request in the specified seconds or time out.

        request_timeout_millis : typing.Optional[int]
            The API will make a best effort to complete the request in the specified milliseconds or time out.

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

        Returns
        -------
        AsyncHttpResponse[AsyncPager[Encoder]]
            List of encoders.
        """
        _response = await self._client_wrapper.httpx_client.request(
            "v2/encoders",
            base_url=self._client_wrapper.get_environment().default,
            method="GET",
            params={
                "filter": filter,
                "limit": limit,
                "page_key": page_key,
            },
            headers={
                "Request-Timeout": str(request_timeout) if request_timeout is not None else None,
                "Request-Timeout-Millis": str(request_timeout_millis) if request_timeout_millis is not None else None,
            },
            request_options=request_options,
        )
        try:
            if 200 <= _response.status_code < 300:
                _parsed_response = typing.cast(
                    ListEncodersResponse,
                    parse_obj_as(
                        type_=ListEncodersResponse,  # type: ignore
                        object_=_response.json(),
                    ),
                )
                _has_next = False
                _get_next = None
                if _parsed_response.metadata is not None:
                    _parsed_next = _parsed_response.metadata.page_key
                    _has_next = _parsed_next is not None and _parsed_next != ""
                    _get_next = lambda: self.list(
                        filter=filter,
                        limit=limit,
                        page_key=_parsed_next,
                        request_timeout=request_timeout,
                        request_timeout_millis=request_timeout_millis,
                        request_options=request_options,
                    )
                _items = _parsed_response.encoders
                return AsyncHttpResponse(
                    response=_response, data=AsyncPager(has_next=_has_next, items=_items, get_next=_get_next)
                )
            if _response.status_code == 403:
                raise ForbiddenError(
                    typing.cast(
                        Error,
                        parse_obj_as(
                            type_=Error,  # type: ignore
                            object_=_response.json(),
                        ),
                    )
                )
            _response_json = _response.json()
        except JSONDecodeError:
            raise ApiError(status_code=_response.status_code, body=_response.text)
        raise ApiError(status_code=_response.status_code, body=_response_json)

    async def create(
        self,
        *,
        name: str,
        description: str,
        uri: str,
        model: str,
        request_timeout: typing.Optional[int] = None,
        request_timeout_millis: typing.Optional[int] = None,
        output_dimensions: typing.Optional[int] = OMIT,
        auth: typing.Optional[RemoteAuth] = OMIT,
        request_options: typing.Optional[RequestOptions] = None,
    ) -> AsyncHttpResponse[Encoder]:
        """
        Create a new encoder.

        Parameters
        ----------
        name : str
            A unique name for the encoder

        description : str
            A description of what this encoder does

        uri : str
            The URI endpoint for the embedding API (can be OpenAI or any compatible embedding API endpoint)

        model : str
            The model name to use for embeddings

        request_timeout : typing.Optional[int]
            The API will make a best effort to complete the request in the specified seconds or time out.

        request_timeout_millis : typing.Optional[int]
            The API will make a best effort to complete the request in the specified milliseconds or time out.

        output_dimensions : typing.Optional[int]
            The number of dimensions in the output embedding vector. If provided and the model supports truncation,
            the response will be truncated to this number of dimensions.

        auth : typing.Optional[RemoteAuth]

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

        Returns
        -------
        AsyncHttpResponse[Encoder]
            The encoder has been created
        """
        _response = await self._client_wrapper.httpx_client.request(
            "v2/encoders",
            base_url=self._client_wrapper.get_environment().default,
            method="POST",
            json={
                "name": name,
                "description": description,
                "output_dimensions": output_dimensions,
                "uri": uri,
                "model": model,
                "auth": convert_and_respect_annotation_metadata(object_=auth, annotation=RemoteAuth, direction="write"),
                "type": "openai-compatible",
            },
            headers={
                "Request-Timeout": str(request_timeout) if request_timeout is not None else None,
                "Request-Timeout-Millis": str(request_timeout_millis) if request_timeout_millis is not None else None,
            },
            request_options=request_options,
            omit=OMIT,
        )
        try:
            if 200 <= _response.status_code < 300:
                _data = typing.cast(
                    Encoder,
                    parse_obj_as(
                        type_=Encoder,  # type: ignore
                        object_=_response.json(),
                    ),
                )
                return AsyncHttpResponse(response=_response, data=_data)
            if _response.status_code == 400:
                raise BadRequestError(
                    typing.cast(
                        BadRequestErrorBody,
                        parse_obj_as(
                            type_=BadRequestErrorBody,  # type: ignore
                            object_=_response.json(),
                        ),
                    )
                )
            if _response.status_code == 403:
                raise ForbiddenError(
                    typing.cast(
                        Error,
                        parse_obj_as(
                            type_=Error,  # type: ignore
                            object_=_response.json(),
                        ),
                    )
                )
            _response_json = _response.json()
        except JSONDecodeError:
            raise ApiError(status_code=_response.status_code, body=_response.text)
        raise ApiError(status_code=_response.status_code, body=_response_json)
