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

from __future__ import annotations

import typing

import httpx
from .core.client_wrapper import AsyncClientWrapper, SyncClientWrapper
from .core.request_options import RequestOptions
from .environment import ExtendEnvironment
from .raw_client import AsyncRawExtend, RawExtend
from .types.parse_async_request_file import ParseAsyncRequestFile
from .types.parse_config import ParseConfig
from .types.parse_request_file import ParseRequestFile
from .types.parse_request_response_type import ParseRequestResponseType
from .types.parser_run import ParserRun
from .types.parser_run_status import ParserRunStatus

if typing.TYPE_CHECKING:
    from .batch_processor_run.client import AsyncBatchProcessorRunClient, BatchProcessorRunClient
    from .batch_workflow_run.client import AsyncBatchWorkflowRunClient, BatchWorkflowRunClient
    from .edit.client import AsyncEditClient, EditClient
    from .evaluation_set.client import AsyncEvaluationSetClient, EvaluationSetClient
    from .evaluation_set_item.client import AsyncEvaluationSetItemClient, EvaluationSetItemClient
    from .file.client import AsyncFileClient, FileClient
    from .parser_run.client import AsyncParserRunClient, ParserRunClient
    from .processor.client import AsyncProcessorClient, ProcessorClient
    from .processor_run.client import AsyncProcessorRunClient, ProcessorRunClient
    from .processor_version.client import AsyncProcessorVersionClient, ProcessorVersionClient
    from .workflow.client import AsyncWorkflowClient, WorkflowClient
    from .workflow_run.client import AsyncWorkflowRunClient, WorkflowRunClient
    from .workflow_run_output.client import AsyncWorkflowRunOutputClient, WorkflowRunOutputClient
# this is used as the default value for optional parameters
OMIT = typing.cast(typing.Any, ...)


class Extend:
    """
    Use this class to access the different functions within the SDK. You can instantiate any number of clients with different configuration that will propagate to these functions.

    Parameters
    ----------
    base_url : typing.Optional[str]
        The base url to use for requests from the client.

    environment : ExtendEnvironment
        The environment to use for requests from the client. from .environment import ExtendEnvironment



        Defaults to ExtendEnvironment.PRODUCTION



    token : typing.Optional[typing.Union[str, typing.Callable[[], str]]]
    headers : typing.Optional[typing.Dict[str, str]]
        Additional headers to send with every request.

    timeout : typing.Optional[float]
        The timeout to be used, in seconds, for requests. By default the timeout is 300 seconds, unless a custom httpx client is used, in which case this default is not enforced.

    follow_redirects : typing.Optional[bool]
        Whether the default httpx client follows redirects or not, this is irrelevant if a custom httpx client is passed in.

    httpx_client : typing.Optional[httpx.Client]
        The httpx client to use for making requests, a preconfigured client is used by default, however this is useful should you want to pass in any custom httpx configuration.

    extend_api_version : typing.Optional[str]
    Examples
    --------
    from extend_ai import Extend

    client = Extend(
        token="YOUR_TOKEN",
    )
    """

    def __init__(
        self,
        *,
        base_url: typing.Optional[str] = None,
        environment: ExtendEnvironment = ExtendEnvironment.PRODUCTION,
        token: typing.Optional[typing.Union[str, typing.Callable[[], str]]] = None,
        headers: typing.Optional[typing.Dict[str, str]] = None,
        timeout: typing.Optional[float] = None,
        follow_redirects: typing.Optional[bool] = True,
        httpx_client: typing.Optional[httpx.Client] = None,
        extend_api_version: typing.Optional[str] = None,
    ):
        _defaulted_timeout = (
            timeout if timeout is not None else 300 if httpx_client is None else httpx_client.timeout.read
        )
        self._client_wrapper = SyncClientWrapper(
            base_url=_get_base_url(base_url=base_url, environment=environment),
            token=token,
            headers=headers,
            httpx_client=httpx_client
            if httpx_client is not None
            else httpx.Client(timeout=_defaulted_timeout, follow_redirects=follow_redirects)
            if follow_redirects is not None
            else httpx.Client(timeout=_defaulted_timeout),
            timeout=_defaulted_timeout,
            extend_api_version=extend_api_version,
        )
        self._raw_client = RawExtend(client_wrapper=self._client_wrapper)
        self._workflow_run: typing.Optional[WorkflowRunClient] = None
        self._batch_workflow_run: typing.Optional[BatchWorkflowRunClient] = None
        self._processor_run: typing.Optional[ProcessorRunClient] = None
        self._processor: typing.Optional[ProcessorClient] = None
        self._processor_version: typing.Optional[ProcessorVersionClient] = None
        self._parser_run: typing.Optional[ParserRunClient] = None
        self._edit: typing.Optional[EditClient] = None
        self._file: typing.Optional[FileClient] = None
        self._evaluation_set: typing.Optional[EvaluationSetClient] = None
        self._evaluation_set_item: typing.Optional[EvaluationSetItemClient] = None
        self._workflow_run_output: typing.Optional[WorkflowRunOutputClient] = None
        self._batch_processor_run: typing.Optional[BatchProcessorRunClient] = None
        self._workflow: typing.Optional[WorkflowClient] = None

    @property
    def with_raw_response(self) -> RawExtend:
        """
        Retrieves a raw implementation of this client that returns raw responses.

        Returns
        -------
        RawExtend
        """
        return self._raw_client

    def parse(
        self,
        *,
        file: ParseRequestFile,
        response_type: typing.Optional[ParseRequestResponseType] = None,
        config: typing.Optional[ParseConfig] = OMIT,
        request_options: typing.Optional[RequestOptions] = None,
    ) -> ParserRun:
        """
        Parse files to get cleaned, chunked target content (e.g. markdown).

        The Parse endpoint allows you to convert documents into structured, machine-readable formats with fine-grained control over the parsing process. This endpoint is ideal for extracting cleaned document content to be used as context for downstream processing, e.g. RAG pipelines, custom ingestion pipelines, embeddings classification, etc.

        For more details, see the [Parse File guide](/product/parsing/parse).

        Parameters
        ----------
        file : ParseRequestFile
            A file object containing either a URL or a fileId.

        response_type : typing.Optional[ParseRequestResponseType]
            Controls the format of the response chunks. Defaults to `json` if not specified.
            * `json` - Returns parsed outputs in the response body
            * `url` - Return a presigned URL to the parsed content in the response body

        config : typing.Optional[ParseConfig]

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

        Returns
        -------
        ParserRun
            Successfully parsed file

        Examples
        --------
        from extend_ai import Extend, ParseRequestFile

        client = Extend(
            token="YOUR_TOKEN",
        )
        client.parse(
            response_type="json",
            file=ParseRequestFile(),
        )
        """
        _response = self._raw_client.parse(
            file=file, response_type=response_type, config=config, request_options=request_options
        )
        return _response.data

    def parse_async(
        self,
        *,
        file: ParseAsyncRequestFile,
        config: typing.Optional[ParseConfig] = OMIT,
        request_options: typing.Optional[RequestOptions] = None,
    ) -> ParserRunStatus:
        """
        Parse files **asynchronously** to get cleaned, chunked target content (e.g. markdown).

        The Parse Async endpoint allows you to convert documents into structured, machine-readable formats with fine-grained control over the parsing process. This endpoint is ideal for extracting cleaned document content to be used as context for downstream processing, e.g. RAG pipelines, custom ingestion pipelines, embeddings classification, etc.

        Parse files asynchronously and get a parser run ID that can be used to check status and retrieve results with the [Get Parser Run](https://docs.extend.ai/2025-04-21/developers/api-reference/parse-endpoints/get-parser-run) endpoint.

        This is useful for:
        * Large files that may take longer to process
        * Avoiding timeout issues with synchronous parsing.

        For more details, see the [Parse File guide](/product/parsing/parse).

        Parameters
        ----------
        file : ParseAsyncRequestFile
            A file object containing either a URL or a fileId.

        config : typing.Optional[ParseConfig]

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

        Returns
        -------
        ParserRunStatus
            Successfully initiated parser run

        Examples
        --------
        from extend_ai import Extend, ParseAsyncRequestFile

        client = Extend(
            token="YOUR_TOKEN",
        )
        client.parse_async(
            file=ParseAsyncRequestFile(),
        )
        """
        _response = self._raw_client.parse_async(file=file, config=config, request_options=request_options)
        return _response.data

    @property
    def workflow_run(self):
        if self._workflow_run is None:
            from .workflow_run.client import WorkflowRunClient  # noqa: E402

            self._workflow_run = WorkflowRunClient(client_wrapper=self._client_wrapper)
        return self._workflow_run

    @property
    def batch_workflow_run(self):
        if self._batch_workflow_run is None:
            from .batch_workflow_run.client import BatchWorkflowRunClient  # noqa: E402

            self._batch_workflow_run = BatchWorkflowRunClient(client_wrapper=self._client_wrapper)
        return self._batch_workflow_run

    @property
    def processor_run(self):
        if self._processor_run is None:
            from .processor_run.client import ProcessorRunClient  # noqa: E402

            self._processor_run = ProcessorRunClient(client_wrapper=self._client_wrapper)
        return self._processor_run

    @property
    def processor(self):
        if self._processor is None:
            from .processor.client import ProcessorClient  # noqa: E402

            self._processor = ProcessorClient(client_wrapper=self._client_wrapper)
        return self._processor

    @property
    def processor_version(self):
        if self._processor_version is None:
            from .processor_version.client import ProcessorVersionClient  # noqa: E402

            self._processor_version = ProcessorVersionClient(client_wrapper=self._client_wrapper)
        return self._processor_version

    @property
    def parser_run(self):
        if self._parser_run is None:
            from .parser_run.client import ParserRunClient  # noqa: E402

            self._parser_run = ParserRunClient(client_wrapper=self._client_wrapper)
        return self._parser_run

    @property
    def edit(self):
        if self._edit is None:
            from .edit.client import EditClient  # noqa: E402

            self._edit = EditClient(client_wrapper=self._client_wrapper)
        return self._edit

    @property
    def file(self):
        if self._file is None:
            from .file.client import FileClient  # noqa: E402

            self._file = FileClient(client_wrapper=self._client_wrapper)
        return self._file

    @property
    def evaluation_set(self):
        if self._evaluation_set is None:
            from .evaluation_set.client import EvaluationSetClient  # noqa: E402

            self._evaluation_set = EvaluationSetClient(client_wrapper=self._client_wrapper)
        return self._evaluation_set

    @property
    def evaluation_set_item(self):
        if self._evaluation_set_item is None:
            from .evaluation_set_item.client import EvaluationSetItemClient  # noqa: E402

            self._evaluation_set_item = EvaluationSetItemClient(client_wrapper=self._client_wrapper)
        return self._evaluation_set_item

    @property
    def workflow_run_output(self):
        if self._workflow_run_output is None:
            from .workflow_run_output.client import WorkflowRunOutputClient  # noqa: E402

            self._workflow_run_output = WorkflowRunOutputClient(client_wrapper=self._client_wrapper)
        return self._workflow_run_output

    @property
    def batch_processor_run(self):
        if self._batch_processor_run is None:
            from .batch_processor_run.client import BatchProcessorRunClient  # noqa: E402

            self._batch_processor_run = BatchProcessorRunClient(client_wrapper=self._client_wrapper)
        return self._batch_processor_run

    @property
    def workflow(self):
        if self._workflow is None:
            from .workflow.client import WorkflowClient  # noqa: E402

            self._workflow = WorkflowClient(client_wrapper=self._client_wrapper)
        return self._workflow


class AsyncExtend:
    """
    Use this class to access the different functions within the SDK. You can instantiate any number of clients with different configuration that will propagate to these functions.

    Parameters
    ----------
    base_url : typing.Optional[str]
        The base url to use for requests from the client.

    environment : ExtendEnvironment
        The environment to use for requests from the client. from .environment import ExtendEnvironment



        Defaults to ExtendEnvironment.PRODUCTION



    token : typing.Optional[typing.Union[str, typing.Callable[[], str]]]
    headers : typing.Optional[typing.Dict[str, str]]
        Additional headers to send with every request.

    timeout : typing.Optional[float]
        The timeout to be used, in seconds, for requests. By default the timeout is 300 seconds, unless a custom httpx client is used, in which case this default is not enforced.

    follow_redirects : typing.Optional[bool]
        Whether the default httpx client follows redirects or not, this is irrelevant if a custom httpx client is passed in.

    httpx_client : typing.Optional[httpx.AsyncClient]
        The httpx client to use for making requests, a preconfigured client is used by default, however this is useful should you want to pass in any custom httpx configuration.

    extend_api_version : typing.Optional[str]
    Examples
    --------
    from extend_ai import AsyncExtend

    client = AsyncExtend(
        token="YOUR_TOKEN",
    )
    """

    def __init__(
        self,
        *,
        base_url: typing.Optional[str] = None,
        environment: ExtendEnvironment = ExtendEnvironment.PRODUCTION,
        token: typing.Optional[typing.Union[str, typing.Callable[[], str]]] = None,
        headers: typing.Optional[typing.Dict[str, str]] = None,
        timeout: typing.Optional[float] = None,
        follow_redirects: typing.Optional[bool] = True,
        httpx_client: typing.Optional[httpx.AsyncClient] = None,
        extend_api_version: typing.Optional[str] = None,
    ):
        _defaulted_timeout = (
            timeout if timeout is not None else 300 if httpx_client is None else httpx_client.timeout.read
        )
        self._client_wrapper = AsyncClientWrapper(
            base_url=_get_base_url(base_url=base_url, environment=environment),
            token=token,
            headers=headers,
            httpx_client=httpx_client
            if httpx_client is not None
            else httpx.AsyncClient(timeout=_defaulted_timeout, follow_redirects=follow_redirects)
            if follow_redirects is not None
            else httpx.AsyncClient(timeout=_defaulted_timeout),
            timeout=_defaulted_timeout,
            extend_api_version=extend_api_version,
        )
        self._raw_client = AsyncRawExtend(client_wrapper=self._client_wrapper)
        self._workflow_run: typing.Optional[AsyncWorkflowRunClient] = None
        self._batch_workflow_run: typing.Optional[AsyncBatchWorkflowRunClient] = None
        self._processor_run: typing.Optional[AsyncProcessorRunClient] = None
        self._processor: typing.Optional[AsyncProcessorClient] = None
        self._processor_version: typing.Optional[AsyncProcessorVersionClient] = None
        self._parser_run: typing.Optional[AsyncParserRunClient] = None
        self._edit: typing.Optional[AsyncEditClient] = None
        self._file: typing.Optional[AsyncFileClient] = None
        self._evaluation_set: typing.Optional[AsyncEvaluationSetClient] = None
        self._evaluation_set_item: typing.Optional[AsyncEvaluationSetItemClient] = None
        self._workflow_run_output: typing.Optional[AsyncWorkflowRunOutputClient] = None
        self._batch_processor_run: typing.Optional[AsyncBatchProcessorRunClient] = None
        self._workflow: typing.Optional[AsyncWorkflowClient] = None

    @property
    def with_raw_response(self) -> AsyncRawExtend:
        """
        Retrieves a raw implementation of this client that returns raw responses.

        Returns
        -------
        AsyncRawExtend
        """
        return self._raw_client

    async def parse(
        self,
        *,
        file: ParseRequestFile,
        response_type: typing.Optional[ParseRequestResponseType] = None,
        config: typing.Optional[ParseConfig] = OMIT,
        request_options: typing.Optional[RequestOptions] = None,
    ) -> ParserRun:
        """
        Parse files to get cleaned, chunked target content (e.g. markdown).

        The Parse endpoint allows you to convert documents into structured, machine-readable formats with fine-grained control over the parsing process. This endpoint is ideal for extracting cleaned document content to be used as context for downstream processing, e.g. RAG pipelines, custom ingestion pipelines, embeddings classification, etc.

        For more details, see the [Parse File guide](/product/parsing/parse).

        Parameters
        ----------
        file : ParseRequestFile
            A file object containing either a URL or a fileId.

        response_type : typing.Optional[ParseRequestResponseType]
            Controls the format of the response chunks. Defaults to `json` if not specified.
            * `json` - Returns parsed outputs in the response body
            * `url` - Return a presigned URL to the parsed content in the response body

        config : typing.Optional[ParseConfig]

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

        Returns
        -------
        ParserRun
            Successfully parsed file

        Examples
        --------
        import asyncio

        from extend_ai import AsyncExtend, ParseRequestFile

        client = AsyncExtend(
            token="YOUR_TOKEN",
        )


        async def main() -> None:
            await client.parse(
                response_type="json",
                file=ParseRequestFile(),
            )


        asyncio.run(main())
        """
        _response = await self._raw_client.parse(
            file=file, response_type=response_type, config=config, request_options=request_options
        )
        return _response.data

    async def parse_async(
        self,
        *,
        file: ParseAsyncRequestFile,
        config: typing.Optional[ParseConfig] = OMIT,
        request_options: typing.Optional[RequestOptions] = None,
    ) -> ParserRunStatus:
        """
        Parse files **asynchronously** to get cleaned, chunked target content (e.g. markdown).

        The Parse Async endpoint allows you to convert documents into structured, machine-readable formats with fine-grained control over the parsing process. This endpoint is ideal for extracting cleaned document content to be used as context for downstream processing, e.g. RAG pipelines, custom ingestion pipelines, embeddings classification, etc.

        Parse files asynchronously and get a parser run ID that can be used to check status and retrieve results with the [Get Parser Run](https://docs.extend.ai/2025-04-21/developers/api-reference/parse-endpoints/get-parser-run) endpoint.

        This is useful for:
        * Large files that may take longer to process
        * Avoiding timeout issues with synchronous parsing.

        For more details, see the [Parse File guide](/product/parsing/parse).

        Parameters
        ----------
        file : ParseAsyncRequestFile
            A file object containing either a URL or a fileId.

        config : typing.Optional[ParseConfig]

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

        Returns
        -------
        ParserRunStatus
            Successfully initiated parser run

        Examples
        --------
        import asyncio

        from extend_ai import AsyncExtend, ParseAsyncRequestFile

        client = AsyncExtend(
            token="YOUR_TOKEN",
        )


        async def main() -> None:
            await client.parse_async(
                file=ParseAsyncRequestFile(),
            )


        asyncio.run(main())
        """
        _response = await self._raw_client.parse_async(file=file, config=config, request_options=request_options)
        return _response.data

    @property
    def workflow_run(self):
        if self._workflow_run is None:
            from .workflow_run.client import AsyncWorkflowRunClient  # noqa: E402

            self._workflow_run = AsyncWorkflowRunClient(client_wrapper=self._client_wrapper)
        return self._workflow_run

    @property
    def batch_workflow_run(self):
        if self._batch_workflow_run is None:
            from .batch_workflow_run.client import AsyncBatchWorkflowRunClient  # noqa: E402

            self._batch_workflow_run = AsyncBatchWorkflowRunClient(client_wrapper=self._client_wrapper)
        return self._batch_workflow_run

    @property
    def processor_run(self):
        if self._processor_run is None:
            from .processor_run.client import AsyncProcessorRunClient  # noqa: E402

            self._processor_run = AsyncProcessorRunClient(client_wrapper=self._client_wrapper)
        return self._processor_run

    @property
    def processor(self):
        if self._processor is None:
            from .processor.client import AsyncProcessorClient  # noqa: E402

            self._processor = AsyncProcessorClient(client_wrapper=self._client_wrapper)
        return self._processor

    @property
    def processor_version(self):
        if self._processor_version is None:
            from .processor_version.client import AsyncProcessorVersionClient  # noqa: E402

            self._processor_version = AsyncProcessorVersionClient(client_wrapper=self._client_wrapper)
        return self._processor_version

    @property
    def parser_run(self):
        if self._parser_run is None:
            from .parser_run.client import AsyncParserRunClient  # noqa: E402

            self._parser_run = AsyncParserRunClient(client_wrapper=self._client_wrapper)
        return self._parser_run

    @property
    def edit(self):
        if self._edit is None:
            from .edit.client import AsyncEditClient  # noqa: E402

            self._edit = AsyncEditClient(client_wrapper=self._client_wrapper)
        return self._edit

    @property
    def file(self):
        if self._file is None:
            from .file.client import AsyncFileClient  # noqa: E402

            self._file = AsyncFileClient(client_wrapper=self._client_wrapper)
        return self._file

    @property
    def evaluation_set(self):
        if self._evaluation_set is None:
            from .evaluation_set.client import AsyncEvaluationSetClient  # noqa: E402

            self._evaluation_set = AsyncEvaluationSetClient(client_wrapper=self._client_wrapper)
        return self._evaluation_set

    @property
    def evaluation_set_item(self):
        if self._evaluation_set_item is None:
            from .evaluation_set_item.client import AsyncEvaluationSetItemClient  # noqa: E402

            self._evaluation_set_item = AsyncEvaluationSetItemClient(client_wrapper=self._client_wrapper)
        return self._evaluation_set_item

    @property
    def workflow_run_output(self):
        if self._workflow_run_output is None:
            from .workflow_run_output.client import AsyncWorkflowRunOutputClient  # noqa: E402

            self._workflow_run_output = AsyncWorkflowRunOutputClient(client_wrapper=self._client_wrapper)
        return self._workflow_run_output

    @property
    def batch_processor_run(self):
        if self._batch_processor_run is None:
            from .batch_processor_run.client import AsyncBatchProcessorRunClient  # noqa: E402

            self._batch_processor_run = AsyncBatchProcessorRunClient(client_wrapper=self._client_wrapper)
        return self._batch_processor_run

    @property
    def workflow(self):
        if self._workflow is None:
            from .workflow.client import AsyncWorkflowClient  # noqa: E402

            self._workflow = AsyncWorkflowClient(client_wrapper=self._client_wrapper)
        return self._workflow


def _get_base_url(*, base_url: typing.Optional[str] = None, environment: ExtendEnvironment) -> str:
    if base_url is not None:
        return base_url
    elif environment is not None:
        return environment.value
    else:
        raise Exception("Please pass in either base_url or environment to construct the client")
