# 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 ..errors.unprocessable_entity_error import UnprocessableEntityError
from ..types.create_project_setup_out import CreateProjectSetupOut
from ..types.get_create_project_setup_response import GetCreateProjectSetupResponse
from ..types.http_validation_error import HttpValidationError
from ..types.languages import Languages

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


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

    def create_project(
        self,
        *,
        media_url: str,
        source_language: Languages,
        target_languages: typing.Sequence[Languages],
        run_id: typing.Optional[int] = None,
        project_name: typing.Optional[str] = OMIT,
        project_description: typing.Optional[str] = OMIT,
        folder_id: typing.Optional[int] = OMIT,
        selected_audio_tracks: typing.Optional[typing.Sequence[int]] = OMIT,
        add_output_as_an_audio_track: typing.Optional[bool] = OMIT,
        chosen_dictionaries: typing.Optional[typing.Sequence[int]] = OMIT,
        request_options: typing.Optional[RequestOptions] = None,
    ) -> HttpResponse[CreateProjectSetupOut]:
        """
        Creates a new project setup with transcription capabilities.

        This endpoint allows users to create a new project by providing media content
        (either as a file upload or URL), specifying source and target languages, and
        other project metadata. The function validates inputs, checks file size limitations,
        and initiates the project setup process.

        Args:
            request_payload (CreateProjectSetupRequestPayload): Complete project configuration
                    including media URL, source/target languages, project metadata, and
                    processing preferences such as audio track selection and dictionary choices.
                api_key_obj_and_subscription: Dependency injection providing validated API key
                    object and associated subscription details for authorization and usage
                    limit enforcement.
                traceparent (str | None, optional): OpenTelemetry trace parent header for
                    distributed tracing across microservices. Enables request correlation
                    and performance monitoring throughout the processing pipeline.

        Returns:
            Project setup response with project details and processing status.

        Raises:
            HTTPException:
                - 400: If neither media_file nor media_url is provided
                - 400: If uploaded file has no filename
                - 413: If uploaded file exceeds size limit

        Parameters
        ----------
        media_url : str

        source_language : Languages

        target_languages : typing.Sequence[Languages]

        run_id : typing.Optional[int]

        project_name : typing.Optional[str]

        project_description : typing.Optional[str]

        folder_id : typing.Optional[int]

        selected_audio_tracks : typing.Optional[typing.Sequence[int]]

        add_output_as_an_audio_track : typing.Optional[bool]

        chosen_dictionaries : typing.Optional[typing.Sequence[int]]

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

        Returns
        -------
        HttpResponse[CreateProjectSetupOut]
            Successful Response
        """
        _response = self._client_wrapper.httpx_client.request(
            "project-setup",
            method="POST",
            params={
                "run_id": run_id,
            },
            json={
                "project_name": project_name,
                "project_description": project_description,
                "folder_id": folder_id,
                "media_url": media_url,
                "source_language": source_language,
                "target_languages": target_languages,
                "selected_audio_tracks": selected_audio_tracks,
                "add_output_as_an_audio_track": add_output_as_an_audio_track,
                "chosen_dictionaries": chosen_dictionaries,
            },
            headers={
                "content-type": "application/json",
            },
            request_options=request_options,
            omit=OMIT,
        )
        try:
            if 200 <= _response.status_code < 300:
                _data = typing.cast(
                    CreateProjectSetupOut,
                    parse_obj_as(
                        type_=CreateProjectSetupOut,  # 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(
                        HttpValidationError,
                        parse_obj_as(
                            type_=HttpValidationError,  # 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_project_setup_task_status(
        self,
        task_id: str,
        *,
        run_id: typing.Optional[int] = None,
        request_options: typing.Optional[RequestOptions] = None,
    ) -> HttpResponse[typing.List[GetCreateProjectSetupResponse]]:
        """
        Parameters
        ----------
        task_id : str

        run_id : typing.Optional[int]

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

        Returns
        -------
        HttpResponse[typing.List[GetCreateProjectSetupResponse]]
            Successful Response
        """
        _response = self._client_wrapper.httpx_client.request(
            f"project-setup/{jsonable_encoder(task_id)}",
            method="GET",
            params={
                "run_id": run_id,
            },
            request_options=request_options,
        )
        try:
            if 200 <= _response.status_code < 300:
                _data = typing.cast(
                    typing.List[GetCreateProjectSetupResponse],
                    parse_obj_as(
                        type_=typing.List[GetCreateProjectSetupResponse],  # 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(
                        HttpValidationError,
                        parse_obj_as(
                            type_=HttpValidationError,  # 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 get_project_setup_result(
        self, run_id: typing.Optional[int], *, request_options: typing.Optional[RequestOptions] = None
    ) -> HttpResponse[typing.Optional[GetCreateProjectSetupResponse]]:
        """
        Retrieves the final result of a completed project setup.

        This endpoint provides access to the final results of a completed project setup.
        It verifies that the authenticated user has access to the requested run_id and
        validates that the run is of the correct type (`DUB_PROJECT`) before returning results.

        Note:
            This endpoint should only be called by users to retrieve their run results via API.
            Access validation is performed to ensure users can only access their own runs.

        Args:
            run_id: Positive integer ID of the project setup run.
            api_key_obj: API key authentication data from dependency.
            traceparent: OpenTelemetry trace header for distributed tracing.

        Returns:
            GetCreateProjectSetupResponse: Project setup results including run details.

        Raises:
            HTTPException:
                - 404: If the run_id is not found
                - 400: If the run type is not valid for this endpoint (must be DUB_PROJECT)

        Parameters
        ----------
        run_id : typing.Optional[int]

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

        Returns
        -------
        HttpResponse[typing.Optional[GetCreateProjectSetupResponse]]
            Successful Response
        """
        _response = self._client_wrapper.httpx_client.request(
            f"project-setup-result/{jsonable_encoder(run_id)}",
            method="GET",
            request_options=request_options,
        )
        try:
            if _response is None or not _response.text.strip():
                return HttpResponse(response=_response, data=None)
            if 200 <= _response.status_code < 300:
                _data = typing.cast(
                    typing.Optional[GetCreateProjectSetupResponse],
                    parse_obj_as(
                        type_=typing.Optional[GetCreateProjectSetupResponse],  # 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(
                        HttpValidationError,
                        parse_obj_as(
                            type_=HttpValidationError,  # 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 get_project_setup_runs_results(
        self,
        *,
        run_ids: typing.Sequence[int],
        run_id: typing.Optional[int] = None,
        request_options: typing.Optional[RequestOptions] = None,
    ) -> HttpResponse[typing.List[GetCreateProjectSetupResponse]]:
        """
        Parameters
        ----------
        run_ids : typing.Sequence[int]

        run_id : typing.Optional[int]

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

        Returns
        -------
        HttpResponse[typing.List[GetCreateProjectSetupResponse]]
            Successful Response
        """
        _response = self._client_wrapper.httpx_client.request(
            "project-setup-results",
            method="POST",
            params={
                "run_id": run_id,
            },
            json={
                "run_ids": run_ids,
            },
            headers={
                "content-type": "application/json",
            },
            request_options=request_options,
            omit=OMIT,
        )
        try:
            if 200 <= _response.status_code < 300:
                _data = typing.cast(
                    typing.List[GetCreateProjectSetupResponse],
                    parse_obj_as(
                        type_=typing.List[GetCreateProjectSetupResponse],  # 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(
                        HttpValidationError,
                        parse_obj_as(
                            type_=HttpValidationError,  # 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 AsyncRawProjectSetupClient:
    def __init__(self, *, client_wrapper: AsyncClientWrapper):
        self._client_wrapper = client_wrapper

    async def create_project(
        self,
        *,
        media_url: str,
        source_language: Languages,
        target_languages: typing.Sequence[Languages],
        run_id: typing.Optional[int] = None,
        project_name: typing.Optional[str] = OMIT,
        project_description: typing.Optional[str] = OMIT,
        folder_id: typing.Optional[int] = OMIT,
        selected_audio_tracks: typing.Optional[typing.Sequence[int]] = OMIT,
        add_output_as_an_audio_track: typing.Optional[bool] = OMIT,
        chosen_dictionaries: typing.Optional[typing.Sequence[int]] = OMIT,
        request_options: typing.Optional[RequestOptions] = None,
    ) -> AsyncHttpResponse[CreateProjectSetupOut]:
        """
        Creates a new project setup with transcription capabilities.

        This endpoint allows users to create a new project by providing media content
        (either as a file upload or URL), specifying source and target languages, and
        other project metadata. The function validates inputs, checks file size limitations,
        and initiates the project setup process.

        Args:
            request_payload (CreateProjectSetupRequestPayload): Complete project configuration
                    including media URL, source/target languages, project metadata, and
                    processing preferences such as audio track selection and dictionary choices.
                api_key_obj_and_subscription: Dependency injection providing validated API key
                    object and associated subscription details for authorization and usage
                    limit enforcement.
                traceparent (str | None, optional): OpenTelemetry trace parent header for
                    distributed tracing across microservices. Enables request correlation
                    and performance monitoring throughout the processing pipeline.

        Returns:
            Project setup response with project details and processing status.

        Raises:
            HTTPException:
                - 400: If neither media_file nor media_url is provided
                - 400: If uploaded file has no filename
                - 413: If uploaded file exceeds size limit

        Parameters
        ----------
        media_url : str

        source_language : Languages

        target_languages : typing.Sequence[Languages]

        run_id : typing.Optional[int]

        project_name : typing.Optional[str]

        project_description : typing.Optional[str]

        folder_id : typing.Optional[int]

        selected_audio_tracks : typing.Optional[typing.Sequence[int]]

        add_output_as_an_audio_track : typing.Optional[bool]

        chosen_dictionaries : typing.Optional[typing.Sequence[int]]

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

        Returns
        -------
        AsyncHttpResponse[CreateProjectSetupOut]
            Successful Response
        """
        _response = await self._client_wrapper.httpx_client.request(
            "project-setup",
            method="POST",
            params={
                "run_id": run_id,
            },
            json={
                "project_name": project_name,
                "project_description": project_description,
                "folder_id": folder_id,
                "media_url": media_url,
                "source_language": source_language,
                "target_languages": target_languages,
                "selected_audio_tracks": selected_audio_tracks,
                "add_output_as_an_audio_track": add_output_as_an_audio_track,
                "chosen_dictionaries": chosen_dictionaries,
            },
            headers={
                "content-type": "application/json",
            },
            request_options=request_options,
            omit=OMIT,
        )
        try:
            if 200 <= _response.status_code < 300:
                _data = typing.cast(
                    CreateProjectSetupOut,
                    parse_obj_as(
                        type_=CreateProjectSetupOut,  # 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(
                        HttpValidationError,
                        parse_obj_as(
                            type_=HttpValidationError,  # 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_project_setup_task_status(
        self,
        task_id: str,
        *,
        run_id: typing.Optional[int] = None,
        request_options: typing.Optional[RequestOptions] = None,
    ) -> AsyncHttpResponse[typing.List[GetCreateProjectSetupResponse]]:
        """
        Parameters
        ----------
        task_id : str

        run_id : typing.Optional[int]

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

        Returns
        -------
        AsyncHttpResponse[typing.List[GetCreateProjectSetupResponse]]
            Successful Response
        """
        _response = await self._client_wrapper.httpx_client.request(
            f"project-setup/{jsonable_encoder(task_id)}",
            method="GET",
            params={
                "run_id": run_id,
            },
            request_options=request_options,
        )
        try:
            if 200 <= _response.status_code < 300:
                _data = typing.cast(
                    typing.List[GetCreateProjectSetupResponse],
                    parse_obj_as(
                        type_=typing.List[GetCreateProjectSetupResponse],  # 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(
                        HttpValidationError,
                        parse_obj_as(
                            type_=HttpValidationError,  # 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 get_project_setup_result(
        self, run_id: typing.Optional[int], *, request_options: typing.Optional[RequestOptions] = None
    ) -> AsyncHttpResponse[typing.Optional[GetCreateProjectSetupResponse]]:
        """
        Retrieves the final result of a completed project setup.

        This endpoint provides access to the final results of a completed project setup.
        It verifies that the authenticated user has access to the requested run_id and
        validates that the run is of the correct type (`DUB_PROJECT`) before returning results.

        Note:
            This endpoint should only be called by users to retrieve their run results via API.
            Access validation is performed to ensure users can only access their own runs.

        Args:
            run_id: Positive integer ID of the project setup run.
            api_key_obj: API key authentication data from dependency.
            traceparent: OpenTelemetry trace header for distributed tracing.

        Returns:
            GetCreateProjectSetupResponse: Project setup results including run details.

        Raises:
            HTTPException:
                - 404: If the run_id is not found
                - 400: If the run type is not valid for this endpoint (must be DUB_PROJECT)

        Parameters
        ----------
        run_id : typing.Optional[int]

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

        Returns
        -------
        AsyncHttpResponse[typing.Optional[GetCreateProjectSetupResponse]]
            Successful Response
        """
        _response = await self._client_wrapper.httpx_client.request(
            f"project-setup-result/{jsonable_encoder(run_id)}",
            method="GET",
            request_options=request_options,
        )
        try:
            if _response is None or not _response.text.strip():
                return AsyncHttpResponse(response=_response, data=None)
            if 200 <= _response.status_code < 300:
                _data = typing.cast(
                    typing.Optional[GetCreateProjectSetupResponse],
                    parse_obj_as(
                        type_=typing.Optional[GetCreateProjectSetupResponse],  # 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(
                        HttpValidationError,
                        parse_obj_as(
                            type_=HttpValidationError,  # 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 get_project_setup_runs_results(
        self,
        *,
        run_ids: typing.Sequence[int],
        run_id: typing.Optional[int] = None,
        request_options: typing.Optional[RequestOptions] = None,
    ) -> AsyncHttpResponse[typing.List[GetCreateProjectSetupResponse]]:
        """
        Parameters
        ----------
        run_ids : typing.Sequence[int]

        run_id : typing.Optional[int]

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

        Returns
        -------
        AsyncHttpResponse[typing.List[GetCreateProjectSetupResponse]]
            Successful Response
        """
        _response = await self._client_wrapper.httpx_client.request(
            "project-setup-results",
            method="POST",
            params={
                "run_id": run_id,
            },
            json={
                "run_ids": run_ids,
            },
            headers={
                "content-type": "application/json",
            },
            request_options=request_options,
            omit=OMIT,
        )
        try:
            if 200 <= _response.status_code < 300:
                _data = typing.cast(
                    typing.List[GetCreateProjectSetupResponse],
                    parse_obj_as(
                        type_=typing.List[GetCreateProjectSetupResponse],  # 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(
                        HttpValidationError,
                        parse_obj_as(
                            type_=HttpValidationError,  # 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)
