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

import typing
import urllib.parse
import uuid
from json.decoder import JSONDecodeError

from ..core.api_error import ApiError
from ..core.client_wrapper import AsyncClientWrapper, SyncClientWrapper
from ..core.jsonable_encoder import jsonable_encoder
from ..core.pydantic_utilities import pydantic_v1
from ..core.query_encoder import encode_query
from ..core.remove_none_from_dict import remove_none_from_dict
from ..core.request_options import RequestOptions
from .types.document_collection_search_options import DocumentCollectionSearchOptions
from .types.search_document_collection_response import SearchDocumentCollectionResponse
from .types.single_field_filter import SingleFieldFilter

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


class SearchClient:
    def __init__(self, *, client_wrapper: SyncClientWrapper):
        self._client_wrapper = client_wrapper

    def search_document_collection(
        self,
        *,
        document_collection_id: uuid.UUID,
        search_query: str,
        user_email: str,
        structured_query_filters: typing.Sequence[SingleFieldFilter],
        search_options: typing.Optional[DocumentCollectionSearchOptions] = OMIT,
        metadata_filter_expression: typing.Optional[str] = OMIT,
        request_options: typing.Optional[RequestOptions] = None,
    ) -> SearchDocumentCollectionResponse:
        """
        Search across all documents in a document collection using the document metadata and contents.

        Parameters
        ----------
        document_collection_id : uuid.UUID

        search_query : str

        user_email : str
            The email of the user making the search request for permissions reduction.


        structured_query_filters : typing.Sequence[SingleFieldFilter]
            The structured query filters to apply to the search query.


        search_options : typing.Optional[DocumentCollectionSearchOptions]

        metadata_filter_expression : typing.Optional[str]
            Legacy metadata filter expression to apply to the search query. Use structuredQueryFilters instead.


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

        Returns
        -------
        SearchDocumentCollectionResponse

        Examples
        --------
        import uuid

        from credal import DocumentCollectionSearchOptions, SingleFieldFilter
        from credal.client import CredalApi

        client = CredalApi(
            api_key="YOUR_API_KEY",
        )
        client.search.search_document_collection(
            document_collection_id=uuid.UUID(
                "82e4b12a-6990-45d4-8ebd-85c00e030c24",
            ),
            search_query="ABC Corp",
            structured_query_filters=[
                SingleFieldFilter(
                    field="status",
                    operator="==",
                    value="Open",
                )
            ],
            user_email="jack@credal.ai",
            search_options=DocumentCollectionSearchOptions(
                max_chunks=10,
                merge_contents=True,
                threshold=0.8,
                enable_smart_filtering=True,
                enable_query_extraction=True,
                enable_reranking=True,
            ),
        )
        """
        _request: typing.Dict[str, typing.Any] = {
            "documentCollectionId": document_collection_id,
            "searchQuery": search_query,
            "userEmail": user_email,
            "structuredQueryFilters": structured_query_filters,
        }
        if search_options is not OMIT:
            _request["searchOptions"] = search_options
        if metadata_filter_expression is not OMIT:
            _request["metadataFilterExpression"] = metadata_filter_expression
        _response = self._client_wrapper.httpx_client.request(
            method="POST",
            url=urllib.parse.urljoin(f"{self._client_wrapper.get_base_url()}/", "v0/search/searchDocumentCollection"),
            params=encode_query(
                jsonable_encoder(
                    request_options.get("additional_query_parameters") if request_options is not None else None
                )
            ),
            json=jsonable_encoder(_request)
            if request_options is None or request_options.get("additional_body_parameters") is None
            else {
                **jsonable_encoder(_request),
                **(jsonable_encoder(remove_none_from_dict(request_options.get("additional_body_parameters", {})))),
            },
            headers=jsonable_encoder(
                remove_none_from_dict(
                    {
                        **self._client_wrapper.get_headers(),
                        **(request_options.get("additional_headers", {}) if request_options is not None else {}),
                    }
                )
            ),
            timeout=request_options.get("timeout_in_seconds")
            if request_options is not None and request_options.get("timeout_in_seconds") is not None
            else self._client_wrapper.get_timeout(),
            retries=0,
            max_retries=request_options.get("max_retries") if request_options is not None else 0,  # type: ignore
        )
        if 200 <= _response.status_code < 300:
            return pydantic_v1.parse_obj_as(SearchDocumentCollectionResponse, _response.json())  # type: ignore
        try:
            _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 AsyncSearchClient:
    def __init__(self, *, client_wrapper: AsyncClientWrapper):
        self._client_wrapper = client_wrapper

    async def search_document_collection(
        self,
        *,
        document_collection_id: uuid.UUID,
        search_query: str,
        user_email: str,
        structured_query_filters: typing.Sequence[SingleFieldFilter],
        search_options: typing.Optional[DocumentCollectionSearchOptions] = OMIT,
        metadata_filter_expression: typing.Optional[str] = OMIT,
        request_options: typing.Optional[RequestOptions] = None,
    ) -> SearchDocumentCollectionResponse:
        """
        Search across all documents in a document collection using the document metadata and contents.

        Parameters
        ----------
        document_collection_id : uuid.UUID

        search_query : str

        user_email : str
            The email of the user making the search request for permissions reduction.


        structured_query_filters : typing.Sequence[SingleFieldFilter]
            The structured query filters to apply to the search query.


        search_options : typing.Optional[DocumentCollectionSearchOptions]

        metadata_filter_expression : typing.Optional[str]
            Legacy metadata filter expression to apply to the search query. Use structuredQueryFilters instead.


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

        Returns
        -------
        SearchDocumentCollectionResponse

        Examples
        --------
        import uuid

        from credal import DocumentCollectionSearchOptions, SingleFieldFilter
        from credal.client import AsyncCredalApi

        client = AsyncCredalApi(
            api_key="YOUR_API_KEY",
        )
        await client.search.search_document_collection(
            document_collection_id=uuid.UUID(
                "82e4b12a-6990-45d4-8ebd-85c00e030c24",
            ),
            search_query="ABC Corp",
            structured_query_filters=[
                SingleFieldFilter(
                    field="status",
                    operator="==",
                    value="Open",
                )
            ],
            user_email="jack@credal.ai",
            search_options=DocumentCollectionSearchOptions(
                max_chunks=10,
                merge_contents=True,
                threshold=0.8,
                enable_smart_filtering=True,
                enable_query_extraction=True,
                enable_reranking=True,
            ),
        )
        """
        _request: typing.Dict[str, typing.Any] = {
            "documentCollectionId": document_collection_id,
            "searchQuery": search_query,
            "userEmail": user_email,
            "structuredQueryFilters": structured_query_filters,
        }
        if search_options is not OMIT:
            _request["searchOptions"] = search_options
        if metadata_filter_expression is not OMIT:
            _request["metadataFilterExpression"] = metadata_filter_expression
        _response = await self._client_wrapper.httpx_client.request(
            method="POST",
            url=urllib.parse.urljoin(f"{self._client_wrapper.get_base_url()}/", "v0/search/searchDocumentCollection"),
            params=encode_query(
                jsonable_encoder(
                    request_options.get("additional_query_parameters") if request_options is not None else None
                )
            ),
            json=jsonable_encoder(_request)
            if request_options is None or request_options.get("additional_body_parameters") is None
            else {
                **jsonable_encoder(_request),
                **(jsonable_encoder(remove_none_from_dict(request_options.get("additional_body_parameters", {})))),
            },
            headers=jsonable_encoder(
                remove_none_from_dict(
                    {
                        **self._client_wrapper.get_headers(),
                        **(request_options.get("additional_headers", {}) if request_options is not None else {}),
                    }
                )
            ),
            timeout=request_options.get("timeout_in_seconds")
            if request_options is not None and request_options.get("timeout_in_seconds") is not None
            else self._client_wrapper.get_timeout(),
            retries=0,
            max_retries=request_options.get("max_retries") if request_options is not None else 0,  # type: ignore
        )
        if 200 <= _response.status_code < 300:
            return pydantic_v1.parse_obj_as(SearchDocumentCollectionResponse, _response.json())  # type: ignore
        try:
            _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)
