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

import contextlib
import json
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.too_many_requests_error import TooManyRequestsError
from .types.analyze_max_tokens import AnalyzeMaxTokens
from .types.analyze_temperature import AnalyzeTemperature
from .types.analyze_text_prompt import AnalyzeTextPrompt
from .types.non_stream_analyze_response import NonStreamAnalyzeResponse
from .types.response_format import ResponseFormat
from .types.stream_analyze_response import StreamAnalyzeResponse
from .types.video_context import VideoContext

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


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

    @contextlib.contextmanager
    def analyze_stream(
        self,
        *,
        prompt: AnalyzeTextPrompt,
        video_id: typing.Optional[str] = OMIT,
        video: typing.Optional[VideoContext] = OMIT,
        temperature: typing.Optional[AnalyzeTemperature] = OMIT,
        response_format: typing.Optional[ResponseFormat] = OMIT,
        max_tokens: typing.Optional[AnalyzeMaxTokens] = OMIT,
        request_options: typing.Optional[RequestOptions] = None,
    ) -> typing.Iterator[HttpResponse[typing.Iterator[StreamAnalyzeResponse]]]:
        """
        This method synchronously analyzes your videos and generates fully customizable text based on your prompts.

        <Accordion title="Input requirements">
        - Minimum duration: 4 seconds
        - Maximum duration: 1 hour
        - Formats: [FFmpeg supported formats](https://ffmpeg.org/ffmpeg-formats.html)
        - Resolution: 360x360 to 5184x2160 pixels
        - Aspect ratio: Between 1:1 and 1:2.4, or between 2.4:1 and 1:1.
        </Accordion>

        **When to use this method**:
        - Analyze videos up to 1 hour
        - Retrieve immediate results without waiting for asynchronous processing
        - Stream text fragments in real-time for immediate processing and feedback

        **Do not use this method for**:
        - Videos longer than 1 hour. Use the [`POST`](/v1.3/api-reference/analyze-videos/create-async-analysis-task) method of the `/analyze/tasks` endpoint instead.

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

        Parameters
        ----------
        prompt : AnalyzeTextPrompt

        video_id : typing.Optional[str]
            The unique identifier of the video to analyze.

            <Info> This parameter will be deprecated and removed in a future version. Use the [`video`](/v1.3/api-reference/analyze-videos/sync-analysis#request.body.video) parameter instead.</Info>

        video : typing.Optional[VideoContext]

        temperature : typing.Optional[AnalyzeTemperature]

        response_format : typing.Optional[ResponseFormat]

        max_tokens : typing.Optional[AnalyzeMaxTokens]

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

        Yields
        ------
        typing.Iterator[HttpResponse[typing.Iterator[StreamAnalyzeResponse]]]

        """
        with self._client_wrapper.httpx_client.stream(
            "analyze",
            method="POST",
            json={
                "video_id": video_id,
                "video": convert_and_respect_annotation_metadata(
                    object_=video, annotation=VideoContext, direction="write"
                ),
                "prompt": prompt,
                "temperature": temperature,
                "response_format": convert_and_respect_annotation_metadata(
                    object_=response_format, annotation=ResponseFormat, direction="write"
                ),
                "max_tokens": max_tokens,
                "stream": True,
            },
            headers={
                "content-type": "application/json",
            },
            request_options=request_options,
            omit=OMIT,
        ) as _response:

            def _stream() -> HttpResponse[typing.Iterator[StreamAnalyzeResponse]]:
                try:
                    if 200 <= _response.status_code < 300:

                        def _iter():
                            for _text in _response.iter_lines():
                                try:
                                    if len(_text) == 0:
                                        continue
                                    yield typing.cast(
                                        StreamAnalyzeResponse,
                                        parse_obj_as(
                                            type_=StreamAnalyzeResponse,  # type: ignore
                                            object_=json.loads(_text),
                                        ),
                                    )
                                except Exception:
                                    pass
                            return

                        return HttpResponse(response=_response, data=_iter())
                    _response.read()
                    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(),
                                ),
                            ),
                        )
                    _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)

            yield _stream()

    def analyze(
        self,
        *,
        prompt: AnalyzeTextPrompt,
        video_id: typing.Optional[str] = OMIT,
        video: typing.Optional[VideoContext] = OMIT,
        temperature: typing.Optional[AnalyzeTemperature] = OMIT,
        response_format: typing.Optional[ResponseFormat] = OMIT,
        max_tokens: typing.Optional[AnalyzeMaxTokens] = OMIT,
        request_options: typing.Optional[RequestOptions] = None,
    ) -> HttpResponse[NonStreamAnalyzeResponse]:
        """
        This method synchronously analyzes your videos and generates fully customizable text based on your prompts.

        <Accordion title="Input requirements">
        - Minimum duration: 4 seconds
        - Maximum duration: 1 hour
        - Formats: [FFmpeg supported formats](https://ffmpeg.org/ffmpeg-formats.html)
        - Resolution: 360x360 to 5184x2160 pixels
        - Aspect ratio: Between 1:1 and 1:2.4, or between 2.4:1 and 1:1.
        </Accordion>

        **When to use this method**:
        - Analyze videos up to 1 hour
        - Retrieve immediate results without waiting for asynchronous processing
        - Stream text fragments in real-time for immediate processing and feedback

        **Do not use this method for**:
        - Videos longer than 1 hour. Use the [`POST`](/v1.3/api-reference/analyze-videos/create-async-analysis-task) method of the `/analyze/tasks` endpoint instead.

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

        Parameters
        ----------
        prompt : AnalyzeTextPrompt

        video_id : typing.Optional[str]
            The unique identifier of the video to analyze.

            <Info> This parameter will be deprecated and removed in a future version. Use the [`video`](/v1.3/api-reference/analyze-videos/sync-analysis#request.body.video) parameter instead.</Info>

        video : typing.Optional[VideoContext]

        temperature : typing.Optional[AnalyzeTemperature]

        response_format : typing.Optional[ResponseFormat]

        max_tokens : typing.Optional[AnalyzeMaxTokens]

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

        Returns
        -------
        HttpResponse[NonStreamAnalyzeResponse]

        """
        _response = self._client_wrapper.httpx_client.request(
            "analyze",
            method="POST",
            json={
                "video_id": video_id,
                "video": convert_and_respect_annotation_metadata(
                    object_=video, annotation=VideoContext, direction="write"
                ),
                "prompt": prompt,
                "temperature": temperature,
                "response_format": convert_and_respect_annotation_metadata(
                    object_=response_format, annotation=ResponseFormat, direction="write"
                ),
                "max_tokens": max_tokens,
                "stream": False,
            },
            headers={
                "content-type": "application/json",
            },
            request_options=request_options,
            omit=OMIT,
        )
        try:
            if 200 <= _response.status_code < 300:
                _data = typing.cast(
                    NonStreamAnalyzeResponse,
                    parse_obj_as(
                        type_=NonStreamAnalyzeResponse,  # 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(),
                        ),
                    ),
                )
            _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 AsyncRawBaseClient:
    def __init__(self, *, client_wrapper: AsyncClientWrapper):
        self._client_wrapper = client_wrapper

    @contextlib.asynccontextmanager
    async def analyze_stream(
        self,
        *,
        prompt: AnalyzeTextPrompt,
        video_id: typing.Optional[str] = OMIT,
        video: typing.Optional[VideoContext] = OMIT,
        temperature: typing.Optional[AnalyzeTemperature] = OMIT,
        response_format: typing.Optional[ResponseFormat] = OMIT,
        max_tokens: typing.Optional[AnalyzeMaxTokens] = OMIT,
        request_options: typing.Optional[RequestOptions] = None,
    ) -> typing.AsyncIterator[AsyncHttpResponse[typing.AsyncIterator[StreamAnalyzeResponse]]]:
        """
        This method synchronously analyzes your videos and generates fully customizable text based on your prompts.

        <Accordion title="Input requirements">
        - Minimum duration: 4 seconds
        - Maximum duration: 1 hour
        - Formats: [FFmpeg supported formats](https://ffmpeg.org/ffmpeg-formats.html)
        - Resolution: 360x360 to 5184x2160 pixels
        - Aspect ratio: Between 1:1 and 1:2.4, or between 2.4:1 and 1:1.
        </Accordion>

        **When to use this method**:
        - Analyze videos up to 1 hour
        - Retrieve immediate results without waiting for asynchronous processing
        - Stream text fragments in real-time for immediate processing and feedback

        **Do not use this method for**:
        - Videos longer than 1 hour. Use the [`POST`](/v1.3/api-reference/analyze-videos/create-async-analysis-task) method of the `/analyze/tasks` endpoint instead.

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

        Parameters
        ----------
        prompt : AnalyzeTextPrompt

        video_id : typing.Optional[str]
            The unique identifier of the video to analyze.

            <Info> This parameter will be deprecated and removed in a future version. Use the [`video`](/v1.3/api-reference/analyze-videos/sync-analysis#request.body.video) parameter instead.</Info>

        video : typing.Optional[VideoContext]

        temperature : typing.Optional[AnalyzeTemperature]

        response_format : typing.Optional[ResponseFormat]

        max_tokens : typing.Optional[AnalyzeMaxTokens]

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

        Yields
        ------
        typing.AsyncIterator[AsyncHttpResponse[typing.AsyncIterator[StreamAnalyzeResponse]]]

        """
        async with self._client_wrapper.httpx_client.stream(
            "analyze",
            method="POST",
            json={
                "video_id": video_id,
                "video": convert_and_respect_annotation_metadata(
                    object_=video, annotation=VideoContext, direction="write"
                ),
                "prompt": prompt,
                "temperature": temperature,
                "response_format": convert_and_respect_annotation_metadata(
                    object_=response_format, annotation=ResponseFormat, direction="write"
                ),
                "max_tokens": max_tokens,
                "stream": True,
            },
            headers={
                "content-type": "application/json",
            },
            request_options=request_options,
            omit=OMIT,
        ) as _response:

            async def _stream() -> AsyncHttpResponse[typing.AsyncIterator[StreamAnalyzeResponse]]:
                try:
                    if 200 <= _response.status_code < 300:

                        async def _iter():
                            async for _text in _response.aiter_lines():
                                try:
                                    if len(_text) == 0:
                                        continue
                                    yield typing.cast(
                                        StreamAnalyzeResponse,
                                        parse_obj_as(
                                            type_=StreamAnalyzeResponse,  # type: ignore
                                            object_=json.loads(_text),
                                        ),
                                    )
                                except Exception:
                                    pass
                            return

                        return AsyncHttpResponse(response=_response, data=_iter())
                    await _response.aread()
                    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(),
                                ),
                            ),
                        )
                    _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)

            yield await _stream()

    async def analyze(
        self,
        *,
        prompt: AnalyzeTextPrompt,
        video_id: typing.Optional[str] = OMIT,
        video: typing.Optional[VideoContext] = OMIT,
        temperature: typing.Optional[AnalyzeTemperature] = OMIT,
        response_format: typing.Optional[ResponseFormat] = OMIT,
        max_tokens: typing.Optional[AnalyzeMaxTokens] = OMIT,
        request_options: typing.Optional[RequestOptions] = None,
    ) -> AsyncHttpResponse[NonStreamAnalyzeResponse]:
        """
        This method synchronously analyzes your videos and generates fully customizable text based on your prompts.

        <Accordion title="Input requirements">
        - Minimum duration: 4 seconds
        - Maximum duration: 1 hour
        - Formats: [FFmpeg supported formats](https://ffmpeg.org/ffmpeg-formats.html)
        - Resolution: 360x360 to 5184x2160 pixels
        - Aspect ratio: Between 1:1 and 1:2.4, or between 2.4:1 and 1:1.
        </Accordion>

        **When to use this method**:
        - Analyze videos up to 1 hour
        - Retrieve immediate results without waiting for asynchronous processing
        - Stream text fragments in real-time for immediate processing and feedback

        **Do not use this method for**:
        - Videos longer than 1 hour. Use the [`POST`](/v1.3/api-reference/analyze-videos/create-async-analysis-task) method of the `/analyze/tasks` endpoint instead.

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

        Parameters
        ----------
        prompt : AnalyzeTextPrompt

        video_id : typing.Optional[str]
            The unique identifier of the video to analyze.

            <Info> This parameter will be deprecated and removed in a future version. Use the [`video`](/v1.3/api-reference/analyze-videos/sync-analysis#request.body.video) parameter instead.</Info>

        video : typing.Optional[VideoContext]

        temperature : typing.Optional[AnalyzeTemperature]

        response_format : typing.Optional[ResponseFormat]

        max_tokens : typing.Optional[AnalyzeMaxTokens]

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

        Returns
        -------
        AsyncHttpResponse[NonStreamAnalyzeResponse]

        """
        _response = await self._client_wrapper.httpx_client.request(
            "analyze",
            method="POST",
            json={
                "video_id": video_id,
                "video": convert_and_respect_annotation_metadata(
                    object_=video, annotation=VideoContext, direction="write"
                ),
                "prompt": prompt,
                "temperature": temperature,
                "response_format": convert_and_respect_annotation_metadata(
                    object_=response_format, annotation=ResponseFormat, direction="write"
                ),
                "max_tokens": max_tokens,
                "stream": False,
            },
            headers={
                "content-type": "application/json",
            },
            request_options=request_options,
            omit=OMIT,
        )
        try:
            if 200 <= _response.status_code < 300:
                _data = typing.cast(
                    NonStreamAnalyzeResponse,
                    parse_obj_as(
                        type_=NonStreamAnalyzeResponse,  # 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(),
                        ),
                    ),
                )
            _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)
