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

import typing

from .. import core
from ..common.types.custom_metadata_value import CustomMetadataValue
from ..core.client_wrapper import AsyncClientWrapper, SyncClientWrapper
from ..core.request_options import RequestOptions
from .raw_client import AsyncRawDocumentCatalogClient, RawDocumentCatalogClient
from .types.document_metadata_patch import DocumentMetadataPatch
from .types.sync_source_by_url_response import SyncSourceByUrlResponse
from .types.upload_document_response import UploadDocumentResponse

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


class DocumentCatalogClient:
    def __init__(self, *, client_wrapper: SyncClientWrapper):
        self._raw_client = RawDocumentCatalogClient(client_wrapper=client_wrapper)

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

        Returns
        -------
        RawDocumentCatalogClient
        """
        return self._raw_client

    def upload_document_contents(
        self,
        *,
        document_name: str,
        document_contents: str,
        allowed_users_email_addresses: typing.Sequence[str],
        upload_as_user_email: str,
        document_external_id: str,
        document_external_url: typing.Optional[str] = OMIT,
        custom_metadata: typing.Optional[typing.Dict[str, CustomMetadataValue]] = OMIT,
        collection_id: typing.Optional[str] = OMIT,
        force_update: typing.Optional[bool] = OMIT,
        internal_public: typing.Optional[bool] = OMIT,
        await_vector_store_sync: typing.Optional[bool] = OMIT,
        request_options: typing.Optional[RequestOptions] = None,
    ) -> UploadDocumentResponse:
        """
        Parameters
        ----------
        document_name : str
            The name of the document you want to upload.

        document_contents : str
            The full LLM-formatted text contents of the document you want to upload.

        allowed_users_email_addresses : typing.Sequence[str]
            Users allowed to access the document. Unlike Credal's out of the box connectors which reconcile various permissions models from 3rd party software, for custom uploads the caller is responsible for specifying who can access the document and currently flattening groups if applicable. Documents can also be marked as internal public.

        upload_as_user_email : str
            [Legacy] The user on behalf of whom the document should be uploaded. In most cases, this can simply be the email of the developer making the API call. This field will be removed in the future in favor of purely specifying permissions via allowedUsersEmailAddresses.

        document_external_id : str
            The external ID of the document. This is typically the ID as it exists in its original external system. Uploads to the same external ID will update the document in Credal.

        document_external_url : typing.Optional[str]
            The external URL of the document you want to upload. If provided Credal will link to this URL.

        custom_metadata : typing.Optional[typing.Dict[str, CustomMetadataValue]]
            Optional JSON representing any custom metadata for this document

        collection_id : typing.Optional[str]
            If specified, the document will also be added to the provided document collection. This operation is eventually consistent, meaning the document does not immediately start appearing in searches of that collection due to an asynchronous embedding process. To achieve strong consistency use the `awaitVectorStoreSync` parameter.

        force_update : typing.Optional[bool]
            If specified, document contents will be re-uploaded and re-embedded even if the document already exists in Credal

        internal_public : typing.Optional[bool]
            If specified, document will be accessible to everyone within the organization of the uploader

        await_vector_store_sync : typing.Optional[bool]
            Document uploads are eventually consistent by default. If specified `true` the API will wait for the vector store to be updated before returning. This is useful if you want to ensure that the document is immediately searchable after this call returns.

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

        Returns
        -------
        UploadDocumentResponse

        Examples
        --------
        from credal import CredalApi

        client = CredalApi(
            api_key="YOUR_API_KEY",
        )
        client.document_catalog.upload_document_contents(
            document_name="My Document",
            document_contents="Lorem ipsum...",
            document_external_id="73eead26-d124-4940-b329-5f068a0a8db9",
            allowed_users_email_addresses=["jack@credal.ai", "ravin@credal.ai"],
            upload_as_user_email="jack@credal.ai",
        )
        """
        _response = self._raw_client.upload_document_contents(
            document_name=document_name,
            document_contents=document_contents,
            allowed_users_email_addresses=allowed_users_email_addresses,
            upload_as_user_email=upload_as_user_email,
            document_external_id=document_external_id,
            document_external_url=document_external_url,
            custom_metadata=custom_metadata,
            collection_id=collection_id,
            force_update=force_update,
            internal_public=internal_public,
            await_vector_store_sync=await_vector_store_sync,
            request_options=request_options,
        )
        return _response.data

    def upload_file(
        self,
        *,
        file: core.File,
        upload_as_user_email: str,
        document_external_id: str,
        document_name: typing.Optional[str] = OMIT,
        allowed_users_email_addresses: typing.Optional[str] = OMIT,
        document_external_url: typing.Optional[str] = OMIT,
        custom_metadata: typing.Optional[str] = OMIT,
        collection_id: typing.Optional[str] = OMIT,
        force_update: typing.Optional[str] = OMIT,
        internal_public: typing.Optional[str] = OMIT,
        source_system_updated: typing.Optional[str] = OMIT,
        await_vector_store_sync: typing.Optional[str] = OMIT,
        request_options: typing.Optional[RequestOptions] = None,
    ) -> UploadDocumentResponse:
        """
        Upload a file (PDF, Word, Excel, CSV, PowerPoint) to Credal. Unlike uploadDocumentContents which requires pre-parsed text, this endpoint accepts actual file uploads and automatically parses them using Credal's parsing service.

        Parameters
        ----------
        file : core.File
            See core.File for more documentation

        upload_as_user_email : str
            [Legacy] The user on behalf of whom the document should be uploaded. In most cases, this can simply be the email of the developer making the API call. This field will be removed in the future in favor of purely specifying permissions via allowedUsersEmailAddresses.

        document_external_id : str
            The external ID of the document. This is typically the ID as it exists in its original external system. Uploads to the same external ID will update the document in Credal.

        document_name : typing.Optional[str]
            The name of the document you want to upload. If not provided, the original filename will be used.

        allowed_users_email_addresses : typing.Optional[str]
            Users allowed to access the document. Can be provided as a JSON array string (e.g., ["user1@example.com","user2@example.com"]) or comma-separated list (e.g., "user1@example.com,user2@example.com"). Unlike Credal's out of the box connectors which reconcile various permissions models from 3rd party software, for custom uploads the caller is responsible for specifying who can access the document and currently flattening groups if applicable. Documents can also be marked as internal public.

        document_external_url : typing.Optional[str]
            The external URL of the document you want to upload. If provided Credal will link to this URL.

        custom_metadata : typing.Optional[str]
            Optional JSON string representing any custom metadata for this document (e.g., '{"key1":"value1","key2":"value2"}').

        collection_id : typing.Optional[str]
            If specified, the document will also be added to the provided document collection. This operation is eventually consistent, meaning the document does not immediately start appearing in searches of that collection due to an asynchronous embedding process. To achieve strong consistency use the `awaitVectorStoreSync` parameter.

        force_update : typing.Optional[str]
            If set to "true", document contents will be re-uploaded and re-embedded even if the document already exists in Credal.

        internal_public : typing.Optional[str]
            If set to "true", document will be accessible to everyone within the organization of the uploader.

        source_system_updated : typing.Optional[str]
            ISO 8601 date string indicating when the document was last updated in the source system (e.g., "2025-11-03T21:15:00Z").

        await_vector_store_sync : typing.Optional[str]
            Document uploads are eventually consistent by default. If set to "true" the API will wait for the vector store to be updated before returning. This is useful if you want to ensure that the document is immediately searchable after this call returns.

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

        Returns
        -------
        UploadDocumentResponse
        """
        _response = self._raw_client.upload_file(
            file=file,
            upload_as_user_email=upload_as_user_email,
            document_external_id=document_external_id,
            document_name=document_name,
            allowed_users_email_addresses=allowed_users_email_addresses,
            document_external_url=document_external_url,
            custom_metadata=custom_metadata,
            collection_id=collection_id,
            force_update=force_update,
            internal_public=internal_public,
            source_system_updated=source_system_updated,
            await_vector_store_sync=await_vector_store_sync,
            request_options=request_options,
        )
        return _response.data

    def sync_source_by_url(
        self, *, upload_as_user_email: str, source_url: str, request_options: typing.Optional[RequestOptions] = None
    ) -> SyncSourceByUrlResponse:
        """
        Sync a document from a source URL. Does not support recursive web search. Reach out to a Credal representative for access.

        Parameters
        ----------
        upload_as_user_email : str

        source_url : str

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

        Returns
        -------
        SyncSourceByUrlResponse

        Examples
        --------
        from credal import CredalApi

        client = CredalApi(
            api_key="YOUR_API_KEY",
        )
        client.document_catalog.sync_source_by_url(
            source_url="https://drive.google.com/file/d/123456/view",
            upload_as_user_email="ria@credal.ai",
        )
        """
        _response = self._raw_client.sync_source_by_url(
            upload_as_user_email=upload_as_user_email, source_url=source_url, request_options=request_options
        )
        return _response.data

    def metadata(
        self,
        *,
        sources: typing.Sequence[DocumentMetadataPatch],
        upload_as_user_email: str,
        request_options: typing.Optional[RequestOptions] = None,
    ) -> None:
        """
        Bulk patch metadata for documents, synced natively by Credal or manual API uploads

        Parameters
        ----------
        sources : typing.Sequence[DocumentMetadataPatch]

        upload_as_user_email : str

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

        Returns
        -------
        None

        Examples
        --------
        from credal import CredalApi
        from credal.common import ResourceIdentifier_ExternalResourceId
        from credal.document_catalog import DocumentMetadataPatch

        client = CredalApi(
            api_key="YOUR_API_KEY",
        )
        client.document_catalog.metadata(
            sources=[
                DocumentMetadataPatch(
                    metadata={"Department": "HR", "Country": "United States"},
                    resource_identifier=ResourceIdentifier_ExternalResourceId(
                        external_resource_id="170NrBm0Do7gdzvr54UvyslPVWkQFOA0lgNycFmdZJQr",
                        resource_type="GOOGLE_DRIVE_ITEM",
                    ),
                ),
                DocumentMetadataPatch(
                    metadata={"Department": "Sales", "Vertical": "Healthcare"},
                    resource_identifier=ResourceIdentifier_ExternalResourceId(
                        external_resource_id="123456",
                        resource_type="ZENDESK_TICKET",
                    ),
                ),
            ],
            upload_as_user_email="ben@credal.ai",
        )
        """
        _response = self._raw_client.metadata(
            sources=sources, upload_as_user_email=upload_as_user_email, request_options=request_options
        )
        return _response.data


class AsyncDocumentCatalogClient:
    def __init__(self, *, client_wrapper: AsyncClientWrapper):
        self._raw_client = AsyncRawDocumentCatalogClient(client_wrapper=client_wrapper)

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

        Returns
        -------
        AsyncRawDocumentCatalogClient
        """
        return self._raw_client

    async def upload_document_contents(
        self,
        *,
        document_name: str,
        document_contents: str,
        allowed_users_email_addresses: typing.Sequence[str],
        upload_as_user_email: str,
        document_external_id: str,
        document_external_url: typing.Optional[str] = OMIT,
        custom_metadata: typing.Optional[typing.Dict[str, CustomMetadataValue]] = OMIT,
        collection_id: typing.Optional[str] = OMIT,
        force_update: typing.Optional[bool] = OMIT,
        internal_public: typing.Optional[bool] = OMIT,
        await_vector_store_sync: typing.Optional[bool] = OMIT,
        request_options: typing.Optional[RequestOptions] = None,
    ) -> UploadDocumentResponse:
        """
        Parameters
        ----------
        document_name : str
            The name of the document you want to upload.

        document_contents : str
            The full LLM-formatted text contents of the document you want to upload.

        allowed_users_email_addresses : typing.Sequence[str]
            Users allowed to access the document. Unlike Credal's out of the box connectors which reconcile various permissions models from 3rd party software, for custom uploads the caller is responsible for specifying who can access the document and currently flattening groups if applicable. Documents can also be marked as internal public.

        upload_as_user_email : str
            [Legacy] The user on behalf of whom the document should be uploaded. In most cases, this can simply be the email of the developer making the API call. This field will be removed in the future in favor of purely specifying permissions via allowedUsersEmailAddresses.

        document_external_id : str
            The external ID of the document. This is typically the ID as it exists in its original external system. Uploads to the same external ID will update the document in Credal.

        document_external_url : typing.Optional[str]
            The external URL of the document you want to upload. If provided Credal will link to this URL.

        custom_metadata : typing.Optional[typing.Dict[str, CustomMetadataValue]]
            Optional JSON representing any custom metadata for this document

        collection_id : typing.Optional[str]
            If specified, the document will also be added to the provided document collection. This operation is eventually consistent, meaning the document does not immediately start appearing in searches of that collection due to an asynchronous embedding process. To achieve strong consistency use the `awaitVectorStoreSync` parameter.

        force_update : typing.Optional[bool]
            If specified, document contents will be re-uploaded and re-embedded even if the document already exists in Credal

        internal_public : typing.Optional[bool]
            If specified, document will be accessible to everyone within the organization of the uploader

        await_vector_store_sync : typing.Optional[bool]
            Document uploads are eventually consistent by default. If specified `true` the API will wait for the vector store to be updated before returning. This is useful if you want to ensure that the document is immediately searchable after this call returns.

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

        Returns
        -------
        UploadDocumentResponse

        Examples
        --------
        import asyncio

        from credal import AsyncCredalApi

        client = AsyncCredalApi(
            api_key="YOUR_API_KEY",
        )


        async def main() -> None:
            await client.document_catalog.upload_document_contents(
                document_name="My Document",
                document_contents="Lorem ipsum...",
                document_external_id="73eead26-d124-4940-b329-5f068a0a8db9",
                allowed_users_email_addresses=["jack@credal.ai", "ravin@credal.ai"],
                upload_as_user_email="jack@credal.ai",
            )


        asyncio.run(main())
        """
        _response = await self._raw_client.upload_document_contents(
            document_name=document_name,
            document_contents=document_contents,
            allowed_users_email_addresses=allowed_users_email_addresses,
            upload_as_user_email=upload_as_user_email,
            document_external_id=document_external_id,
            document_external_url=document_external_url,
            custom_metadata=custom_metadata,
            collection_id=collection_id,
            force_update=force_update,
            internal_public=internal_public,
            await_vector_store_sync=await_vector_store_sync,
            request_options=request_options,
        )
        return _response.data

    async def upload_file(
        self,
        *,
        file: core.File,
        upload_as_user_email: str,
        document_external_id: str,
        document_name: typing.Optional[str] = OMIT,
        allowed_users_email_addresses: typing.Optional[str] = OMIT,
        document_external_url: typing.Optional[str] = OMIT,
        custom_metadata: typing.Optional[str] = OMIT,
        collection_id: typing.Optional[str] = OMIT,
        force_update: typing.Optional[str] = OMIT,
        internal_public: typing.Optional[str] = OMIT,
        source_system_updated: typing.Optional[str] = OMIT,
        await_vector_store_sync: typing.Optional[str] = OMIT,
        request_options: typing.Optional[RequestOptions] = None,
    ) -> UploadDocumentResponse:
        """
        Upload a file (PDF, Word, Excel, CSV, PowerPoint) to Credal. Unlike uploadDocumentContents which requires pre-parsed text, this endpoint accepts actual file uploads and automatically parses them using Credal's parsing service.

        Parameters
        ----------
        file : core.File
            See core.File for more documentation

        upload_as_user_email : str
            [Legacy] The user on behalf of whom the document should be uploaded. In most cases, this can simply be the email of the developer making the API call. This field will be removed in the future in favor of purely specifying permissions via allowedUsersEmailAddresses.

        document_external_id : str
            The external ID of the document. This is typically the ID as it exists in its original external system. Uploads to the same external ID will update the document in Credal.

        document_name : typing.Optional[str]
            The name of the document you want to upload. If not provided, the original filename will be used.

        allowed_users_email_addresses : typing.Optional[str]
            Users allowed to access the document. Can be provided as a JSON array string (e.g., ["user1@example.com","user2@example.com"]) or comma-separated list (e.g., "user1@example.com,user2@example.com"). Unlike Credal's out of the box connectors which reconcile various permissions models from 3rd party software, for custom uploads the caller is responsible for specifying who can access the document and currently flattening groups if applicable. Documents can also be marked as internal public.

        document_external_url : typing.Optional[str]
            The external URL of the document you want to upload. If provided Credal will link to this URL.

        custom_metadata : typing.Optional[str]
            Optional JSON string representing any custom metadata for this document (e.g., '{"key1":"value1","key2":"value2"}').

        collection_id : typing.Optional[str]
            If specified, the document will also be added to the provided document collection. This operation is eventually consistent, meaning the document does not immediately start appearing in searches of that collection due to an asynchronous embedding process. To achieve strong consistency use the `awaitVectorStoreSync` parameter.

        force_update : typing.Optional[str]
            If set to "true", document contents will be re-uploaded and re-embedded even if the document already exists in Credal.

        internal_public : typing.Optional[str]
            If set to "true", document will be accessible to everyone within the organization of the uploader.

        source_system_updated : typing.Optional[str]
            ISO 8601 date string indicating when the document was last updated in the source system (e.g., "2025-11-03T21:15:00Z").

        await_vector_store_sync : typing.Optional[str]
            Document uploads are eventually consistent by default. If set to "true" the API will wait for the vector store to be updated before returning. This is useful if you want to ensure that the document is immediately searchable after this call returns.

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

        Returns
        -------
        UploadDocumentResponse
        """
        _response = await self._raw_client.upload_file(
            file=file,
            upload_as_user_email=upload_as_user_email,
            document_external_id=document_external_id,
            document_name=document_name,
            allowed_users_email_addresses=allowed_users_email_addresses,
            document_external_url=document_external_url,
            custom_metadata=custom_metadata,
            collection_id=collection_id,
            force_update=force_update,
            internal_public=internal_public,
            source_system_updated=source_system_updated,
            await_vector_store_sync=await_vector_store_sync,
            request_options=request_options,
        )
        return _response.data

    async def sync_source_by_url(
        self, *, upload_as_user_email: str, source_url: str, request_options: typing.Optional[RequestOptions] = None
    ) -> SyncSourceByUrlResponse:
        """
        Sync a document from a source URL. Does not support recursive web search. Reach out to a Credal representative for access.

        Parameters
        ----------
        upload_as_user_email : str

        source_url : str

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

        Returns
        -------
        SyncSourceByUrlResponse

        Examples
        --------
        import asyncio

        from credal import AsyncCredalApi

        client = AsyncCredalApi(
            api_key="YOUR_API_KEY",
        )


        async def main() -> None:
            await client.document_catalog.sync_source_by_url(
                source_url="https://drive.google.com/file/d/123456/view",
                upload_as_user_email="ria@credal.ai",
            )


        asyncio.run(main())
        """
        _response = await self._raw_client.sync_source_by_url(
            upload_as_user_email=upload_as_user_email, source_url=source_url, request_options=request_options
        )
        return _response.data

    async def metadata(
        self,
        *,
        sources: typing.Sequence[DocumentMetadataPatch],
        upload_as_user_email: str,
        request_options: typing.Optional[RequestOptions] = None,
    ) -> None:
        """
        Bulk patch metadata for documents, synced natively by Credal or manual API uploads

        Parameters
        ----------
        sources : typing.Sequence[DocumentMetadataPatch]

        upload_as_user_email : str

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

        Returns
        -------
        None

        Examples
        --------
        import asyncio

        from credal import AsyncCredalApi
        from credal.common import ResourceIdentifier_ExternalResourceId
        from credal.document_catalog import DocumentMetadataPatch

        client = AsyncCredalApi(
            api_key="YOUR_API_KEY",
        )


        async def main() -> None:
            await client.document_catalog.metadata(
                sources=[
                    DocumentMetadataPatch(
                        metadata={"Department": "HR", "Country": "United States"},
                        resource_identifier=ResourceIdentifier_ExternalResourceId(
                            external_resource_id="170NrBm0Do7gdzvr54UvyslPVWkQFOA0lgNycFmdZJQr",
                            resource_type="GOOGLE_DRIVE_ITEM",
                        ),
                    ),
                    DocumentMetadataPatch(
                        metadata={"Department": "Sales", "Vertical": "Healthcare"},
                        resource_identifier=ResourceIdentifier_ExternalResourceId(
                            external_resource_id="123456",
                            resource_type="ZENDESK_TICKET",
                        ),
                    ),
                ],
                upload_as_user_email="ben@credal.ai",
            )


        asyncio.run(main())
        """
        _response = await self._raw_client.metadata(
            sources=sources, upload_as_user_email=upload_as_user_email, request_options=request_options
        )
        return _response.data
