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

import typing
from json.decoder import JSONDecodeError

from ... import core
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.parse_error import ParsingError
from ...core.request_options import RequestOptions
from ...core.unchecked_base_model import construct_type
from ...errors.unprocessable_entity_error import UnprocessableEntityError
from ...types.dubbing_project_list_response import DubbingProjectListResponse
from ...types.dubbing_project_response import DubbingProjectResponse
from .types.project_create_request_model_id import ProjectCreateRequestModelId
from .types.project_list_request_sort_direction import ProjectListRequestSortDirection
from pydantic import ValidationError

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


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

    def list(
        self,
        *,
        cursor: typing.Optional[str] = None,
        page_size: typing.Optional[int] = None,
        status: typing.Optional[str] = None,
        sort_direction: typing.Optional[ProjectListRequestSortDirection] = None,
        request_options: typing.Optional[RequestOptions] = None,
    ) -> HttpResponse[DubbingProjectListResponse]:
        """
        List the workspace's dubbing projects (cursor-paginated).

        Parameters
        ----------
        cursor : typing.Optional[str]
            Pagination cursor from a previous response's next_cursor.

        page_size : typing.Optional[int]
            Number of projects per page (max 100).

        status : typing.Optional[str]
            Filter to projects in this status (preparing, ready, failed).

        sort_direction : typing.Optional[ProjectListRequestSortDirection]
            Sort by creation time (default 'DESCENDING').

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

        Returns
        -------
        HttpResponse[DubbingProjectListResponse]
            Successful Response
        """
        _response = self._client_wrapper.httpx_client.request(
            "v1/dubbing/project",
            method="GET",
            params={
                "cursor": cursor,
                "page_size": page_size,
                "status": status,
                "sort_direction": sort_direction,
            },
            request_options=request_options,
        )
        try:
            if 200 <= _response.status_code < 300:
                _data = typing.cast(
                    DubbingProjectListResponse,
                    construct_type(
                        type_=DubbingProjectListResponse,  # type: ignore
                        object_=_response.json(),
                    ),
                )
                return HttpResponse(response=_response, data=_data)
            if _response.status_code == 422:
                raise UnprocessableEntityError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        typing.Any,
                        construct_type(
                            type_=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)
        except ValidationError as e:
            raise ParsingError(
                status_code=_response.status_code, headers=dict(_response.headers), body=_response.json(), cause=e
            )
        raise ApiError(status_code=_response.status_code, headers=dict(_response.headers), body=_response_json)

    def create(
        self,
        *,
        file: typing.Optional[core.File] = OMIT,
        source_url: typing.Optional[str] = OMIT,
        reference: typing.Optional[str] = OMIT,
        source_language: typing.Optional[str] = OMIT,
        model_id: typing.Optional[ProjectCreateRequestModelId] = OMIT,
        keyterms: typing.Optional[typing.List[str]] = OMIT,
        webhook_ids: typing.Optional[typing.List[str]] = OMIT,
        target_language: typing.Optional[str] = OMIT,
        transcript: typing.Optional[core.File] = OMIT,
        request_options: typing.Optional[RequestOptions] = None,
    ) -> HttpResponse[DubbingProjectResponse]:
        """
        Create a dubbing project from an uploaded file or a source URL.

        Parameters
        ----------
        file : typing.Optional[core.File]
            See core.File for more documentation

        source_url : typing.Optional[str]
            Public URL to fetch the source media from. Provide this or file.

        reference : typing.Optional[str]
            Optional free-form string (max 500 characters) to identify the project on your end.

        source_language : typing.Optional[str]
            BCP-47 language tag of the source media; must be a language the transcription model supports. Any region or script subtag is ignored, since transcription is per-language. Omit to auto-detect.

        model_id : typing.Optional[ProjectCreateRequestModelId]
            Default dubbing model id ('dubbing_v1' or 'dubbing_v2') for the project's language targets; a target may override it. Omit to use the system default.

        keyterms : typing.Optional[typing.List[str]]
            Key terms to bias transcription/translation toward (e.g. product or brand names). At most 1000 terms; each term at most 50 characters and 5 words; the characters `<>{}[]\\` are not allowed.

        webhook_ids : typing.Optional[typing.List[str]]
            Ids of workspace webhooks to notify when this project becomes ready or fails, and when any of its languages completes or fails. At most 3; each must be a webhook configured in your workspace.

        target_language : typing.Optional[str]
            Optional shortcut: also create a language target in this BCP-47 language, queued to start once the project is ready. Must be a language the dubbing model supports, and a region-qualified tag must be one of the supported dialects.

        transcript : typing.Optional[core.File]
            See core.File for more documentation

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

        Returns
        -------
        HttpResponse[DubbingProjectResponse]
            Successful Response
        """
        _response = self._client_wrapper.httpx_client.request(
            "v1/dubbing/project",
            method="POST",
            data={
                "source_url": source_url,
                "reference": reference,
                "source_language": source_language,
                "model_id": model_id,
                "keyterms": keyterms,
                "webhook_ids": webhook_ids,
                "target_language": target_language,
            },
            files={
                **({"file": file} if file is not None else {}),
                **({"transcript": transcript} if transcript is not None else {}),
            },
            request_options=request_options,
            omit=OMIT,
            force_multipart=True,
        )
        try:
            if 200 <= _response.status_code < 300:
                _data = typing.cast(
                    DubbingProjectResponse,
                    construct_type(
                        type_=DubbingProjectResponse,  # type: ignore
                        object_=_response.json(),
                    ),
                )
                return HttpResponse(response=_response, data=_data)
            if _response.status_code == 422:
                raise UnprocessableEntityError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        typing.Any,
                        construct_type(
                            type_=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)
        except ValidationError as e:
            raise ParsingError(
                status_code=_response.status_code, headers=dict(_response.headers), body=_response.json(), cause=e
            )
        raise ApiError(status_code=_response.status_code, headers=dict(_response.headers), body=_response_json)

    def get(
        self, project_id: str, *, request_options: typing.Optional[RequestOptions] = None
    ) -> HttpResponse[DubbingProjectResponse]:
        """
        Full project detail, including its language target ids.

        Parameters
        ----------
        project_id : str
            Identifier of the dubbing project to fetch.

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

        Returns
        -------
        HttpResponse[DubbingProjectResponse]
            Successful Response
        """
        _response = self._client_wrapper.httpx_client.request(
            f"v1/dubbing/project/{jsonable_encoder(project_id)}",
            method="GET",
            request_options=request_options,
        )
        try:
            if 200 <= _response.status_code < 300:
                _data = typing.cast(
                    DubbingProjectResponse,
                    construct_type(
                        type_=DubbingProjectResponse,  # type: ignore
                        object_=_response.json(),
                    ),
                )
                return HttpResponse(response=_response, data=_data)
            if _response.status_code == 422:
                raise UnprocessableEntityError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        typing.Any,
                        construct_type(
                            type_=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)
        except ValidationError as e:
            raise ParsingError(
                status_code=_response.status_code, headers=dict(_response.headers), body=_response.json(), cause=e
            )
        raise ApiError(status_code=_response.status_code, headers=dict(_response.headers), body=_response_json)

    def delete(self, project_id: str, *, request_options: typing.Optional[RequestOptions] = None) -> HttpResponse[None]:
        """
        Delete a project and its language targets.

        Parameters
        ----------
        project_id : str
            Identifier of the dubbing project to delete.

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

        Returns
        -------
        HttpResponse[None]
        """
        _response = self._client_wrapper.httpx_client.request(
            f"v1/dubbing/project/{jsonable_encoder(project_id)}",
            method="DELETE",
            request_options=request_options,
        )
        try:
            if 200 <= _response.status_code < 300:
                return HttpResponse(response=_response, data=None)
            if _response.status_code == 422:
                raise UnprocessableEntityError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        typing.Any,
                        construct_type(
                            type_=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)
        except ValidationError as e:
            raise ParsingError(
                status_code=_response.status_code, headers=dict(_response.headers), body=_response.json(), cause=e
            )
        raise ApiError(status_code=_response.status_code, headers=dict(_response.headers), body=_response_json)


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

    async def list(
        self,
        *,
        cursor: typing.Optional[str] = None,
        page_size: typing.Optional[int] = None,
        status: typing.Optional[str] = None,
        sort_direction: typing.Optional[ProjectListRequestSortDirection] = None,
        request_options: typing.Optional[RequestOptions] = None,
    ) -> AsyncHttpResponse[DubbingProjectListResponse]:
        """
        List the workspace's dubbing projects (cursor-paginated).

        Parameters
        ----------
        cursor : typing.Optional[str]
            Pagination cursor from a previous response's next_cursor.

        page_size : typing.Optional[int]
            Number of projects per page (max 100).

        status : typing.Optional[str]
            Filter to projects in this status (preparing, ready, failed).

        sort_direction : typing.Optional[ProjectListRequestSortDirection]
            Sort by creation time (default 'DESCENDING').

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

        Returns
        -------
        AsyncHttpResponse[DubbingProjectListResponse]
            Successful Response
        """
        _response = await self._client_wrapper.httpx_client.request(
            "v1/dubbing/project",
            method="GET",
            params={
                "cursor": cursor,
                "page_size": page_size,
                "status": status,
                "sort_direction": sort_direction,
            },
            request_options=request_options,
        )
        try:
            if 200 <= _response.status_code < 300:
                _data = typing.cast(
                    DubbingProjectListResponse,
                    construct_type(
                        type_=DubbingProjectListResponse,  # type: ignore
                        object_=_response.json(),
                    ),
                )
                return AsyncHttpResponse(response=_response, data=_data)
            if _response.status_code == 422:
                raise UnprocessableEntityError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        typing.Any,
                        construct_type(
                            type_=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)
        except ValidationError as e:
            raise ParsingError(
                status_code=_response.status_code, headers=dict(_response.headers), body=_response.json(), cause=e
            )
        raise ApiError(status_code=_response.status_code, headers=dict(_response.headers), body=_response_json)

    async def create(
        self,
        *,
        file: typing.Optional[core.File] = OMIT,
        source_url: typing.Optional[str] = OMIT,
        reference: typing.Optional[str] = OMIT,
        source_language: typing.Optional[str] = OMIT,
        model_id: typing.Optional[ProjectCreateRequestModelId] = OMIT,
        keyterms: typing.Optional[typing.List[str]] = OMIT,
        webhook_ids: typing.Optional[typing.List[str]] = OMIT,
        target_language: typing.Optional[str] = OMIT,
        transcript: typing.Optional[core.File] = OMIT,
        request_options: typing.Optional[RequestOptions] = None,
    ) -> AsyncHttpResponse[DubbingProjectResponse]:
        """
        Create a dubbing project from an uploaded file or a source URL.

        Parameters
        ----------
        file : typing.Optional[core.File]
            See core.File for more documentation

        source_url : typing.Optional[str]
            Public URL to fetch the source media from. Provide this or file.

        reference : typing.Optional[str]
            Optional free-form string (max 500 characters) to identify the project on your end.

        source_language : typing.Optional[str]
            BCP-47 language tag of the source media; must be a language the transcription model supports. Any region or script subtag is ignored, since transcription is per-language. Omit to auto-detect.

        model_id : typing.Optional[ProjectCreateRequestModelId]
            Default dubbing model id ('dubbing_v1' or 'dubbing_v2') for the project's language targets; a target may override it. Omit to use the system default.

        keyterms : typing.Optional[typing.List[str]]
            Key terms to bias transcription/translation toward (e.g. product or brand names). At most 1000 terms; each term at most 50 characters and 5 words; the characters `<>{}[]\\` are not allowed.

        webhook_ids : typing.Optional[typing.List[str]]
            Ids of workspace webhooks to notify when this project becomes ready or fails, and when any of its languages completes or fails. At most 3; each must be a webhook configured in your workspace.

        target_language : typing.Optional[str]
            Optional shortcut: also create a language target in this BCP-47 language, queued to start once the project is ready. Must be a language the dubbing model supports, and a region-qualified tag must be one of the supported dialects.

        transcript : typing.Optional[core.File]
            See core.File for more documentation

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

        Returns
        -------
        AsyncHttpResponse[DubbingProjectResponse]
            Successful Response
        """
        _response = await self._client_wrapper.httpx_client.request(
            "v1/dubbing/project",
            method="POST",
            data={
                "source_url": source_url,
                "reference": reference,
                "source_language": source_language,
                "model_id": model_id,
                "keyterms": keyterms,
                "webhook_ids": webhook_ids,
                "target_language": target_language,
            },
            files={
                **({"file": file} if file is not None else {}),
                **({"transcript": transcript} if transcript is not None else {}),
            },
            request_options=request_options,
            omit=OMIT,
            force_multipart=True,
        )
        try:
            if 200 <= _response.status_code < 300:
                _data = typing.cast(
                    DubbingProjectResponse,
                    construct_type(
                        type_=DubbingProjectResponse,  # type: ignore
                        object_=_response.json(),
                    ),
                )
                return AsyncHttpResponse(response=_response, data=_data)
            if _response.status_code == 422:
                raise UnprocessableEntityError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        typing.Any,
                        construct_type(
                            type_=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)
        except ValidationError as e:
            raise ParsingError(
                status_code=_response.status_code, headers=dict(_response.headers), body=_response.json(), cause=e
            )
        raise ApiError(status_code=_response.status_code, headers=dict(_response.headers), body=_response_json)

    async def get(
        self, project_id: str, *, request_options: typing.Optional[RequestOptions] = None
    ) -> AsyncHttpResponse[DubbingProjectResponse]:
        """
        Full project detail, including its language target ids.

        Parameters
        ----------
        project_id : str
            Identifier of the dubbing project to fetch.

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

        Returns
        -------
        AsyncHttpResponse[DubbingProjectResponse]
            Successful Response
        """
        _response = await self._client_wrapper.httpx_client.request(
            f"v1/dubbing/project/{jsonable_encoder(project_id)}",
            method="GET",
            request_options=request_options,
        )
        try:
            if 200 <= _response.status_code < 300:
                _data = typing.cast(
                    DubbingProjectResponse,
                    construct_type(
                        type_=DubbingProjectResponse,  # type: ignore
                        object_=_response.json(),
                    ),
                )
                return AsyncHttpResponse(response=_response, data=_data)
            if _response.status_code == 422:
                raise UnprocessableEntityError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        typing.Any,
                        construct_type(
                            type_=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)
        except ValidationError as e:
            raise ParsingError(
                status_code=_response.status_code, headers=dict(_response.headers), body=_response.json(), cause=e
            )
        raise ApiError(status_code=_response.status_code, headers=dict(_response.headers), body=_response_json)

    async def delete(
        self, project_id: str, *, request_options: typing.Optional[RequestOptions] = None
    ) -> AsyncHttpResponse[None]:
        """
        Delete a project and its language targets.

        Parameters
        ----------
        project_id : str
            Identifier of the dubbing project to delete.

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

        Returns
        -------
        AsyncHttpResponse[None]
        """
        _response = await self._client_wrapper.httpx_client.request(
            f"v1/dubbing/project/{jsonable_encoder(project_id)}",
            method="DELETE",
            request_options=request_options,
        )
        try:
            if 200 <= _response.status_code < 300:
                return AsyncHttpResponse(response=_response, data=None)
            if _response.status_code == 422:
                raise UnprocessableEntityError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        typing.Any,
                        construct_type(
                            type_=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)
        except ValidationError as e:
            raise ParsingError(
                status_code=_response.status_code, headers=dict(_response.headers), body=_response.json(), cause=e
            )
        raise ApiError(status_code=_response.status_code, headers=dict(_response.headers), body=_response_json)
