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

import typing
from json.decoder import JSONDecodeError

from ..core.api_error import ApiError
from ..core.client_wrapper import AsyncClientWrapper, SyncClientWrapper
from ..core.http_response import AsyncHttpResponse, HttpResponse
from ..core.pydantic_utilities import parse_obj_as
from ..core.request_options import RequestOptions
from ..core.serialization import convert_and_respect_annotation_metadata
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 RawDocumentCatalogClient:
    def __init__(self, *, client_wrapper: SyncClientWrapper):
        self._client_wrapper = client_wrapper

    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.Optional[typing.Any]] = OMIT,
        collection_id: typing.Optional[str] = OMIT,
        force_update: typing.Optional[bool] = OMIT,
        internal_public: typing.Optional[bool] = OMIT,
        request_options: typing.Optional[RequestOptions] = None,
    ) -> HttpResponse[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.Optional[typing.Any]]
            Optional JSON representing any custom metdata for this document

        collection_id : typing.Optional[str]
            If specified, document will also be added to a particular document collection

        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

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

        Returns
        -------
        HttpResponse[UploadDocumentResponse]
        """
        _response = self._client_wrapper.httpx_client.request(
            "v0/catalog/uploadDocumentContents",
            method="POST",
            json={
                "documentName": document_name,
                "documentContents": document_contents,
                "allowedUsersEmailAddresses": allowed_users_email_addresses,
                "uploadAsUserEmail": upload_as_user_email,
                "documentExternalId": document_external_id,
                "documentExternalUrl": document_external_url,
                "customMetadata": custom_metadata,
                "collectionId": collection_id,
                "forceUpdate": force_update,
                "internalPublic": internal_public,
            },
            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)
            _response_json = _response.json()
        except JSONDecodeError:
            raise ApiError(status_code=_response.status_code, headers=dict(_response.headers), body=_response.text)
        raise ApiError(status_code=_response.status_code, headers=dict(_response.headers), body=_response_json)

    def sync_source_by_url(
        self, *, upload_as_user_email: str, source_url: str, request_options: typing.Optional[RequestOptions] = None
    ) -> HttpResponse[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
        -------
        HttpResponse[SyncSourceByUrlResponse]
        """
        _response = self._client_wrapper.httpx_client.request(
            "v0/catalog/syncSourceByUrl",
            method="POST",
            json={
                "uploadAsUserEmail": upload_as_user_email,
                "sourceUrl": source_url,
            },
            request_options=request_options,
            omit=OMIT,
        )
        try:
            if 200 <= _response.status_code < 300:
                _data = typing.cast(
                    SyncSourceByUrlResponse,
                    parse_obj_as(
                        type_=SyncSourceByUrlResponse,  # type: ignore
                        object_=_response.json(),
                    ),
                )
                return HttpResponse(response=_response, data=_data)
            _response_json = _response.json()
        except JSONDecodeError:
            raise ApiError(status_code=_response.status_code, headers=dict(_response.headers), body=_response.text)
        raise ApiError(status_code=_response.status_code, headers=dict(_response.headers), body=_response_json)

    def metadata(
        self,
        *,
        sources: typing.Sequence[DocumentMetadataPatch],
        upload_as_user_email: str,
        request_options: typing.Optional[RequestOptions] = None,
    ) -> HttpResponse[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
        -------
        HttpResponse[None]
        """
        _response = self._client_wrapper.httpx_client.request(
            "v0/catalog/metadata",
            method="PATCH",
            json={
                "sources": convert_and_respect_annotation_metadata(
                    object_=sources, annotation=typing.Sequence[DocumentMetadataPatch], direction="write"
                ),
                "uploadAsUserEmail": upload_as_user_email,
            },
            request_options=request_options,
            omit=OMIT,
        )
        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, headers=dict(_response.headers), body=_response.text)
        raise ApiError(status_code=_response.status_code, headers=dict(_response.headers), body=_response_json)


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

    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.Optional[typing.Any]] = OMIT,
        collection_id: typing.Optional[str] = OMIT,
        force_update: typing.Optional[bool] = OMIT,
        internal_public: typing.Optional[bool] = OMIT,
        request_options: typing.Optional[RequestOptions] = None,
    ) -> AsyncHttpResponse[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.Optional[typing.Any]]
            Optional JSON representing any custom metdata for this document

        collection_id : typing.Optional[str]
            If specified, document will also be added to a particular document collection

        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

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

        Returns
        -------
        AsyncHttpResponse[UploadDocumentResponse]
        """
        _response = await self._client_wrapper.httpx_client.request(
            "v0/catalog/uploadDocumentContents",
            method="POST",
            json={
                "documentName": document_name,
                "documentContents": document_contents,
                "allowedUsersEmailAddresses": allowed_users_email_addresses,
                "uploadAsUserEmail": upload_as_user_email,
                "documentExternalId": document_external_id,
                "documentExternalUrl": document_external_url,
                "customMetadata": custom_metadata,
                "collectionId": collection_id,
                "forceUpdate": force_update,
                "internalPublic": internal_public,
            },
            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)
            _response_json = _response.json()
        except JSONDecodeError:
            raise ApiError(status_code=_response.status_code, headers=dict(_response.headers), body=_response.text)
        raise ApiError(status_code=_response.status_code, headers=dict(_response.headers), body=_response_json)

    async def sync_source_by_url(
        self, *, upload_as_user_email: str, source_url: str, request_options: typing.Optional[RequestOptions] = None
    ) -> AsyncHttpResponse[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
        -------
        AsyncHttpResponse[SyncSourceByUrlResponse]
        """
        _response = await self._client_wrapper.httpx_client.request(
            "v0/catalog/syncSourceByUrl",
            method="POST",
            json={
                "uploadAsUserEmail": upload_as_user_email,
                "sourceUrl": source_url,
            },
            request_options=request_options,
            omit=OMIT,
        )
        try:
            if 200 <= _response.status_code < 300:
                _data = typing.cast(
                    SyncSourceByUrlResponse,
                    parse_obj_as(
                        type_=SyncSourceByUrlResponse,  # type: ignore
                        object_=_response.json(),
                    ),
                )
                return AsyncHttpResponse(response=_response, data=_data)
            _response_json = _response.json()
        except JSONDecodeError:
            raise ApiError(status_code=_response.status_code, headers=dict(_response.headers), body=_response.text)
        raise ApiError(status_code=_response.status_code, headers=dict(_response.headers), body=_response_json)

    async def metadata(
        self,
        *,
        sources: typing.Sequence[DocumentMetadataPatch],
        upload_as_user_email: str,
        request_options: typing.Optional[RequestOptions] = None,
    ) -> AsyncHttpResponse[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
        -------
        AsyncHttpResponse[None]
        """
        _response = await self._client_wrapper.httpx_client.request(
            "v0/catalog/metadata",
            method="PATCH",
            json={
                "sources": convert_and_respect_annotation_metadata(
                    object_=sources, annotation=typing.Sequence[DocumentMetadataPatch], direction="write"
                ),
                "uploadAsUserEmail": upload_as_user_email,
            },
            request_options=request_options,
            omit=OMIT,
        )
        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, headers=dict(_response.headers), body=_response.text)
        raise ApiError(status_code=_response.status_code, headers=dict(_response.headers), body=_response_json)
