# 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 .types.get_job_status_response import GetJobStatusResponse
from .types.initialize_render_job_request_format_opts import InitializeRenderJobRequestFormatOpts
from .types.initialize_render_job_request_target import InitializeRenderJobRequestTarget
from .types.initialize_render_job_request_type import InitializeRenderJobRequestType
from .types.initialize_render_job_response import InitializeRenderJobResponse
from .types.start_immediate_render_request_format_opts import StartImmediateRenderRequestFormatOpts
from .types.start_immediate_render_request_target import StartImmediateRenderRequestTarget
from .types.start_immediate_render_request_type import StartImmediateRenderRequestType
from .types.start_immediate_render_response import StartImmediateRenderResponse
from .types.start_render_job_response import StartRenderJobResponse

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


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

    def initialize_render_job(
        self,
        *,
        type: InitializeRenderJobRequestType,
        target: InitializeRenderJobRequestTarget,
        data: typing.Optional[typing.Dict[str, typing.Optional[typing.Any]]] = OMIT,
        template_id: typing.Optional[str] = OMIT,
        format_opts: typing.Optional[InitializeRenderJobRequestFormatOpts] = OMIT,
        request_options: typing.Optional[RequestOptions] = None,
    ) -> HttpResponse[InitializeRenderJobResponse]:
        """
        Creates a new render job with a unique ID, sets up S3 storage for template and data files, and generates presigned upload URLs if needed. Requires subscription check.

        Parameters
        ----------
        type : InitializeRenderJobRequestType
            Type of template to be rendered

        target : InitializeRenderJobRequestTarget
            Type of output to be rendered

        data : typing.Optional[typing.Dict[str, typing.Optional[typing.Any]]]
            Sample data for the template

        template_id : typing.Optional[str]
            ID of the template to be used

        format_opts : typing.Optional[InitializeRenderJobRequestFormatOpts]
            Format options for the rendered document

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

        Returns
        -------
        HttpResponse[InitializeRenderJobResponse]
            Default Response
        """
        _response = self._client_wrapper.httpx_client.request(
            "documents/init",
            method="POST",
            json={
                "data": data,
                "type": type,
                "target": target,
                "templateId": template_id,
                "formatOpts": convert_and_respect_annotation_metadata(
                    object_=format_opts, annotation=InitializeRenderJobRequestFormatOpts, direction="write"
                ),
            },
            headers={
                "content-type": "application/json",
            },
            request_options=request_options,
            omit=OMIT,
        )
        try:
            if 200 <= _response.status_code < 300:
                _data = typing.cast(
                    InitializeRenderJobResponse,
                    parse_obj_as(
                        type_=InitializeRenderJobResponse,  # type: ignore
                        object_=_response.json(),
                    ),
                )
                return HttpResponse(response=_response, data=_data)
            _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 start_render_job(
        self,
        job_id: str,
        *,
        should_wait_for_render_completion: typing.Optional[bool] = OMIT,
        upload_presigned_s_3_url: typing.Optional[str] = OMIT,
        request_options: typing.Optional[RequestOptions] = None,
    ) -> HttpResponse[StartRenderJobResponse]:
        """
        Takes a previously initialized job, updates its status to in-progress, and triggers the rendering process using Puppeteer. Can optionally wait for render completion.

        Parameters
        ----------
        job_id : str

        should_wait_for_render_completion : typing.Optional[bool]
            Whether to wait for the render job to complete, if false, the job will be returned immediately

        upload_presigned_s_3_url : typing.Optional[str]

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

        Returns
        -------
        HttpResponse[StartRenderJobResponse]
            Default Response
        """
        _response = self._client_wrapper.httpx_client.request(
            f"documents/{jsonable_encoder(job_id)}/render",
            method="POST",
            json={
                "shouldWaitForRenderCompletion": should_wait_for_render_completion,
                "uploadPresignedS3Url": upload_presigned_s_3_url,
            },
            headers={
                "content-type": "application/json",
            },
            request_options=request_options,
            omit=OMIT,
        )
        try:
            if 200 <= _response.status_code < 300:
                _data = typing.cast(
                    StartRenderJobResponse,
                    parse_obj_as(
                        type_=StartRenderJobResponse,  # type: ignore
                        object_=_response.json(),
                    ),
                )
                return HttpResponse(response=_response, data=_data)
            _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 start_immediate_render(
        self,
        *,
        type: StartImmediateRenderRequestType,
        target: StartImmediateRenderRequestTarget,
        data: typing.Dict[str, typing.Optional[typing.Any]],
        template_id: typing.Optional[str] = OMIT,
        format_opts: typing.Optional[StartImmediateRenderRequestFormatOpts] = OMIT,
        template: typing.Optional[str] = OMIT,
        upload_presigned_s_3_url: typing.Optional[str] = OMIT,
        request_options: typing.Optional[RequestOptions] = None,
    ) -> HttpResponse[StartImmediateRenderResponse]:
        """
        Combines initialization and rendering in one step. Creates a job, uploads template/data directly, starts rendering, and adds the document to Strapi. Requires subscription check.

        Parameters
        ----------
        type : StartImmediateRenderRequestType
            Type of template to be rendered

        target : StartImmediateRenderRequestTarget
            Type of output to be rendered

        data : typing.Dict[str, typing.Optional[typing.Any]]
            Sample data for the template

        template_id : typing.Optional[str]
            ID of the template to be used

        format_opts : typing.Optional[StartImmediateRenderRequestFormatOpts]
            Format options for the rendered document

        template : typing.Optional[str]
            index.html or ejs file of the template as a string

        upload_presigned_s_3_url : typing.Optional[str]
            Presigned URL to upload the data for the render job to S3

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

        Returns
        -------
        HttpResponse[StartImmediateRenderResponse]
            Default Response
        """
        _response = self._client_wrapper.httpx_client.request(
            "documents/immediate-render",
            method="POST",
            json={
                "type": type,
                "target": target,
                "templateId": template_id,
                "formatOpts": convert_and_respect_annotation_metadata(
                    object_=format_opts, annotation=StartImmediateRenderRequestFormatOpts, direction="write"
                ),
                "data": data,
                "template": template,
                "uploadPresignedS3Url": upload_presigned_s_3_url,
            },
            headers={
                "content-type": "application/json",
            },
            request_options=request_options,
            omit=OMIT,
        )
        try:
            if 200 <= _response.status_code < 300:
                _data = typing.cast(
                    StartImmediateRenderResponse,
                    parse_obj_as(
                        type_=StartImmediateRenderResponse,  # type: ignore
                        object_=_response.json(),
                    ),
                )
                return HttpResponse(response=_response, data=_data)
            _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_job_status(
        self, job_id: str, *, request_options: typing.Optional[RequestOptions] = None
    ) -> HttpResponse[GetJobStatusResponse]:
        """
        Fetches detailed job information from S3 storage including job status, template ID, target format, and output details if available.

        Parameters
        ----------
        job_id : str
            ID of the render job

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

        Returns
        -------
        HttpResponse[GetJobStatusResponse]
            Default Response
        """
        _response = self._client_wrapper.httpx_client.request(
            f"jobs/{jsonable_encoder(job_id)}",
            method="GET",
            request_options=request_options,
        )
        try:
            if 200 <= _response.status_code < 300:
                _data = typing.cast(
                    GetJobStatusResponse,
                    parse_obj_as(
                        type_=GetJobStatusResponse,  # type: ignore
                        object_=_response.json(),
                    ),
                )
                return HttpResponse(response=_response, data=_data)
            _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 AsyncRawDocumentsClient:
    def __init__(self, *, client_wrapper: AsyncClientWrapper):
        self._client_wrapper = client_wrapper

    async def initialize_render_job(
        self,
        *,
        type: InitializeRenderJobRequestType,
        target: InitializeRenderJobRequestTarget,
        data: typing.Optional[typing.Dict[str, typing.Optional[typing.Any]]] = OMIT,
        template_id: typing.Optional[str] = OMIT,
        format_opts: typing.Optional[InitializeRenderJobRequestFormatOpts] = OMIT,
        request_options: typing.Optional[RequestOptions] = None,
    ) -> AsyncHttpResponse[InitializeRenderJobResponse]:
        """
        Creates a new render job with a unique ID, sets up S3 storage for template and data files, and generates presigned upload URLs if needed. Requires subscription check.

        Parameters
        ----------
        type : InitializeRenderJobRequestType
            Type of template to be rendered

        target : InitializeRenderJobRequestTarget
            Type of output to be rendered

        data : typing.Optional[typing.Dict[str, typing.Optional[typing.Any]]]
            Sample data for the template

        template_id : typing.Optional[str]
            ID of the template to be used

        format_opts : typing.Optional[InitializeRenderJobRequestFormatOpts]
            Format options for the rendered document

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

        Returns
        -------
        AsyncHttpResponse[InitializeRenderJobResponse]
            Default Response
        """
        _response = await self._client_wrapper.httpx_client.request(
            "documents/init",
            method="POST",
            json={
                "data": data,
                "type": type,
                "target": target,
                "templateId": template_id,
                "formatOpts": convert_and_respect_annotation_metadata(
                    object_=format_opts, annotation=InitializeRenderJobRequestFormatOpts, direction="write"
                ),
            },
            headers={
                "content-type": "application/json",
            },
            request_options=request_options,
            omit=OMIT,
        )
        try:
            if 200 <= _response.status_code < 300:
                _data = typing.cast(
                    InitializeRenderJobResponse,
                    parse_obj_as(
                        type_=InitializeRenderJobResponse,  # type: ignore
                        object_=_response.json(),
                    ),
                )
                return AsyncHttpResponse(response=_response, data=_data)
            _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 start_render_job(
        self,
        job_id: str,
        *,
        should_wait_for_render_completion: typing.Optional[bool] = OMIT,
        upload_presigned_s_3_url: typing.Optional[str] = OMIT,
        request_options: typing.Optional[RequestOptions] = None,
    ) -> AsyncHttpResponse[StartRenderJobResponse]:
        """
        Takes a previously initialized job, updates its status to in-progress, and triggers the rendering process using Puppeteer. Can optionally wait for render completion.

        Parameters
        ----------
        job_id : str

        should_wait_for_render_completion : typing.Optional[bool]
            Whether to wait for the render job to complete, if false, the job will be returned immediately

        upload_presigned_s_3_url : typing.Optional[str]

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

        Returns
        -------
        AsyncHttpResponse[StartRenderJobResponse]
            Default Response
        """
        _response = await self._client_wrapper.httpx_client.request(
            f"documents/{jsonable_encoder(job_id)}/render",
            method="POST",
            json={
                "shouldWaitForRenderCompletion": should_wait_for_render_completion,
                "uploadPresignedS3Url": upload_presigned_s_3_url,
            },
            headers={
                "content-type": "application/json",
            },
            request_options=request_options,
            omit=OMIT,
        )
        try:
            if 200 <= _response.status_code < 300:
                _data = typing.cast(
                    StartRenderJobResponse,
                    parse_obj_as(
                        type_=StartRenderJobResponse,  # type: ignore
                        object_=_response.json(),
                    ),
                )
                return AsyncHttpResponse(response=_response, data=_data)
            _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 start_immediate_render(
        self,
        *,
        type: StartImmediateRenderRequestType,
        target: StartImmediateRenderRequestTarget,
        data: typing.Dict[str, typing.Optional[typing.Any]],
        template_id: typing.Optional[str] = OMIT,
        format_opts: typing.Optional[StartImmediateRenderRequestFormatOpts] = OMIT,
        template: typing.Optional[str] = OMIT,
        upload_presigned_s_3_url: typing.Optional[str] = OMIT,
        request_options: typing.Optional[RequestOptions] = None,
    ) -> AsyncHttpResponse[StartImmediateRenderResponse]:
        """
        Combines initialization and rendering in one step. Creates a job, uploads template/data directly, starts rendering, and adds the document to Strapi. Requires subscription check.

        Parameters
        ----------
        type : StartImmediateRenderRequestType
            Type of template to be rendered

        target : StartImmediateRenderRequestTarget
            Type of output to be rendered

        data : typing.Dict[str, typing.Optional[typing.Any]]
            Sample data for the template

        template_id : typing.Optional[str]
            ID of the template to be used

        format_opts : typing.Optional[StartImmediateRenderRequestFormatOpts]
            Format options for the rendered document

        template : typing.Optional[str]
            index.html or ejs file of the template as a string

        upload_presigned_s_3_url : typing.Optional[str]
            Presigned URL to upload the data for the render job to S3

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

        Returns
        -------
        AsyncHttpResponse[StartImmediateRenderResponse]
            Default Response
        """
        _response = await self._client_wrapper.httpx_client.request(
            "documents/immediate-render",
            method="POST",
            json={
                "type": type,
                "target": target,
                "templateId": template_id,
                "formatOpts": convert_and_respect_annotation_metadata(
                    object_=format_opts, annotation=StartImmediateRenderRequestFormatOpts, direction="write"
                ),
                "data": data,
                "template": template,
                "uploadPresignedS3Url": upload_presigned_s_3_url,
            },
            headers={
                "content-type": "application/json",
            },
            request_options=request_options,
            omit=OMIT,
        )
        try:
            if 200 <= _response.status_code < 300:
                _data = typing.cast(
                    StartImmediateRenderResponse,
                    parse_obj_as(
                        type_=StartImmediateRenderResponse,  # type: ignore
                        object_=_response.json(),
                    ),
                )
                return AsyncHttpResponse(response=_response, data=_data)
            _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_job_status(
        self, job_id: str, *, request_options: typing.Optional[RequestOptions] = None
    ) -> AsyncHttpResponse[GetJobStatusResponse]:
        """
        Fetches detailed job information from S3 storage including job status, template ID, target format, and output details if available.

        Parameters
        ----------
        job_id : str
            ID of the render job

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

        Returns
        -------
        AsyncHttpResponse[GetJobStatusResponse]
            Default Response
        """
        _response = await self._client_wrapper.httpx_client.request(
            f"jobs/{jsonable_encoder(job_id)}",
            method="GET",
            request_options=request_options,
        )
        try:
            if 200 <= _response.status_code < 300:
                _data = typing.cast(
                    GetJobStatusResponse,
                    parse_obj_as(
                        type_=GetJobStatusResponse,  # type: ignore
                        object_=_response.json(),
                    ),
                )
                return AsyncHttpResponse(response=_response, data=_data)
            _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)
