# 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.request_options import RequestOptions
from ..core.unchecked_base_model import construct_type
from ..errors.bad_request_error import BadRequestError
from ..errors.internal_server_error import InternalServerError
from ..errors.not_found_error import NotFoundError
from ..errors.unauthorized_error import UnauthorizedError
from ..types.error import Error
from ..types.extend_error import ExtendError
from .types.parser_run_delete_response import ParserRunDeleteResponse
from .types.parser_run_get_request_response_type import ParserRunGetRequestResponseType
from .types.parser_run_get_response import ParserRunGetResponse


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

    def get(
        self,
        id: str,
        *,
        response_type: typing.Optional[ParserRunGetRequestResponseType] = None,
        request_options: typing.Optional[RequestOptions] = None,
    ) -> HttpResponse[ParserRunGetResponse]:
        """
        Retrieve the status and results of a parser run.

        Use this endpoint to get results for a parser run that has already completed, or to check on the status of an asynchronous parser run initiated via the [Parse File Asynchronously](https://docs.extend.ai/2025-04-21/developers/api-reference/parse-endpoints/parse-file-async) endpoint.

        If parsing is still in progress, you'll receive a response with just the status. Once complete, you'll receive the full parsed content in the response.

        Parameters
        ----------
        id : str
            The unique identifier for the parser run.

            Example: `"parser_run_xK9mLPqRtN3vS8wF5hB2cQ"`

        response_type : typing.Optional[ParserRunGetRequestResponseType]
            Controls the format of the response chunks. Defaults to `json` if not specified.
            * `json` - Returns chunks with inline content
            * `url` - Returns chunks with presigned URLs to content instead of inline data

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

        Returns
        -------
        HttpResponse[ParserRunGetResponse]
            Successfully retrieved parser run
        """
        _response = self._client_wrapper.httpx_client.request(
            f"parser_runs/{jsonable_encoder(id)}",
            method="GET",
            params={
                "responseType": response_type,
            },
            request_options=request_options,
        )
        try:
            if 200 <= _response.status_code < 300:
                _data = typing.cast(
                    ParserRunGetResponse,
                    construct_type(
                        type_=ParserRunGetResponse,  # 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],
                        construct_type(
                            type_=typing.Optional[typing.Any],  # type: ignore
                            object_=_response.json(),
                        ),
                    ),
                )
            if _response.status_code == 401:
                raise UnauthorizedError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        Error,
                        construct_type(
                            type_=Error,  # type: ignore
                            object_=_response.json(),
                        ),
                    ),
                )
            if _response.status_code == 404:
                raise NotFoundError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        typing.Optional[typing.Any],
                        construct_type(
                            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, id: str, *, request_options: typing.Optional[RequestOptions] = None
    ) -> HttpResponse[ParserRunDeleteResponse]:
        """
        Delete a parser run and all associated data from Extend. This operation is permanent and cannot be undone.

        This endpoint can be used if you'd like to manage data retention on your own rather than automated data retention policies. Or make one-off deletions for your downstream customers.

        Parameters
        ----------
        id : str
            The ID of the parser run to delete.

            Example: `"parser_run_xK9mLPqRtN3vS8wF5hB2cQ"`

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

        Returns
        -------
        HttpResponse[ParserRunDeleteResponse]
            Successfully deleted parser run
        """
        _response = self._client_wrapper.httpx_client.request(
            f"parser_runs/{jsonable_encoder(id)}",
            method="DELETE",
            request_options=request_options,
        )
        try:
            if 200 <= _response.status_code < 300:
                _data = typing.cast(
                    ParserRunDeleteResponse,
                    construct_type(
                        type_=ParserRunDeleteResponse,  # 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],
                        construct_type(
                            type_=typing.Optional[typing.Any],  # type: ignore
                            object_=_response.json(),
                        ),
                    ),
                )
            if _response.status_code == 500:
                raise InternalServerError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        ExtendError,
                        construct_type(
                            type_=ExtendError,  # 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 AsyncRawParserRunClient:
    def __init__(self, *, client_wrapper: AsyncClientWrapper):
        self._client_wrapper = client_wrapper

    async def get(
        self,
        id: str,
        *,
        response_type: typing.Optional[ParserRunGetRequestResponseType] = None,
        request_options: typing.Optional[RequestOptions] = None,
    ) -> AsyncHttpResponse[ParserRunGetResponse]:
        """
        Retrieve the status and results of a parser run.

        Use this endpoint to get results for a parser run that has already completed, or to check on the status of an asynchronous parser run initiated via the [Parse File Asynchronously](https://docs.extend.ai/2025-04-21/developers/api-reference/parse-endpoints/parse-file-async) endpoint.

        If parsing is still in progress, you'll receive a response with just the status. Once complete, you'll receive the full parsed content in the response.

        Parameters
        ----------
        id : str
            The unique identifier for the parser run.

            Example: `"parser_run_xK9mLPqRtN3vS8wF5hB2cQ"`

        response_type : typing.Optional[ParserRunGetRequestResponseType]
            Controls the format of the response chunks. Defaults to `json` if not specified.
            * `json` - Returns chunks with inline content
            * `url` - Returns chunks with presigned URLs to content instead of inline data

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

        Returns
        -------
        AsyncHttpResponse[ParserRunGetResponse]
            Successfully retrieved parser run
        """
        _response = await self._client_wrapper.httpx_client.request(
            f"parser_runs/{jsonable_encoder(id)}",
            method="GET",
            params={
                "responseType": response_type,
            },
            request_options=request_options,
        )
        try:
            if 200 <= _response.status_code < 300:
                _data = typing.cast(
                    ParserRunGetResponse,
                    construct_type(
                        type_=ParserRunGetResponse,  # 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],
                        construct_type(
                            type_=typing.Optional[typing.Any],  # type: ignore
                            object_=_response.json(),
                        ),
                    ),
                )
            if _response.status_code == 401:
                raise UnauthorizedError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        Error,
                        construct_type(
                            type_=Error,  # type: ignore
                            object_=_response.json(),
                        ),
                    ),
                )
            if _response.status_code == 404:
                raise NotFoundError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        typing.Optional[typing.Any],
                        construct_type(
                            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, id: str, *, request_options: typing.Optional[RequestOptions] = None
    ) -> AsyncHttpResponse[ParserRunDeleteResponse]:
        """
        Delete a parser run and all associated data from Extend. This operation is permanent and cannot be undone.

        This endpoint can be used if you'd like to manage data retention on your own rather than automated data retention policies. Or make one-off deletions for your downstream customers.

        Parameters
        ----------
        id : str
            The ID of the parser run to delete.

            Example: `"parser_run_xK9mLPqRtN3vS8wF5hB2cQ"`

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

        Returns
        -------
        AsyncHttpResponse[ParserRunDeleteResponse]
            Successfully deleted parser run
        """
        _response = await self._client_wrapper.httpx_client.request(
            f"parser_runs/{jsonable_encoder(id)}",
            method="DELETE",
            request_options=request_options,
        )
        try:
            if 200 <= _response.status_code < 300:
                _data = typing.cast(
                    ParserRunDeleteResponse,
                    construct_type(
                        type_=ParserRunDeleteResponse,  # 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],
                        construct_type(
                            type_=typing.Optional[typing.Any],  # type: ignore
                            object_=_response.json(),
                        ),
                    ),
                )
            if _response.status_code == 500:
                raise InternalServerError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        ExtendError,
                        construct_type(
                            type_=ExtendError,  # 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)
