# 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.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.conflict_error import ConflictError
from ...errors.internal_server_error import InternalServerError
from ...errors.not_found_error import NotFoundError
from ...types.analyze_max_tokens import AnalyzeMaxTokens
from ...types.analyze_task_response import AnalyzeTaskResponse
from ...types.analyze_task_status import AnalyzeTaskStatus
from ...types.analyze_temperature import AnalyzeTemperature
from ...types.analyze_text_prompt import AnalyzeTextPrompt
from ...types.create_analyze_task_response import CreateAnalyzeTaskResponse
from ...types.error_response import ErrorResponse
from ...types.response_format import ResponseFormat
from ...types.video_context import VideoContext
from .types.tasks_list_response import TasksListResponse

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


class RawTasksClient:
    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,
        status: typing.Optional[AnalyzeTaskStatus] = None,
        request_options: typing.Optional[RequestOptions] = None,
    ) -> HttpResponse[TasksListResponse]:
        """
        This method returns a list of the analysis tasks in your account. The platform returns your analysis tasks sorted by creation date, with the newest 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`.

        status : typing.Optional[AnalyzeTaskStatus]
            Filter analysis tasks by status.
            Possible values: `queued`, `pending`, `processing`, `ready`, `failed`.

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

        Returns
        -------
        HttpResponse[TasksListResponse]
            A list of analysis tasks has successfully been retrieved.
        """
        _response = self._client_wrapper.httpx_client.request(
            "analyze/tasks",
            method="GET",
            params={
                "page": page,
                "page_limit": page_limit,
                "status": status,
            },
            request_options=request_options,
        )
        try:
            if 200 <= _response.status_code < 300:
                _data = typing.cast(
                    TasksListResponse,
                    parse_obj_as(
                        type_=TasksListResponse,  # 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 create(
        self,
        *,
        video: VideoContext,
        prompt: AnalyzeTextPrompt,
        temperature: typing.Optional[AnalyzeTemperature] = OMIT,
        max_tokens: typing.Optional[AnalyzeMaxTokens] = OMIT,
        response_format: typing.Optional[ResponseFormat] = OMIT,
        request_options: typing.Optional[RequestOptions] = None,
    ) -> HttpResponse[CreateAnalyzeTaskResponse]:
        """
        This method asynchronously analyzes your videos and generates fully customizable text based on your prompts.

        <Accordion title="Input requirements">
        - Minimum duration: 4 seconds
        - Maximum duration: 2 hours
        - 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 longer than 1 hour
        - Process videos asynchronously without blocking your application

        **Do not use this method for**:
        - Videos for which you need immediate results or real-time streaming. Use the [`POST`](/v1.3/api-reference/analyze-videos/sync-analysis) method of the `/analyze` endpoint instead.

        Analyzing videos asynchronously requires three steps:

        1. Create an analysis task using this method. The platform returns a task ID.
        2. Poll the status of the task using the [`GET`](/v1.3/api-reference/analyze-videos/retrieve-analysis-task-status-results) method of the `/analyze/tasks/{task_id}` endpoint. Wait until the status is `ready`.
        3. Retrieve the results from the response when the status is `ready` using the [`GET`](/v1.3/api-reference/analyze-videos/retrieve-analysis-task-status-results) method of the `/analyze/tasks/{task_id}` endpoint.

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

        Parameters
        ----------
        video : VideoContext

        prompt : AnalyzeTextPrompt

        temperature : typing.Optional[AnalyzeTemperature]

        max_tokens : typing.Optional[AnalyzeMaxTokens]

        response_format : typing.Optional[ResponseFormat]

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

        Returns
        -------
        HttpResponse[CreateAnalyzeTaskResponse]
            An analysis task has successfully been created.
        """
        _response = self._client_wrapper.httpx_client.request(
            "analyze/tasks",
            method="POST",
            json={
                "video": convert_and_respect_annotation_metadata(
                    object_=video, annotation=VideoContext, direction="write"
                ),
                "prompt": prompt,
                "temperature": temperature,
                "max_tokens": max_tokens,
                "response_format": convert_and_respect_annotation_metadata(
                    object_=response_format, annotation=ResponseFormat, direction="write"
                ),
            },
            headers={
                "content-type": "application/json",
            },
            request_options=request_options,
            omit=OMIT,
        )
        try:
            if 200 <= _response.status_code < 300:
                _data = typing.cast(
                    CreateAnalyzeTaskResponse,
                    parse_obj_as(
                        type_=CreateAnalyzeTaskResponse,  # 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 == 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)

    def retrieve(
        self, task_id: str, *, request_options: typing.Optional[RequestOptions] = None
    ) -> HttpResponse[AnalyzeTaskResponse]:
        """
        This method retrieves the status and results of an analysis task.

        **Task statuses**:
        - `queued`: The task is waiting to be processed.
        - `pending`: The task is queued and waiting to start.
        - `processing`: The platform is analyzing the video.
        - `ready`: Processing is complete. Results are available in the response.
        - `failed`: The task failed. No results were generated.

        Poll this method until `status` is `ready` or `failed`. When `status` is `ready`, use the results from the response.

        Parameters
        ----------
        task_id : str
            The unique identifier of the analysis task.

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

        Returns
        -------
        HttpResponse[AnalyzeTaskResponse]
            Task status and results retrieved successfully
        """
        _response = self._client_wrapper.httpx_client.request(
            f"analyze/tasks/{jsonable_encoder(task_id)}",
            method="GET",
            request_options=request_options,
        )
        try:
            if 200 <= _response.status_code < 300:
                _data = typing.cast(
                    AnalyzeTaskResponse,
                    parse_obj_as(
                        type_=AnalyzeTaskResponse,  # 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(
                        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, task_id: str, *, request_options: typing.Optional[RequestOptions] = None) -> HttpResponse[None]:
        """
        This method deletes an analysis task. You can only delete tasks that are not currently being processed.

        Parameters
        ----------
        task_id : str
            The unique identifier of the analyze task.

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

        Returns
        -------
        HttpResponse[None]
        """
        _response = self._client_wrapper.httpx_client.request(
            f"analyze/tasks/{jsonable_encoder(task_id)}",
            method="DELETE",
            request_options=request_options,
        )
        try:
            if 200 <= _response.status_code < 300:
                return HttpResponse(response=_response, data=None)
            if _response.status_code == 404:
                raise NotFoundError(
                    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 == 409:
                raise ConflictError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        ErrorResponse,
                        parse_obj_as(
                            type_=ErrorResponse,  # 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 AsyncRawTasksClient:
    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,
        status: typing.Optional[AnalyzeTaskStatus] = None,
        request_options: typing.Optional[RequestOptions] = None,
    ) -> AsyncHttpResponse[TasksListResponse]:
        """
        This method returns a list of the analysis tasks in your account. The platform returns your analysis tasks sorted by creation date, with the newest 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`.

        status : typing.Optional[AnalyzeTaskStatus]
            Filter analysis tasks by status.
            Possible values: `queued`, `pending`, `processing`, `ready`, `failed`.

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

        Returns
        -------
        AsyncHttpResponse[TasksListResponse]
            A list of analysis tasks has successfully been retrieved.
        """
        _response = await self._client_wrapper.httpx_client.request(
            "analyze/tasks",
            method="GET",
            params={
                "page": page,
                "page_limit": page_limit,
                "status": status,
            },
            request_options=request_options,
        )
        try:
            if 200 <= _response.status_code < 300:
                _data = typing.cast(
                    TasksListResponse,
                    parse_obj_as(
                        type_=TasksListResponse,  # 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 create(
        self,
        *,
        video: VideoContext,
        prompt: AnalyzeTextPrompt,
        temperature: typing.Optional[AnalyzeTemperature] = OMIT,
        max_tokens: typing.Optional[AnalyzeMaxTokens] = OMIT,
        response_format: typing.Optional[ResponseFormat] = OMIT,
        request_options: typing.Optional[RequestOptions] = None,
    ) -> AsyncHttpResponse[CreateAnalyzeTaskResponse]:
        """
        This method asynchronously analyzes your videos and generates fully customizable text based on your prompts.

        <Accordion title="Input requirements">
        - Minimum duration: 4 seconds
        - Maximum duration: 2 hours
        - 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 longer than 1 hour
        - Process videos asynchronously without blocking your application

        **Do not use this method for**:
        - Videos for which you need immediate results or real-time streaming. Use the [`POST`](/v1.3/api-reference/analyze-videos/sync-analysis) method of the `/analyze` endpoint instead.

        Analyzing videos asynchronously requires three steps:

        1. Create an analysis task using this method. The platform returns a task ID.
        2. Poll the status of the task using the [`GET`](/v1.3/api-reference/analyze-videos/retrieve-analysis-task-status-results) method of the `/analyze/tasks/{task_id}` endpoint. Wait until the status is `ready`.
        3. Retrieve the results from the response when the status is `ready` using the [`GET`](/v1.3/api-reference/analyze-videos/retrieve-analysis-task-status-results) method of the `/analyze/tasks/{task_id}` endpoint.

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

        Parameters
        ----------
        video : VideoContext

        prompt : AnalyzeTextPrompt

        temperature : typing.Optional[AnalyzeTemperature]

        max_tokens : typing.Optional[AnalyzeMaxTokens]

        response_format : typing.Optional[ResponseFormat]

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

        Returns
        -------
        AsyncHttpResponse[CreateAnalyzeTaskResponse]
            An analysis task has successfully been created.
        """
        _response = await self._client_wrapper.httpx_client.request(
            "analyze/tasks",
            method="POST",
            json={
                "video": convert_and_respect_annotation_metadata(
                    object_=video, annotation=VideoContext, direction="write"
                ),
                "prompt": prompt,
                "temperature": temperature,
                "max_tokens": max_tokens,
                "response_format": convert_and_respect_annotation_metadata(
                    object_=response_format, annotation=ResponseFormat, direction="write"
                ),
            },
            headers={
                "content-type": "application/json",
            },
            request_options=request_options,
            omit=OMIT,
        )
        try:
            if 200 <= _response.status_code < 300:
                _data = typing.cast(
                    CreateAnalyzeTaskResponse,
                    parse_obj_as(
                        type_=CreateAnalyzeTaskResponse,  # 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 == 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)

    async def retrieve(
        self, task_id: str, *, request_options: typing.Optional[RequestOptions] = None
    ) -> AsyncHttpResponse[AnalyzeTaskResponse]:
        """
        This method retrieves the status and results of an analysis task.

        **Task statuses**:
        - `queued`: The task is waiting to be processed.
        - `pending`: The task is queued and waiting to start.
        - `processing`: The platform is analyzing the video.
        - `ready`: Processing is complete. Results are available in the response.
        - `failed`: The task failed. No results were generated.

        Poll this method until `status` is `ready` or `failed`. When `status` is `ready`, use the results from the response.

        Parameters
        ----------
        task_id : str
            The unique identifier of the analysis task.

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

        Returns
        -------
        AsyncHttpResponse[AnalyzeTaskResponse]
            Task status and results retrieved successfully
        """
        _response = await self._client_wrapper.httpx_client.request(
            f"analyze/tasks/{jsonable_encoder(task_id)}",
            method="GET",
            request_options=request_options,
        )
        try:
            if 200 <= _response.status_code < 300:
                _data = typing.cast(
                    AnalyzeTaskResponse,
                    parse_obj_as(
                        type_=AnalyzeTaskResponse,  # 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(
                        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, task_id: str, *, request_options: typing.Optional[RequestOptions] = None
    ) -> AsyncHttpResponse[None]:
        """
        This method deletes an analysis task. You can only delete tasks that are not currently being processed.

        Parameters
        ----------
        task_id : str
            The unique identifier of the analyze task.

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

        Returns
        -------
        AsyncHttpResponse[None]
        """
        _response = await self._client_wrapper.httpx_client.request(
            f"analyze/tasks/{jsonable_encoder(task_id)}",
            method="DELETE",
            request_options=request_options,
        )
        try:
            if 200 <= _response.status_code < 300:
                return AsyncHttpResponse(response=_response, data=None)
            if _response.status_code == 404:
                raise NotFoundError(
                    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 == 409:
                raise ConflictError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        ErrorResponse,
                        parse_obj_as(
                            type_=ErrorResponse,  # 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)
