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

import typing

from ..core.client_wrapper import AsyncClientWrapper, SyncClientWrapper
from ..core.request_options import RequestOptions
from ..requests.extract_config_json import ExtractConfigJsonParams
from ..types.extract_run import ExtractRun
from ..types.max_page_size import MaxPageSize
from ..types.next_page_token import NextPageToken
from ..types.processor_run_status import ProcessorRunStatus
from ..types.run_metadata import RunMetadata
from ..types.run_priority import RunPriority
from ..types.run_source import RunSource
from ..types.run_source_id import RunSourceId
from ..types.sort_by import SortBy
from ..types.sort_dir import SortDir
from .raw_client import AsyncRawExtractRunsClient, RawExtractRunsClient
from .requests.extract_runs_create_request_extractor import ExtractRunsCreateRequestExtractorParams
from .requests.extract_runs_create_request_file import ExtractRunsCreateRequestFileParams
from .types.extract_runs_delete_response import ExtractRunsDeleteResponse
from .types.extract_runs_list_response import ExtractRunsListResponse

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


class ExtractRunsClient:
    def __init__(self, *, client_wrapper: SyncClientWrapper):
        self._raw_client = RawExtractRunsClient(client_wrapper=client_wrapper)

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

        Returns
        -------
        RawExtractRunsClient
        """
        return self._raw_client

    def list(
        self,
        *,
        status: typing.Optional[ProcessorRunStatus] = None,
        extractor_id: typing.Optional[str] = None,
        source_id: typing.Optional[RunSourceId] = None,
        source: typing.Optional[RunSource] = None,
        file_name_contains: typing.Optional[str] = None,
        sort_by: typing.Optional[SortBy] = None,
        sort_dir: typing.Optional[SortDir] = None,
        next_page_token: typing.Optional[NextPageToken] = None,
        max_page_size: typing.Optional[MaxPageSize] = None,
        request_options: typing.Optional[RequestOptions] = None,
    ) -> ExtractRunsListResponse:
        """
        List all extract runs.

        Returns a summary of each run. Use `GET /extract_runs/{id}` to retrieve the full object including `output` and `config`.

        Parameters
        ----------
        status : typing.Optional[ProcessorRunStatus]

        extractor_id : typing.Optional[str]
            Filters extract runs by the extractor ID. If not provided, all extract runs are returned.

            Example: `"ex_BMdfq_yWM3sT-ZzvCnA3f"`

        source_id : typing.Optional[RunSourceId]
            Filters runs by the source ID.

        source : typing.Optional[RunSource]
            Filters runs by the source that created them. If not provided, runs from all sources are returned.

        file_name_contains : typing.Optional[str]
            Filters runs by the name of the file. Only returns runs where the file name contains this string.

            Example: `"invoice"`

        sort_by : typing.Optional[SortBy]

        sort_dir : typing.Optional[SortDir]

        next_page_token : typing.Optional[NextPageToken]

        max_page_size : typing.Optional[MaxPageSize]

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

        Returns
        -------
        ExtractRunsListResponse
            You will get a list of summaries for each extract run. These are shortened versions of the full extract run object.

            To get the full object, use the [Get Extract Run](https://docs.extend.ai/2026-02-09/developers/api-reference/endpoints/extract/get-extract-run) endpoint.

        Examples
        --------
        from extend_ai import Extend

        client = Extend(
            token="YOUR_TOKEN",
        )
        client.extract_runs.list(
            next_page_token="xK9mLPqRtN3vS8wF5hB2cQ==:zWvUxYjM4nKpL7aDgE9HbTcR2mAyX3/Q+CNkfBSw1dZ=",
        )
        """
        _response = self._raw_client.list(
            status=status,
            extractor_id=extractor_id,
            source_id=source_id,
            source=source,
            file_name_contains=file_name_contains,
            sort_by=sort_by,
            sort_dir=sort_dir,
            next_page_token=next_page_token,
            max_page_size=max_page_size,
            request_options=request_options,
        )
        return _response.data

    def create(
        self,
        *,
        file: ExtractRunsCreateRequestFileParams,
        extractor: typing.Optional[ExtractRunsCreateRequestExtractorParams] = OMIT,
        config: typing.Optional[ExtractConfigJsonParams] = OMIT,
        priority: typing.Optional[RunPriority] = OMIT,
        metadata: typing.Optional[RunMetadata] = OMIT,
        request_options: typing.Optional[RequestOptions] = None,
    ) -> ExtractRun:
        """
        Extract structured data from a file using an existing extractor or an inline configuration.

        The request returns immediately with a `PROCESSING` status. Use webhooks or poll the Get Extract Run endpoint for results.

        Parameters
        ----------
        file : ExtractRunsCreateRequestFileParams
            The file to be extracted from. Files can be provided as a URL, Extend file ID, or raw text.

        extractor : typing.Optional[ExtractRunsCreateRequestExtractorParams]
            Reference to an existing extractor. One of `extractor` or `config` must be provided.

        config : typing.Optional[ExtractConfigJsonParams]
            Inline extract configuration. One of `extractor` or `config` must be provided.

        priority : typing.Optional[RunPriority]

        metadata : typing.Optional[RunMetadata]

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

        Returns
        -------
        ExtractRun
            Extract completed successfully

        Examples
        --------
        from extend_ai import Extend

        client = Extend(
            token="YOUR_TOKEN",
        )
        client.extract_runs.create(
            extractor={"id": "ex_1234567890"},
            file={"url": "https://example.com/invoice.pdf"},
        )
        """
        _response = self._raw_client.create(
            file=file,
            extractor=extractor,
            config=config,
            priority=priority,
            metadata=metadata,
            request_options=request_options,
        )
        return _response.data

    def retrieve(self, id: str, *, request_options: typing.Optional[RequestOptions] = None) -> ExtractRun:
        """
        Retrieve details about a specific extract run, including its status, outputs, and any edits made during review.

        A common use case for this endpoint is to poll for the status and final output of an extract run when using the [Create Extract Run](https://docs.extend.ai/2026-02-09/developers/api-reference/endpoints/extract/create-extract-run) endpoint. For instance, if you do not want to not configure webhooks to receive the output via completion/failure events.

        Parameters
        ----------
        id : str
            The unique identifier for this extract run.

            Example: `"ex_Xj8mK2pL9nR4vT7qY5wZ"`

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

        Returns
        -------
        ExtractRun
            Successfully retrieved extract run

        Examples
        --------
        from extend_ai import Extend

        client = Extend(
            token="YOUR_TOKEN",
        )
        client.extract_runs.retrieve(
            id="extract_run_id_here",
        )
        """
        _response = self._raw_client.retrieve(id, request_options=request_options)
        return _response.data

    def delete(self, id: str, *, request_options: typing.Optional[RequestOptions] = None) -> ExtractRunsDeleteResponse:
        """
        Delete an extract 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 extract run.

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

        Returns
        -------
        ExtractRunsDeleteResponse
            Extractor run deleted successfully

        Examples
        --------
        from extend_ai import Extend

        client = Extend(
            token="YOUR_TOKEN",
        )
        client.extract_runs.delete(
            id="id",
        )
        """
        _response = self._raw_client.delete(id, request_options=request_options)
        return _response.data

    def cancel(self, id: str, *, request_options: typing.Optional[RequestOptions] = None) -> ExtractRun:
        """
        Cancel an in-progress extract run.

        Note: Only extract runs with a status of `"PROCESSING"` can be cancelled. Extractor runs that have already completed, failed, or been cancelled cannot be cancelled again.

        Parameters
        ----------
        id : str
            The ID of the extract run to cancel.

            Example: `"ex_Xj8mK2pL9nR4vT7qY5wZ"`

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

        Returns
        -------
        ExtractRun
            Extractor run cancelled successfully

        Examples
        --------
        from extend_ai import Extend

        client = Extend(
            token="YOUR_TOKEN",
        )
        client.extract_runs.cancel(
            id="extract_run_id_here",
        )
        """
        _response = self._raw_client.cancel(id, request_options=request_options)
        return _response.data


class AsyncExtractRunsClient:
    def __init__(self, *, client_wrapper: AsyncClientWrapper):
        self._raw_client = AsyncRawExtractRunsClient(client_wrapper=client_wrapper)

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

        Returns
        -------
        AsyncRawExtractRunsClient
        """
        return self._raw_client

    async def list(
        self,
        *,
        status: typing.Optional[ProcessorRunStatus] = None,
        extractor_id: typing.Optional[str] = None,
        source_id: typing.Optional[RunSourceId] = None,
        source: typing.Optional[RunSource] = None,
        file_name_contains: typing.Optional[str] = None,
        sort_by: typing.Optional[SortBy] = None,
        sort_dir: typing.Optional[SortDir] = None,
        next_page_token: typing.Optional[NextPageToken] = None,
        max_page_size: typing.Optional[MaxPageSize] = None,
        request_options: typing.Optional[RequestOptions] = None,
    ) -> ExtractRunsListResponse:
        """
        List all extract runs.

        Returns a summary of each run. Use `GET /extract_runs/{id}` to retrieve the full object including `output` and `config`.

        Parameters
        ----------
        status : typing.Optional[ProcessorRunStatus]

        extractor_id : typing.Optional[str]
            Filters extract runs by the extractor ID. If not provided, all extract runs are returned.

            Example: `"ex_BMdfq_yWM3sT-ZzvCnA3f"`

        source_id : typing.Optional[RunSourceId]
            Filters runs by the source ID.

        source : typing.Optional[RunSource]
            Filters runs by the source that created them. If not provided, runs from all sources are returned.

        file_name_contains : typing.Optional[str]
            Filters runs by the name of the file. Only returns runs where the file name contains this string.

            Example: `"invoice"`

        sort_by : typing.Optional[SortBy]

        sort_dir : typing.Optional[SortDir]

        next_page_token : typing.Optional[NextPageToken]

        max_page_size : typing.Optional[MaxPageSize]

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

        Returns
        -------
        ExtractRunsListResponse
            You will get a list of summaries for each extract run. These are shortened versions of the full extract run object.

            To get the full object, use the [Get Extract Run](https://docs.extend.ai/2026-02-09/developers/api-reference/endpoints/extract/get-extract-run) endpoint.

        Examples
        --------
        import asyncio

        from extend_ai import AsyncExtend

        client = AsyncExtend(
            token="YOUR_TOKEN",
        )


        async def main() -> None:
            await client.extract_runs.list(
                next_page_token="xK9mLPqRtN3vS8wF5hB2cQ==:zWvUxYjM4nKpL7aDgE9HbTcR2mAyX3/Q+CNkfBSw1dZ=",
            )


        asyncio.run(main())
        """
        _response = await self._raw_client.list(
            status=status,
            extractor_id=extractor_id,
            source_id=source_id,
            source=source,
            file_name_contains=file_name_contains,
            sort_by=sort_by,
            sort_dir=sort_dir,
            next_page_token=next_page_token,
            max_page_size=max_page_size,
            request_options=request_options,
        )
        return _response.data

    async def create(
        self,
        *,
        file: ExtractRunsCreateRequestFileParams,
        extractor: typing.Optional[ExtractRunsCreateRequestExtractorParams] = OMIT,
        config: typing.Optional[ExtractConfigJsonParams] = OMIT,
        priority: typing.Optional[RunPriority] = OMIT,
        metadata: typing.Optional[RunMetadata] = OMIT,
        request_options: typing.Optional[RequestOptions] = None,
    ) -> ExtractRun:
        """
        Extract structured data from a file using an existing extractor or an inline configuration.

        The request returns immediately with a `PROCESSING` status. Use webhooks or poll the Get Extract Run endpoint for results.

        Parameters
        ----------
        file : ExtractRunsCreateRequestFileParams
            The file to be extracted from. Files can be provided as a URL, Extend file ID, or raw text.

        extractor : typing.Optional[ExtractRunsCreateRequestExtractorParams]
            Reference to an existing extractor. One of `extractor` or `config` must be provided.

        config : typing.Optional[ExtractConfigJsonParams]
            Inline extract configuration. One of `extractor` or `config` must be provided.

        priority : typing.Optional[RunPriority]

        metadata : typing.Optional[RunMetadata]

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

        Returns
        -------
        ExtractRun
            Extract completed successfully

        Examples
        --------
        import asyncio

        from extend_ai import AsyncExtend

        client = AsyncExtend(
            token="YOUR_TOKEN",
        )


        async def main() -> None:
            await client.extract_runs.create(
                extractor={"id": "ex_1234567890"},
                file={"url": "https://example.com/invoice.pdf"},
            )


        asyncio.run(main())
        """
        _response = await self._raw_client.create(
            file=file,
            extractor=extractor,
            config=config,
            priority=priority,
            metadata=metadata,
            request_options=request_options,
        )
        return _response.data

    async def retrieve(self, id: str, *, request_options: typing.Optional[RequestOptions] = None) -> ExtractRun:
        """
        Retrieve details about a specific extract run, including its status, outputs, and any edits made during review.

        A common use case for this endpoint is to poll for the status and final output of an extract run when using the [Create Extract Run](https://docs.extend.ai/2026-02-09/developers/api-reference/endpoints/extract/create-extract-run) endpoint. For instance, if you do not want to not configure webhooks to receive the output via completion/failure events.

        Parameters
        ----------
        id : str
            The unique identifier for this extract run.

            Example: `"ex_Xj8mK2pL9nR4vT7qY5wZ"`

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

        Returns
        -------
        ExtractRun
            Successfully retrieved extract run

        Examples
        --------
        import asyncio

        from extend_ai import AsyncExtend

        client = AsyncExtend(
            token="YOUR_TOKEN",
        )


        async def main() -> None:
            await client.extract_runs.retrieve(
                id="extract_run_id_here",
            )


        asyncio.run(main())
        """
        _response = await self._raw_client.retrieve(id, request_options=request_options)
        return _response.data

    async def delete(
        self, id: str, *, request_options: typing.Optional[RequestOptions] = None
    ) -> ExtractRunsDeleteResponse:
        """
        Delete an extract 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 extract run.

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

        Returns
        -------
        ExtractRunsDeleteResponse
            Extractor run deleted successfully

        Examples
        --------
        import asyncio

        from extend_ai import AsyncExtend

        client = AsyncExtend(
            token="YOUR_TOKEN",
        )


        async def main() -> None:
            await client.extract_runs.delete(
                id="id",
            )


        asyncio.run(main())
        """
        _response = await self._raw_client.delete(id, request_options=request_options)
        return _response.data

    async def cancel(self, id: str, *, request_options: typing.Optional[RequestOptions] = None) -> ExtractRun:
        """
        Cancel an in-progress extract run.

        Note: Only extract runs with a status of `"PROCESSING"` can be cancelled. Extractor runs that have already completed, failed, or been cancelled cannot be cancelled again.

        Parameters
        ----------
        id : str
            The ID of the extract run to cancel.

            Example: `"ex_Xj8mK2pL9nR4vT7qY5wZ"`

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

        Returns
        -------
        ExtractRun
            Extractor run cancelled successfully

        Examples
        --------
        import asyncio

        from extend_ai import AsyncExtend

        client = AsyncExtend(
            token="YOUR_TOKEN",
        )


        async def main() -> None:
            await client.extract_runs.cancel(
                id="extract_run_id_here",
            )


        asyncio.run(main())
        """
        _response = await self._raw_client.cancel(id, request_options=request_options)
        return _response.data
