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

import typing
from ...core.client_wrapper import SyncClientWrapper
from ...core.request_options import RequestOptions
from ...core.http_response import HttpResponse
from ...types.paginated_slim_document_list import PaginatedSlimDocumentList
from ...core.pydantic_utilities import parse_obj_as
from json.decoder import JSONDecodeError
from ...core.api_error import ApiError
from ...types.document_read import DocumentRead
from ...core.jsonable_encoder import jsonable_encoder
from ...types.document_status import DocumentStatus
from ... import core
from ...types.upload_document_response import UploadDocumentResponse
from ...errors.bad_request_error import BadRequestError
from ...errors.not_found_error import NotFoundError
from ...errors.internal_server_error import InternalServerError
from ...core.client_wrapper import AsyncClientWrapper
from ...core.http_response import AsyncHttpResponse

# 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 list(
        self,
        *,
        document_index_id: typing.Optional[str] = None,
        limit: typing.Optional[int] = None,
        offset: typing.Optional[int] = None,
        ordering: typing.Optional[str] = None,
        search: typing.Optional[str] = None,
        request_options: typing.Optional[RequestOptions] = None,
    ) -> HttpResponse[PaginatedSlimDocumentList]:
        """
        Used to list documents. Optionally filter on supported fields.

        Parameters
        ----------
        document_index_id : typing.Optional[str]
            Filter down to only those documents that are included in the specified index. You may provide either the Vellum-generated ID or the unique name of the index specified upon initial creation.

        limit : typing.Optional[int]
            Number of results to return per page.

        offset : typing.Optional[int]
            The initial index from which to return the results.

        ordering : typing.Optional[str]
            Which field to use when ordering the results.

        search : typing.Optional[str]
            A search term.

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

        Returns
        -------
        HttpResponse[PaginatedSlimDocumentList]

        """
        _response = self._client_wrapper.httpx_client.request(
            "v1/documents",
            base_url=self._client_wrapper.get_environment().default,
            method="GET",
            params={
                "document_index_id": document_index_id,
                "limit": limit,
                "offset": offset,
                "ordering": ordering,
                "search": search,
            },
            request_options=request_options,
        )
        try:
            if 200 <= _response.status_code < 300:
                _data = typing.cast(
                    PaginatedSlimDocumentList,
                    parse_obj_as(
                        type_=PaginatedSlimDocumentList,  # type: ignore
                        object_=_response.json(),
                    ),
                )
                return HttpResponse(response=_response, data=_data)
            _response_json = _response.json()
        except JSONDecodeError:
            raise ApiError(status_code=_response.status_code, body=_response.text)
        raise ApiError(status_code=_response.status_code, body=_response_json)

    def retrieve(
        self, id: str, *, request_options: typing.Optional[RequestOptions] = None
    ) -> HttpResponse[DocumentRead]:
        """
        Retrieve a Document, keying off of either its Vellum-generated ID or its external ID.

        Parameters
        ----------
        id : str

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

        Returns
        -------
        HttpResponse[DocumentRead]

        """
        _response = self._client_wrapper.httpx_client.request(
            f"v1/documents/{jsonable_encoder(id)}",
            base_url=self._client_wrapper.get_environment().default,
            method="GET",
            request_options=request_options,
        )
        try:
            if 200 <= _response.status_code < 300:
                _data = typing.cast(
                    DocumentRead,
                    parse_obj_as(
                        type_=DocumentRead,  # type: ignore
                        object_=_response.json(),
                    ),
                )
                return HttpResponse(response=_response, data=_data)
            _response_json = _response.json()
        except JSONDecodeError:
            raise ApiError(status_code=_response.status_code, body=_response.text)
        raise ApiError(status_code=_response.status_code, body=_response_json)

    def destroy(self, id: str, *, request_options: typing.Optional[RequestOptions] = None) -> HttpResponse[None]:
        """
        Delete a Document, keying off of either its Vellum-generated ID or its external ID.

        Parameters
        ----------
        id : str

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

        Returns
        -------
        HttpResponse[None]
        """
        _response = self._client_wrapper.httpx_client.request(
            f"v1/documents/{jsonable_encoder(id)}",
            base_url=self._client_wrapper.get_environment().documents,
            method="DELETE",
            request_options=request_options,
        )
        try:
            if 200 <= _response.status_code < 300:
                return HttpResponse(response=_response, data=None)
            _response_json = _response.json()
        except JSONDecodeError:
            raise ApiError(status_code=_response.status_code, body=_response.text)
        raise ApiError(status_code=_response.status_code, body=_response_json)

    def partial_update(
        self,
        id: str,
        *,
        label: typing.Optional[str] = OMIT,
        status: typing.Optional[DocumentStatus] = OMIT,
        keywords: typing.Optional[typing.Sequence[str]] = OMIT,
        metadata: typing.Optional[typing.Dict[str, typing.Optional[typing.Any]]] = OMIT,
        request_options: typing.Optional[RequestOptions] = None,
    ) -> HttpResponse[DocumentRead]:
        """
        Update a Document, keying off of either its Vellum-generated ID or its external ID. Particularly useful for updating its metadata.

        Parameters
        ----------
        id : str

        label : typing.Optional[str]
            A human-readable label for the document. Defaults to the originally uploaded file's file name.

        status : typing.Optional[DocumentStatus]
            The current status of the document

            * `ACTIVE` - Active

        keywords : typing.Optional[typing.Sequence[str]]
            A list of keywords that'll be associated with the document. Used as part of keyword search.

        metadata : typing.Optional[typing.Dict[str, typing.Optional[typing.Any]]]
            A JSON object containing any metadata associated with the document that you'd like to filter upon later.

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

        Returns
        -------
        HttpResponse[DocumentRead]

        """
        _response = self._client_wrapper.httpx_client.request(
            f"v1/documents/{jsonable_encoder(id)}",
            base_url=self._client_wrapper.get_environment().default,
            method="PATCH",
            json={
                "label": label,
                "status": status,
                "keywords": keywords,
                "metadata": metadata,
            },
            headers={
                "content-type": "application/json",
            },
            request_options=request_options,
            omit=OMIT,
        )
        try:
            if 200 <= _response.status_code < 300:
                _data = typing.cast(
                    DocumentRead,
                    parse_obj_as(
                        type_=DocumentRead,  # type: ignore
                        object_=_response.json(),
                    ),
                )
                return HttpResponse(response=_response, data=_data)
            _response_json = _response.json()
        except JSONDecodeError:
            raise ApiError(status_code=_response.status_code, body=_response.text)
        raise ApiError(status_code=_response.status_code, body=_response_json)

    def upload(
        self,
        *,
        label: str,
        contents: core.File,
        add_to_index_names: typing.Optional[typing.List[str]] = OMIT,
        external_id: typing.Optional[str] = OMIT,
        keywords: typing.Optional[typing.List[str]] = OMIT,
        metadata: typing.Optional[str] = OMIT,
        request_options: typing.Optional[RequestOptions] = None,
    ) -> HttpResponse[UploadDocumentResponse]:
        """
        Upload a document to be indexed and used for search.

        **Note:** Uses a base url of `https://documents.vellum.ai`.

        Parameters
        ----------
        label : str
            A human-friendly name for this document. Typically the filename.

        contents : core.File
            See core.File for more documentation

        add_to_index_names : typing.Optional[typing.List[str]]
            Optionally include the names of all indexes that you'd like this document to be included in

        external_id : typing.Optional[str]
            Optionally include an external ID for this document. This is useful if you want to re-upload the same document later when its contents change and would like it to be re-indexed.

        keywords : typing.Optional[typing.List[str]]
            Optionally include a list of keywords that'll be associated with this document. Used when performing keyword searches.

        metadata : typing.Optional[str]
            A stringified JSON object containing any metadata associated with the document that you'd like to filter upon later.

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

        Returns
        -------
        HttpResponse[UploadDocumentResponse]

        """
        _response = self._client_wrapper.httpx_client.request(
            "v1/upload-document",
            base_url=self._client_wrapper.get_environment().documents,
            method="POST",
            data={
                "add_to_index_names": add_to_index_names,
                "external_id": external_id,
                "label": label,
                "keywords": keywords,
                "metadata": metadata,
            },
            files={
                "contents": contents,
            },
            request_options=request_options,
            omit=OMIT,
        )
        try:
            if 200 <= _response.status_code < 300:
                _data = typing.cast(
                    UploadDocumentResponse,
                    parse_obj_as(
                        type_=UploadDocumentResponse,  # type: ignore
                        object_=_response.json(),
                    ),
                )
                return HttpResponse(response=_response, data=_data)
            if _response.status_code == 400:
                raise BadRequestError(
                    typing.cast(
                        typing.Optional[typing.Any],
                        parse_obj_as(
                            type_=typing.Optional[typing.Any],  # type: ignore
                            object_=_response.json(),
                        ),
                    )
                )
            if _response.status_code == 404:
                raise NotFoundError(
                    typing.cast(
                        typing.Optional[typing.Any],
                        parse_obj_as(
                            type_=typing.Optional[typing.Any],  # type: ignore
                            object_=_response.json(),
                        ),
                    )
                )
            if _response.status_code == 500:
                raise InternalServerError(
                    typing.cast(
                        typing.Optional[typing.Any],
                        parse_obj_as(
                            type_=typing.Optional[typing.Any],  # type: ignore
                            object_=_response.json(),
                        ),
                    )
                )
            _response_json = _response.json()
        except JSONDecodeError:
            raise ApiError(status_code=_response.status_code, body=_response.text)
        raise ApiError(status_code=_response.status_code, body=_response_json)


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

    async def list(
        self,
        *,
        document_index_id: typing.Optional[str] = None,
        limit: typing.Optional[int] = None,
        offset: typing.Optional[int] = None,
        ordering: typing.Optional[str] = None,
        search: typing.Optional[str] = None,
        request_options: typing.Optional[RequestOptions] = None,
    ) -> AsyncHttpResponse[PaginatedSlimDocumentList]:
        """
        Used to list documents. Optionally filter on supported fields.

        Parameters
        ----------
        document_index_id : typing.Optional[str]
            Filter down to only those documents that are included in the specified index. You may provide either the Vellum-generated ID or the unique name of the index specified upon initial creation.

        limit : typing.Optional[int]
            Number of results to return per page.

        offset : typing.Optional[int]
            The initial index from which to return the results.

        ordering : typing.Optional[str]
            Which field to use when ordering the results.

        search : typing.Optional[str]
            A search term.

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

        Returns
        -------
        AsyncHttpResponse[PaginatedSlimDocumentList]

        """
        _response = await self._client_wrapper.httpx_client.request(
            "v1/documents",
            base_url=self._client_wrapper.get_environment().default,
            method="GET",
            params={
                "document_index_id": document_index_id,
                "limit": limit,
                "offset": offset,
                "ordering": ordering,
                "search": search,
            },
            request_options=request_options,
        )
        try:
            if 200 <= _response.status_code < 300:
                _data = typing.cast(
                    PaginatedSlimDocumentList,
                    parse_obj_as(
                        type_=PaginatedSlimDocumentList,  # type: ignore
                        object_=_response.json(),
                    ),
                )
                return AsyncHttpResponse(response=_response, data=_data)
            _response_json = _response.json()
        except JSONDecodeError:
            raise ApiError(status_code=_response.status_code, body=_response.text)
        raise ApiError(status_code=_response.status_code, body=_response_json)

    async def retrieve(
        self, id: str, *, request_options: typing.Optional[RequestOptions] = None
    ) -> AsyncHttpResponse[DocumentRead]:
        """
        Retrieve a Document, keying off of either its Vellum-generated ID or its external ID.

        Parameters
        ----------
        id : str

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

        Returns
        -------
        AsyncHttpResponse[DocumentRead]

        """
        _response = await self._client_wrapper.httpx_client.request(
            f"v1/documents/{jsonable_encoder(id)}",
            base_url=self._client_wrapper.get_environment().default,
            method="GET",
            request_options=request_options,
        )
        try:
            if 200 <= _response.status_code < 300:
                _data = typing.cast(
                    DocumentRead,
                    parse_obj_as(
                        type_=DocumentRead,  # type: ignore
                        object_=_response.json(),
                    ),
                )
                return AsyncHttpResponse(response=_response, data=_data)
            _response_json = _response.json()
        except JSONDecodeError:
            raise ApiError(status_code=_response.status_code, body=_response.text)
        raise ApiError(status_code=_response.status_code, body=_response_json)

    async def destroy(
        self, id: str, *, request_options: typing.Optional[RequestOptions] = None
    ) -> AsyncHttpResponse[None]:
        """
        Delete a Document, keying off of either its Vellum-generated ID or its external ID.

        Parameters
        ----------
        id : str

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

        Returns
        -------
        AsyncHttpResponse[None]
        """
        _response = await self._client_wrapper.httpx_client.request(
            f"v1/documents/{jsonable_encoder(id)}",
            base_url=self._client_wrapper.get_environment().documents,
            method="DELETE",
            request_options=request_options,
        )
        try:
            if 200 <= _response.status_code < 300:
                return AsyncHttpResponse(response=_response, data=None)
            _response_json = _response.json()
        except JSONDecodeError:
            raise ApiError(status_code=_response.status_code, body=_response.text)
        raise ApiError(status_code=_response.status_code, body=_response_json)

    async def partial_update(
        self,
        id: str,
        *,
        label: typing.Optional[str] = OMIT,
        status: typing.Optional[DocumentStatus] = OMIT,
        keywords: typing.Optional[typing.Sequence[str]] = OMIT,
        metadata: typing.Optional[typing.Dict[str, typing.Optional[typing.Any]]] = OMIT,
        request_options: typing.Optional[RequestOptions] = None,
    ) -> AsyncHttpResponse[DocumentRead]:
        """
        Update a Document, keying off of either its Vellum-generated ID or its external ID. Particularly useful for updating its metadata.

        Parameters
        ----------
        id : str

        label : typing.Optional[str]
            A human-readable label for the document. Defaults to the originally uploaded file's file name.

        status : typing.Optional[DocumentStatus]
            The current status of the document

            * `ACTIVE` - Active

        keywords : typing.Optional[typing.Sequence[str]]
            A list of keywords that'll be associated with the document. Used as part of keyword search.

        metadata : typing.Optional[typing.Dict[str, typing.Optional[typing.Any]]]
            A JSON object containing any metadata associated with the document that you'd like to filter upon later.

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

        Returns
        -------
        AsyncHttpResponse[DocumentRead]

        """
        _response = await self._client_wrapper.httpx_client.request(
            f"v1/documents/{jsonable_encoder(id)}",
            base_url=self._client_wrapper.get_environment().default,
            method="PATCH",
            json={
                "label": label,
                "status": status,
                "keywords": keywords,
                "metadata": metadata,
            },
            headers={
                "content-type": "application/json",
            },
            request_options=request_options,
            omit=OMIT,
        )
        try:
            if 200 <= _response.status_code < 300:
                _data = typing.cast(
                    DocumentRead,
                    parse_obj_as(
                        type_=DocumentRead,  # type: ignore
                        object_=_response.json(),
                    ),
                )
                return AsyncHttpResponse(response=_response, data=_data)
            _response_json = _response.json()
        except JSONDecodeError:
            raise ApiError(status_code=_response.status_code, body=_response.text)
        raise ApiError(status_code=_response.status_code, body=_response_json)

    async def upload(
        self,
        *,
        label: str,
        contents: core.File,
        add_to_index_names: typing.Optional[typing.List[str]] = OMIT,
        external_id: typing.Optional[str] = OMIT,
        keywords: typing.Optional[typing.List[str]] = OMIT,
        metadata: typing.Optional[str] = OMIT,
        request_options: typing.Optional[RequestOptions] = None,
    ) -> AsyncHttpResponse[UploadDocumentResponse]:
        """
        Upload a document to be indexed and used for search.

        **Note:** Uses a base url of `https://documents.vellum.ai`.

        Parameters
        ----------
        label : str
            A human-friendly name for this document. Typically the filename.

        contents : core.File
            See core.File for more documentation

        add_to_index_names : typing.Optional[typing.List[str]]
            Optionally include the names of all indexes that you'd like this document to be included in

        external_id : typing.Optional[str]
            Optionally include an external ID for this document. This is useful if you want to re-upload the same document later when its contents change and would like it to be re-indexed.

        keywords : typing.Optional[typing.List[str]]
            Optionally include a list of keywords that'll be associated with this document. Used when performing keyword searches.

        metadata : typing.Optional[str]
            A stringified JSON object containing any metadata associated with the document that you'd like to filter upon later.

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

        Returns
        -------
        AsyncHttpResponse[UploadDocumentResponse]

        """
        _response = await self._client_wrapper.httpx_client.request(
            "v1/upload-document",
            base_url=self._client_wrapper.get_environment().documents,
            method="POST",
            data={
                "add_to_index_names": add_to_index_names,
                "external_id": external_id,
                "label": label,
                "keywords": keywords,
                "metadata": metadata,
            },
            files={
                "contents": contents,
            },
            request_options=request_options,
            omit=OMIT,
        )
        try:
            if 200 <= _response.status_code < 300:
                _data = typing.cast(
                    UploadDocumentResponse,
                    parse_obj_as(
                        type_=UploadDocumentResponse,  # type: ignore
                        object_=_response.json(),
                    ),
                )
                return AsyncHttpResponse(response=_response, data=_data)
            if _response.status_code == 400:
                raise BadRequestError(
                    typing.cast(
                        typing.Optional[typing.Any],
                        parse_obj_as(
                            type_=typing.Optional[typing.Any],  # type: ignore
                            object_=_response.json(),
                        ),
                    )
                )
            if _response.status_code == 404:
                raise NotFoundError(
                    typing.cast(
                        typing.Optional[typing.Any],
                        parse_obj_as(
                            type_=typing.Optional[typing.Any],  # type: ignore
                            object_=_response.json(),
                        ),
                    )
                )
            if _response.status_code == 500:
                raise InternalServerError(
                    typing.cast(
                        typing.Optional[typing.Any],
                        parse_obj_as(
                            type_=typing.Optional[typing.Any],  # type: ignore
                            object_=_response.json(),
                        ),
                    )
                )
            _response_json = _response.json()
        except JSONDecodeError:
            raise ApiError(status_code=_response.status_code, body=_response.text)
        raise ApiError(status_code=_response.status_code, body=_response_json)
