# 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.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.internal_server_error import InternalServerError
from ...errors.too_many_requests_error import TooManyRequestsError
from ...types.audio_input_request import AudioInputRequest
from ...types.embedding_success_response import EmbeddingSuccessResponse
from ...types.image_input_request import ImageInputRequest
from ...types.multi_input_request import MultiInputRequest
from ...types.text_image_input_request import TextImageInputRequest
from ...types.text_input_request import TextInputRequest
from ...types.video_input_request import VideoInputRequest
from .types.create_embeddings_request_input_type import CreateEmbeddingsRequestInputType
from .types.create_embeddings_request_model_name import CreateEmbeddingsRequestModelName

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


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

    def create(
        self,
        *,
        input_type: CreateEmbeddingsRequestInputType,
        model_name: CreateEmbeddingsRequestModelName,
        text: typing.Optional[TextInputRequest] = OMIT,
        image: typing.Optional[ImageInputRequest] = OMIT,
        text_image: typing.Optional[TextImageInputRequest] = OMIT,
        audio: typing.Optional[AudioInputRequest] = OMIT,
        video: typing.Optional[VideoInputRequest] = OMIT,
        multi_input: typing.Optional[MultiInputRequest] = OMIT,
        request_options: typing.Optional[RequestOptions] = None,
    ) -> HttpResponse[EmbeddingSuccessResponse]:
        """
        This endpoint synchronously creates embeddings for multimodal content and returns the results immediately in the response.

        **When to use this endpoint**:
        - Create embeddings for text, images, audio, or video content
        - Retrieve immediate results without waiting for background processing
        - Process audio or video content up to 10 minutes in duration

        **Do not use this endpoint for**:
        - Audio or video content longer than 10 minutes. Use the [`POST`](/v1.3/api-reference/create-embeddings-v2/create-async-embedding-task) method of the `/embed-v2/tasks` endpoint instead.

        <Accordion title="Input requirements">
          **Text**:
          - Maximum length: 500 tokens

          **Images**:
          - Formats: JPEG, PNG
          - Minimum size: 128x128 pixels
          - Maximum file size: 5 MB

          **Audio and video**:
          - Maximum duration: 10 minutes
          - Maximum file size for base64 encoded strings: 36 MB
          - Audio formats: WAV (uncompressed), MP3 (lossy), FLAC (lossless)
          - Video formats: [FFmpeg supported formats](https://ffmpeg.org/ffmpeg-formats.html)
          - Video resolution: 360x360 to 5184x2160 pixels
          - Aspect ratio: Between 1:1 and 1:2.4, or between 2.4:1 and 1:1
        </Accordion>

        <Note title="Note">
        This endpoint is rate-limited. For details, see the [Rate limits](/v1.3/docs/get-started/rate-limits) page.
        </Note>

        Parameters
        ----------
        input_type : CreateEmbeddingsRequestInputType
            The type of content for the embeddings.


            **Values**:
            - `audio`: Creates embeddings for an audio file
            - `video`: Creates embeddings for a video file
            - `image`: Creates embeddings for an image file
            - `text`: Creates embeddings for text input
            - `text_image`: Creates embeddings for text and an image
            - `multi_input`: Creates a single embedding from up to 10 images. You can optionally include text to provide context. To reference specific images in your text, use placeholders in the following format: `<@name>`, where `name` matches the `name` field of a media source

        model_name : CreateEmbeddingsRequestModelName
            The video understanding model to use. Value: "marengo3.0".

        text : typing.Optional[TextInputRequest]

        image : typing.Optional[ImageInputRequest]

        text_image : typing.Optional[TextImageInputRequest]

        audio : typing.Optional[AudioInputRequest]

        video : typing.Optional[VideoInputRequest]

        multi_input : typing.Optional[MultiInputRequest]

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

        Returns
        -------
        HttpResponse[EmbeddingSuccessResponse]
            Successful request; normal operation
        """
        _response = self._client_wrapper.httpx_client.request(
            "embed-v2",
            method="POST",
            json={
                "input_type": input_type,
                "model_name": model_name,
                "text": convert_and_respect_annotation_metadata(
                    object_=text, annotation=TextInputRequest, direction="write"
                ),
                "image": convert_and_respect_annotation_metadata(
                    object_=image, annotation=ImageInputRequest, direction="write"
                ),
                "text_image": convert_and_respect_annotation_metadata(
                    object_=text_image, annotation=TextImageInputRequest, direction="write"
                ),
                "audio": convert_and_respect_annotation_metadata(
                    object_=audio, annotation=AudioInputRequest, direction="write"
                ),
                "video": convert_and_respect_annotation_metadata(
                    object_=video, annotation=VideoInputRequest, direction="write"
                ),
                "multi_input": convert_and_respect_annotation_metadata(
                    object_=multi_input, annotation=MultiInputRequest, direction="write"
                ),
            },
            headers={
                "content-type": "application/json",
            },
            request_options=request_options,
            omit=OMIT,
        )
        try:
            if 200 <= _response.status_code < 300:
                _data = typing.cast(
                    EmbeddingSuccessResponse,
                    parse_obj_as(
                        type_=EmbeddingSuccessResponse,  # 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(),
                        ),
                    ),
                )
            if _response.status_code == 429:
                raise TooManyRequestsError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        typing.Optional[typing.Any],
                        parse_obj_as(
                            type_=typing.Optional[typing.Any],  # type: ignore
                            object_=_response.json(),
                        ),
                    ),
                )
            if _response.status_code == 500:
                raise InternalServerError(
                    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 AsyncRawV2Client:
    def __init__(self, *, client_wrapper: AsyncClientWrapper):
        self._client_wrapper = client_wrapper

    async def create(
        self,
        *,
        input_type: CreateEmbeddingsRequestInputType,
        model_name: CreateEmbeddingsRequestModelName,
        text: typing.Optional[TextInputRequest] = OMIT,
        image: typing.Optional[ImageInputRequest] = OMIT,
        text_image: typing.Optional[TextImageInputRequest] = OMIT,
        audio: typing.Optional[AudioInputRequest] = OMIT,
        video: typing.Optional[VideoInputRequest] = OMIT,
        multi_input: typing.Optional[MultiInputRequest] = OMIT,
        request_options: typing.Optional[RequestOptions] = None,
    ) -> AsyncHttpResponse[EmbeddingSuccessResponse]:
        """
        This endpoint synchronously creates embeddings for multimodal content and returns the results immediately in the response.

        **When to use this endpoint**:
        - Create embeddings for text, images, audio, or video content
        - Retrieve immediate results without waiting for background processing
        - Process audio or video content up to 10 minutes in duration

        **Do not use this endpoint for**:
        - Audio or video content longer than 10 minutes. Use the [`POST`](/v1.3/api-reference/create-embeddings-v2/create-async-embedding-task) method of the `/embed-v2/tasks` endpoint instead.

        <Accordion title="Input requirements">
          **Text**:
          - Maximum length: 500 tokens

          **Images**:
          - Formats: JPEG, PNG
          - Minimum size: 128x128 pixels
          - Maximum file size: 5 MB

          **Audio and video**:
          - Maximum duration: 10 minutes
          - Maximum file size for base64 encoded strings: 36 MB
          - Audio formats: WAV (uncompressed), MP3 (lossy), FLAC (lossless)
          - Video formats: [FFmpeg supported formats](https://ffmpeg.org/ffmpeg-formats.html)
          - Video resolution: 360x360 to 5184x2160 pixels
          - Aspect ratio: Between 1:1 and 1:2.4, or between 2.4:1 and 1:1
        </Accordion>

        <Note title="Note">
        This endpoint is rate-limited. For details, see the [Rate limits](/v1.3/docs/get-started/rate-limits) page.
        </Note>

        Parameters
        ----------
        input_type : CreateEmbeddingsRequestInputType
            The type of content for the embeddings.


            **Values**:
            - `audio`: Creates embeddings for an audio file
            - `video`: Creates embeddings for a video file
            - `image`: Creates embeddings for an image file
            - `text`: Creates embeddings for text input
            - `text_image`: Creates embeddings for text and an image
            - `multi_input`: Creates a single embedding from up to 10 images. You can optionally include text to provide context. To reference specific images in your text, use placeholders in the following format: `<@name>`, where `name` matches the `name` field of a media source

        model_name : CreateEmbeddingsRequestModelName
            The video understanding model to use. Value: "marengo3.0".

        text : typing.Optional[TextInputRequest]

        image : typing.Optional[ImageInputRequest]

        text_image : typing.Optional[TextImageInputRequest]

        audio : typing.Optional[AudioInputRequest]

        video : typing.Optional[VideoInputRequest]

        multi_input : typing.Optional[MultiInputRequest]

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

        Returns
        -------
        AsyncHttpResponse[EmbeddingSuccessResponse]
            Successful request; normal operation
        """
        _response = await self._client_wrapper.httpx_client.request(
            "embed-v2",
            method="POST",
            json={
                "input_type": input_type,
                "model_name": model_name,
                "text": convert_and_respect_annotation_metadata(
                    object_=text, annotation=TextInputRequest, direction="write"
                ),
                "image": convert_and_respect_annotation_metadata(
                    object_=image, annotation=ImageInputRequest, direction="write"
                ),
                "text_image": convert_and_respect_annotation_metadata(
                    object_=text_image, annotation=TextImageInputRequest, direction="write"
                ),
                "audio": convert_and_respect_annotation_metadata(
                    object_=audio, annotation=AudioInputRequest, direction="write"
                ),
                "video": convert_and_respect_annotation_metadata(
                    object_=video, annotation=VideoInputRequest, direction="write"
                ),
                "multi_input": convert_and_respect_annotation_metadata(
                    object_=multi_input, annotation=MultiInputRequest, direction="write"
                ),
            },
            headers={
                "content-type": "application/json",
            },
            request_options=request_options,
            omit=OMIT,
        )
        try:
            if 200 <= _response.status_code < 300:
                _data = typing.cast(
                    EmbeddingSuccessResponse,
                    parse_obj_as(
                        type_=EmbeddingSuccessResponse,  # 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(),
                        ),
                    ),
                )
            if _response.status_code == 429:
                raise TooManyRequestsError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        typing.Optional[typing.Any],
                        parse_obj_as(
                            type_=typing.Optional[typing.Any],  # type: ignore
                            object_=_response.json(),
                        ),
                    ),
                )
            if _response.status_code == 500:
                raise InternalServerError(
                    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)
