# 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.serialization import convert_and_respect_annotation_metadata
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.too_many_requests_error import TooManyRequestsError
from ..errors.unauthorized_error import UnauthorizedError
from ..types.legacy_list_processors_response import LegacyListProcessorsResponse
from ..types.legacy_processor_type import LegacyProcessorType
from .requests.processor_create_request_config import ProcessorCreateRequestConfigParams
from .requests.processor_update_request_config import ProcessorUpdateRequestConfigParams
from .types.processor_create_response import ProcessorCreateResponse
from .types.processor_list_request_sort_by import ProcessorListRequestSortBy
from .types.processor_list_request_sort_dir import ProcessorListRequestSortDir
from .types.processor_update_response import ProcessorUpdateResponse

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


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

    def list(
        self,
        *,
        type: typing.Optional[LegacyProcessorType] = None,
        next_page_token: typing.Optional[str] = None,
        max_page_size: typing.Optional[int] = None,
        sort_by: typing.Optional[ProcessorListRequestSortBy] = None,
        sort_dir: typing.Optional[ProcessorListRequestSortDir] = None,
        request_options: typing.Optional[RequestOptions] = None,
    ) -> HttpResponse[LegacyListProcessorsResponse]:
        """
        List all processors in your organization

        Parameters
        ----------
        type : typing.Optional[LegacyProcessorType]
            Filter processors by type

        next_page_token : typing.Optional[str]
            Token for retrieving the next page of results

        max_page_size : typing.Optional[int]
            Maximum number of processors to return per page

        sort_by : typing.Optional[ProcessorListRequestSortBy]
            Field to sort by

        sort_dir : typing.Optional[ProcessorListRequestSortDir]
            Sort direction

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

        Returns
        -------
        HttpResponse[LegacyListProcessorsResponse]
            Successfully retrieved processors
        """
        _response = self._client_wrapper.httpx_client.request(
            "processors",
            method="GET",
            params={
                "type": type,
                "nextPageToken": next_page_token,
                "maxPageSize": max_page_size,
                "sortBy": sort_by,
                "sortDir": sort_dir,
            },
            request_options=request_options,
        )
        try:
            if 200 <= _response.status_code < 300:
                _data = typing.cast(
                    LegacyListProcessorsResponse,
                    construct_type(
                        type_=LegacyListProcessorsResponse,  # 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.Any,
                        construct_type(
                            type_=typing.Any,  # type: ignore
                            object_=_response.json(),
                        ),
                    ),
                )
            if _response.status_code == 401:
                raise UnauthorizedError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        typing.Any,
                        construct_type(
                            type_=typing.Any,  # type: ignore
                            object_=_response.json(),
                        ),
                    ),
                )
            if _response.status_code == 429:
                raise TooManyRequestsError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        typing.Any,
                        construct_type(
                            type_=typing.Any,  # type: ignore
                            object_=_response.json(),
                        ),
                    ),
                )
            if _response.status_code == 500:
                raise InternalServerError(
                    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)
        raise ApiError(status_code=_response.status_code, headers=dict(_response.headers), body=_response_json)

    def create(
        self,
        *,
        name: str,
        type: LegacyProcessorType,
        clone_processor_id: typing.Optional[str] = OMIT,
        config: typing.Optional[ProcessorCreateRequestConfigParams] = OMIT,
        request_options: typing.Optional[RequestOptions] = None,
    ) -> HttpResponse[ProcessorCreateResponse]:
        """
        Create a new processor in Extend, optionally cloning from an existing processor

        Parameters
        ----------
        name : str
            The name of the new processor

        type : LegacyProcessorType

        clone_processor_id : typing.Optional[str]
            The ID of an existing processor to clone. One of `cloneProcessorId` or `config` must be provided.

            Example: `"ex_Xj8mK2pL9nR4vT7qY5wZ"`

        config : typing.Optional[ProcessorCreateRequestConfigParams]
            The configuration for the processor. The type of configuration must match the processor type. One of `cloneProcessorId` or `config` must be provided.

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

        Returns
        -------
        HttpResponse[ProcessorCreateResponse]
            Successfully created processor
        """
        _response = self._client_wrapper.httpx_client.request(
            "processors",
            method="POST",
            json={
                "name": name,
                "type": type,
                "cloneProcessorId": clone_processor_id,
                "config": convert_and_respect_annotation_metadata(
                    object_=config, annotation=ProcessorCreateRequestConfigParams, direction="write"
                ),
            },
            headers={
                "content-type": "application/json",
            },
            request_options=request_options,
            omit=OMIT,
        )
        try:
            if 200 <= _response.status_code < 300:
                _data = typing.cast(
                    ProcessorCreateResponse,
                    construct_type(
                        type_=ProcessorCreateResponse,  # 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.Any,
                        construct_type(
                            type_=typing.Any,  # type: ignore
                            object_=_response.json(),
                        ),
                    ),
                )
            if _response.status_code == 401:
                raise UnauthorizedError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        typing.Any,
                        construct_type(
                            type_=typing.Any,  # type: ignore
                            object_=_response.json(),
                        ),
                    ),
                )
            if _response.status_code == 404:
                raise NotFoundError(
                    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)
        raise ApiError(status_code=_response.status_code, headers=dict(_response.headers), body=_response_json)

    def update(
        self,
        id: str,
        *,
        name: typing.Optional[str] = OMIT,
        config: typing.Optional[ProcessorUpdateRequestConfigParams] = OMIT,
        request_options: typing.Optional[RequestOptions] = None,
    ) -> HttpResponse[ProcessorUpdateResponse]:
        """
        Update an existing processor in Extend

        Parameters
        ----------
        id : str
            The ID of the processor to update.

            Example: `"ex_Xj8mK2pL9nR4vT7qY5wZ"`

        name : typing.Optional[str]
            The new name for the processor

        config : typing.Optional[ProcessorUpdateRequestConfigParams]
            The new configuration for the processor. The type of configuration must match the processor type:
            * For classification processors, use `ClassificationConfig`
            * For extraction processors, use `ExtractionConfig`
            * For splitter processors, use `SplitterConfig`

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

        Returns
        -------
        HttpResponse[ProcessorUpdateResponse]
            Successfully updated processor
        """
        _response = self._client_wrapper.httpx_client.request(
            f"processors/{jsonable_encoder(id)}",
            method="POST",
            json={
                "name": name,
                "config": convert_and_respect_annotation_metadata(
                    object_=config, annotation=ProcessorUpdateRequestConfigParams, direction="write"
                ),
            },
            headers={
                "content-type": "application/json",
            },
            request_options=request_options,
            omit=OMIT,
        )
        try:
            if 200 <= _response.status_code < 300:
                _data = typing.cast(
                    ProcessorUpdateResponse,
                    construct_type(
                        type_=ProcessorUpdateResponse,  # 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.Any,
                        construct_type(
                            type_=typing.Any,  # type: ignore
                            object_=_response.json(),
                        ),
                    ),
                )
            if _response.status_code == 401:
                raise UnauthorizedError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        typing.Any,
                        construct_type(
                            type_=typing.Any,  # type: ignore
                            object_=_response.json(),
                        ),
                    ),
                )
            if _response.status_code == 404:
                raise NotFoundError(
                    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)
        raise ApiError(status_code=_response.status_code, headers=dict(_response.headers), body=_response_json)


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

    async def list(
        self,
        *,
        type: typing.Optional[LegacyProcessorType] = None,
        next_page_token: typing.Optional[str] = None,
        max_page_size: typing.Optional[int] = None,
        sort_by: typing.Optional[ProcessorListRequestSortBy] = None,
        sort_dir: typing.Optional[ProcessorListRequestSortDir] = None,
        request_options: typing.Optional[RequestOptions] = None,
    ) -> AsyncHttpResponse[LegacyListProcessorsResponse]:
        """
        List all processors in your organization

        Parameters
        ----------
        type : typing.Optional[LegacyProcessorType]
            Filter processors by type

        next_page_token : typing.Optional[str]
            Token for retrieving the next page of results

        max_page_size : typing.Optional[int]
            Maximum number of processors to return per page

        sort_by : typing.Optional[ProcessorListRequestSortBy]
            Field to sort by

        sort_dir : typing.Optional[ProcessorListRequestSortDir]
            Sort direction

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

        Returns
        -------
        AsyncHttpResponse[LegacyListProcessorsResponse]
            Successfully retrieved processors
        """
        _response = await self._client_wrapper.httpx_client.request(
            "processors",
            method="GET",
            params={
                "type": type,
                "nextPageToken": next_page_token,
                "maxPageSize": max_page_size,
                "sortBy": sort_by,
                "sortDir": sort_dir,
            },
            request_options=request_options,
        )
        try:
            if 200 <= _response.status_code < 300:
                _data = typing.cast(
                    LegacyListProcessorsResponse,
                    construct_type(
                        type_=LegacyListProcessorsResponse,  # 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.Any,
                        construct_type(
                            type_=typing.Any,  # type: ignore
                            object_=_response.json(),
                        ),
                    ),
                )
            if _response.status_code == 401:
                raise UnauthorizedError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        typing.Any,
                        construct_type(
                            type_=typing.Any,  # type: ignore
                            object_=_response.json(),
                        ),
                    ),
                )
            if _response.status_code == 429:
                raise TooManyRequestsError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        typing.Any,
                        construct_type(
                            type_=typing.Any,  # type: ignore
                            object_=_response.json(),
                        ),
                    ),
                )
            if _response.status_code == 500:
                raise InternalServerError(
                    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)
        raise ApiError(status_code=_response.status_code, headers=dict(_response.headers), body=_response_json)

    async def create(
        self,
        *,
        name: str,
        type: LegacyProcessorType,
        clone_processor_id: typing.Optional[str] = OMIT,
        config: typing.Optional[ProcessorCreateRequestConfigParams] = OMIT,
        request_options: typing.Optional[RequestOptions] = None,
    ) -> AsyncHttpResponse[ProcessorCreateResponse]:
        """
        Create a new processor in Extend, optionally cloning from an existing processor

        Parameters
        ----------
        name : str
            The name of the new processor

        type : LegacyProcessorType

        clone_processor_id : typing.Optional[str]
            The ID of an existing processor to clone. One of `cloneProcessorId` or `config` must be provided.

            Example: `"ex_Xj8mK2pL9nR4vT7qY5wZ"`

        config : typing.Optional[ProcessorCreateRequestConfigParams]
            The configuration for the processor. The type of configuration must match the processor type. One of `cloneProcessorId` or `config` must be provided.

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

        Returns
        -------
        AsyncHttpResponse[ProcessorCreateResponse]
            Successfully created processor
        """
        _response = await self._client_wrapper.httpx_client.request(
            "processors",
            method="POST",
            json={
                "name": name,
                "type": type,
                "cloneProcessorId": clone_processor_id,
                "config": convert_and_respect_annotation_metadata(
                    object_=config, annotation=ProcessorCreateRequestConfigParams, direction="write"
                ),
            },
            headers={
                "content-type": "application/json",
            },
            request_options=request_options,
            omit=OMIT,
        )
        try:
            if 200 <= _response.status_code < 300:
                _data = typing.cast(
                    ProcessorCreateResponse,
                    construct_type(
                        type_=ProcessorCreateResponse,  # 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.Any,
                        construct_type(
                            type_=typing.Any,  # type: ignore
                            object_=_response.json(),
                        ),
                    ),
                )
            if _response.status_code == 401:
                raise UnauthorizedError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        typing.Any,
                        construct_type(
                            type_=typing.Any,  # type: ignore
                            object_=_response.json(),
                        ),
                    ),
                )
            if _response.status_code == 404:
                raise NotFoundError(
                    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)
        raise ApiError(status_code=_response.status_code, headers=dict(_response.headers), body=_response_json)

    async def update(
        self,
        id: str,
        *,
        name: typing.Optional[str] = OMIT,
        config: typing.Optional[ProcessorUpdateRequestConfigParams] = OMIT,
        request_options: typing.Optional[RequestOptions] = None,
    ) -> AsyncHttpResponse[ProcessorUpdateResponse]:
        """
        Update an existing processor in Extend

        Parameters
        ----------
        id : str
            The ID of the processor to update.

            Example: `"ex_Xj8mK2pL9nR4vT7qY5wZ"`

        name : typing.Optional[str]
            The new name for the processor

        config : typing.Optional[ProcessorUpdateRequestConfigParams]
            The new configuration for the processor. The type of configuration must match the processor type:
            * For classification processors, use `ClassificationConfig`
            * For extraction processors, use `ExtractionConfig`
            * For splitter processors, use `SplitterConfig`

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

        Returns
        -------
        AsyncHttpResponse[ProcessorUpdateResponse]
            Successfully updated processor
        """
        _response = await self._client_wrapper.httpx_client.request(
            f"processors/{jsonable_encoder(id)}",
            method="POST",
            json={
                "name": name,
                "config": convert_and_respect_annotation_metadata(
                    object_=config, annotation=ProcessorUpdateRequestConfigParams, direction="write"
                ),
            },
            headers={
                "content-type": "application/json",
            },
            request_options=request_options,
            omit=OMIT,
        )
        try:
            if 200 <= _response.status_code < 300:
                _data = typing.cast(
                    ProcessorUpdateResponse,
                    construct_type(
                        type_=ProcessorUpdateResponse,  # 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.Any,
                        construct_type(
                            type_=typing.Any,  # type: ignore
                            object_=_response.json(),
                        ),
                    ),
                )
            if _response.status_code == 401:
                raise UnauthorizedError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        typing.Any,
                        construct_type(
                            type_=typing.Any,  # type: ignore
                            object_=_response.json(),
                        ),
                    ),
                )
            if _response.status_code == 404:
                raise NotFoundError(
                    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)
        raise ApiError(status_code=_response.status_code, headers=dict(_response.headers), body=_response_json)
