# coding: utf-8

"""
Code generated by OpenAPI Generator (https://openapi-generator.tech), manual changes will be lost - read more on https://github.com/algolia/api-clients-automation. DO NOT EDIT.
"""

from __future__ import annotations

from json import dumps
from sys import version_info
from typing import Any, Optional, Union
from urllib.parse import quote

from pydantic import Field, StrictStr
from typing_extensions import Annotated

if version_info >= (3, 11):
    from typing import Self
else:
    from typing_extensions import Self

from algoliasearch.composition.config import CompositionConfig
from algoliasearch.composition.models import (
    RequestBody,
    SearchForFacetValuesRequest,
    SearchForFacetValuesResponse,
    SearchResponse,
)
from algoliasearch.http.api_response import ApiResponse
from algoliasearch.http.base_config import BaseConfig
from algoliasearch.http.request_options import RequestOptions
from algoliasearch.http.serializer import body_serializer
from algoliasearch.http.transporter import Transporter
from algoliasearch.http.transporter_sync import TransporterSync
from algoliasearch.http.verb import Verb


class CompositionClient:
    """The Algolia 'CompositionClient' class.

    Args:
    app_id (str): The Algolia application ID to retrieve information from.
    api_key (str): The Algolia api key bound to the given `app_id`.


    Returns:
    The initialized API client.

    Example:
    _client = CompositionClient("YOUR_ALGOLIA_APP_ID", "YOUR_ALGOLIA_API_KEY")
    _client_with_named_args = CompositionClient(app_id="YOUR_ALGOLIA_APP_ID", api_key="YOUR_ALGOLIA_API_KEY")

    See `CompositionClient.create_with_config` for advanced configuration.
    """

    _transporter: Transporter
    _config: BaseConfig
    _request_options: RequestOptions

    def __init__(
        self,
        app_id: Optional[str] = None,
        api_key: Optional[str] = None,
        transporter: Optional[Transporter] = None,
        config: Optional[CompositionConfig] = None,
    ) -> None:
        if transporter is not None and config is None:
            config = CompositionConfig(
                transporter.config.app_id, transporter.config.api_key
            )
        elif config is None:
            config = CompositionConfig(app_id, api_key)

        config.set_default_hosts()

        self._config = config
        self._request_options = RequestOptions(config)

        if transporter is None:
            transporter = Transporter(config)
        self._transporter = transporter

    @classmethod
    def create_with_config(
        cls, config: CompositionConfig, transporter: Optional[Transporter] = None
    ) -> CompositionClient:
        """Allows creating a client with a customized `CompositionConfig` and `Transporter`. If `transporter` is not provided, the default one will be initialized from the given `config`.

        Args:
        config (CompositionConfig): The config of the API client.
        transporter (Transporter): The HTTP transporter, see `http/transporter.py` for implementation details.

        Returns:
        The initialized API client.

        Example:
        _client_with_custom_config = CompositionClient.create_with_config(config=CompositionConfig(...))
        _client_with_custom_config_and_transporter = CompositionClient.create_with_config(config=CompositionConfig(...), transporter=Transporter(...))
        """
        if transporter is None:
            transporter = Transporter(config)

        client = CompositionClient(
            app_id=config.app_id,
            api_key=config.api_key,
            transporter=transporter,
            config=config,
        )

        return client

    async def __aenter__(self) -> Self:
        return self

    async def __aexit__(self, exc_type, exc_value, traceback) -> None:
        """Closes the underlying `transporter` of the API client."""
        await self.close()

    async def close(self) -> None:
        """Closes the underlying `transporter` of the API client."""
        return await self._transporter.close()

    async def set_client_api_key(self, api_key: str) -> None:
        """Sets a new API key to authenticate requests."""
        self._transporter.config.set_client_api_key(api_key)

    async def add_user_agent(self, segment: str, version: Optional[str] = None) -> None:
        """adds a segment to the default user agent, and update the headers sent with each requests as well"""
        self._transporter.config.add_user_agent(segment, version)

    async def search_with_http_info(
        self,
        composition_id: Annotated[
            StrictStr, Field(description="Unique Composition ObjectID.")
        ],
        request_body: Union[RequestBody, dict[str, Any]],
        request_options: Optional[Union[dict, RequestOptions]] = None,
    ) -> ApiResponse[str]:
        """
        Runs a query on a single composition and returns matching results.

        Required API Key ACLs:
          - search

        :param composition_id: Unique Composition ObjectID. (required)
        :type composition_id: str
        :param request_body: (required)
        :type request_body: RequestBody
        :param request_options: The request options to send along with the query, they will be merged with the transporter base parameters (headers, query params, timeouts, etc.). (optional)
        :return: Returns the raw algoliasearch 'APIResponse' object.
        """

        if composition_id is None:
            raise ValueError(
                "Parameter `composition_id` is required when calling `search`."
            )

        if request_body is None:
            raise ValueError(
                "Parameter `request_body` is required when calling `search`."
            )

        _data = {}
        if request_body is not None:
            _data = request_body

        return await self._transporter.request(
            verb=Verb.POST,
            path="/1/compositions/{compositionID}/run".replace(
                "{compositionID}", quote(str(composition_id), safe="")
            ),
            request_options=self._request_options.merge(
                data=dumps(body_serializer(_data)),
                user_request_options=request_options,
            ),
            use_read_transporter=True,
        )

    async def search(
        self,
        composition_id: Annotated[
            StrictStr, Field(description="Unique Composition ObjectID.")
        ],
        request_body: Union[RequestBody, dict[str, Any]],
        request_options: Optional[Union[dict, RequestOptions]] = None,
    ) -> SearchResponse:
        """
        Runs a query on a single composition and returns matching results.

        Required API Key ACLs:
          - search

        :param composition_id: Unique Composition ObjectID. (required)
        :type composition_id: str
        :param request_body: (required)
        :type request_body: RequestBody
        :param request_options: The request options to send along with the query, they will be merged with the transporter base parameters (headers, query params, timeouts, etc.). (optional)
        :return: Returns the deserialized response in a 'SearchResponse' result object.
        """
        resp = await self.search_with_http_info(
            composition_id, request_body, request_options
        )
        return resp.deserialize(SearchResponse, resp.raw_data)

    async def search_for_facet_values_with_http_info(
        self,
        composition_id: Annotated[
            StrictStr, Field(description="Unique Composition ObjectID.")
        ],
        facet_name: Annotated[
            StrictStr,
            Field(
                description="Facet attribute in which to search for values.  This attribute must be included in the `attributesForFaceting` index setting with the `searchable()` modifier. "
            ),
        ],
        search_for_facet_values_request: Union[
            Optional[SearchForFacetValuesRequest], dict[str, Any]
        ] = None,
        request_options: Optional[Union[dict, RequestOptions]] = None,
    ) -> ApiResponse[str]:
        """
        Searches for values of a specified facet attribute on the composition's main source's index.  - By default, facet values are sorted by decreasing count.   You can adjust this with the `sortFacetValueBy` parameter. - Searching for facet values doesn't work if you have **more than 65 searchable facets and searchable attributes combined**.

        Required API Key ACLs:
          - search

        :param composition_id: Unique Composition ObjectID. (required)
        :type composition_id: str
        :param facet_name: Facet attribute in which to search for values.  This attribute must be included in the `attributesForFaceting` index setting with the `searchable()` modifier.  (required)
        :type facet_name: str
        :param search_for_facet_values_request:
        :type search_for_facet_values_request: SearchForFacetValuesRequest
        :param request_options: The request options to send along with the query, they will be merged with the transporter base parameters (headers, query params, timeouts, etc.). (optional)
        :return: Returns the raw algoliasearch 'APIResponse' object.
        """

        if composition_id is None:
            raise ValueError(
                "Parameter `composition_id` is required when calling `search_for_facet_values`."
            )

        if facet_name is None:
            raise ValueError(
                "Parameter `facet_name` is required when calling `search_for_facet_values`."
            )

        _data = {}
        if search_for_facet_values_request is not None:
            _data = search_for_facet_values_request

        return await self._transporter.request(
            verb=Verb.POST,
            path="/1/compositions/{compositionID}/facets/{facetName}/query".replace(
                "{compositionID}", quote(str(composition_id), safe="")
            ).replace("{facetName}", quote(str(facet_name), safe="")),
            request_options=self._request_options.merge(
                data=dumps(body_serializer(_data)),
                user_request_options=request_options,
            ),
            use_read_transporter=True,
        )

    async def search_for_facet_values(
        self,
        composition_id: Annotated[
            StrictStr, Field(description="Unique Composition ObjectID.")
        ],
        facet_name: Annotated[
            StrictStr,
            Field(
                description="Facet attribute in which to search for values.  This attribute must be included in the `attributesForFaceting` index setting with the `searchable()` modifier. "
            ),
        ],
        search_for_facet_values_request: Union[
            Optional[SearchForFacetValuesRequest], dict[str, Any]
        ] = None,
        request_options: Optional[Union[dict, RequestOptions]] = None,
    ) -> SearchForFacetValuesResponse:
        """
        Searches for values of a specified facet attribute on the composition's main source's index.  - By default, facet values are sorted by decreasing count.   You can adjust this with the `sortFacetValueBy` parameter. - Searching for facet values doesn't work if you have **more than 65 searchable facets and searchable attributes combined**.

        Required API Key ACLs:
          - search

        :param composition_id: Unique Composition ObjectID. (required)
        :type composition_id: str
        :param facet_name: Facet attribute in which to search for values.  This attribute must be included in the `attributesForFaceting` index setting with the `searchable()` modifier.  (required)
        :type facet_name: str
        :param search_for_facet_values_request:
        :type search_for_facet_values_request: SearchForFacetValuesRequest
        :param request_options: The request options to send along with the query, they will be merged with the transporter base parameters (headers, query params, timeouts, etc.). (optional)
        :return: Returns the deserialized response in a 'SearchForFacetValuesResponse' result object.
        """
        resp = await self.search_for_facet_values_with_http_info(
            composition_id, facet_name, search_for_facet_values_request, request_options
        )
        return resp.deserialize(SearchForFacetValuesResponse, resp.raw_data)


class CompositionClientSync:
    """The Algolia 'CompositionClientSync' class.

    Args:
    app_id (str): The Algolia application ID to retrieve information from.
    api_key (str): The Algolia api key bound to the given `app_id`.


    Returns:
    The initialized API client.

    Example:
    _client = CompositionClientSync("YOUR_ALGOLIA_APP_ID", "YOUR_ALGOLIA_API_KEY")
    _client_with_named_args = CompositionClientSync(app_id="YOUR_ALGOLIA_APP_ID", api_key="YOUR_ALGOLIA_API_KEY")

    See `CompositionClientSync.create_with_config` for advanced configuration.
    """

    _transporter: TransporterSync
    _config: BaseConfig
    _request_options: RequestOptions

    def __init__(
        self,
        app_id: Optional[str] = None,
        api_key: Optional[str] = None,
        transporter: Optional[TransporterSync] = None,
        config: Optional[CompositionConfig] = None,
    ) -> None:
        if transporter is not None and config is None:
            config = CompositionConfig(
                transporter.config.app_id, transporter.config.api_key
            )
        elif config is None:
            config = CompositionConfig(app_id, api_key)

        config.set_default_hosts()

        self._config = config
        self._request_options = RequestOptions(config)

        if transporter is None:
            transporter = TransporterSync(config)
        self._transporter = transporter

    @classmethod
    def create_with_config(
        cls, config: CompositionConfig, transporter: Optional[TransporterSync] = None
    ) -> CompositionClientSync:
        """Allows creating a client with a customized `CompositionConfig` and `TransporterSync`. If `transporter` is not provided, the default one will be initialized from the given `config`.

        Args:
        config (CompositionConfig): The config of the API client.
        transporter (TransporterSync): The HTTP transporter, see `http/transporter.py` for implementation details.

        Returns:
        The initialized API client.

        Example:
        _client_with_custom_config = CompositionClientSync.create_with_config(config=CompositionConfig(...))
        _client_with_custom_config_and_transporter = CompositionClientSync.create_with_config(config=CompositionConfig(...), transporter=TransporterSync(...))
        """
        if transporter is None:
            transporter = TransporterSync(config)

        client = CompositionClientSync(
            app_id=config.app_id,
            api_key=config.api_key,
            transporter=transporter,
            config=config,
        )

        return client

    def __enter__(self) -> Self:
        return self

    def __exit__(self, exc_type, exc_value, traceback) -> None:
        """Closes the underlying `transporter` of the API client."""
        self.close()

    def close(self) -> None:
        return self._transporter.close()

    def set_client_api_key(self, api_key: str) -> None:
        """Sets a new API key to authenticate requests."""
        self._transporter.config.set_client_api_key(api_key)

    def add_user_agent(self, segment: str, version: Optional[str] = None) -> None:
        """adds a segment to the default user agent, and update the headers sent with each requests as well"""
        self._transporter.config.add_user_agent(segment, version)

    def search_with_http_info(
        self,
        composition_id: Annotated[
            StrictStr, Field(description="Unique Composition ObjectID.")
        ],
        request_body: Union[RequestBody, dict[str, Any]],
        request_options: Optional[Union[dict, RequestOptions]] = None,
    ) -> ApiResponse[str]:
        """
        Runs a query on a single composition and returns matching results.

        Required API Key ACLs:
          - search

        :param composition_id: Unique Composition ObjectID. (required)
        :type composition_id: str
        :param request_body: (required)
        :type request_body: RequestBody
        :param request_options: The request options to send along with the query, they will be merged with the transporter base parameters (headers, query params, timeouts, etc.). (optional)
        :return: Returns the raw algoliasearch 'APIResponse' object.
        """

        if composition_id is None:
            raise ValueError(
                "Parameter `composition_id` is required when calling `search`."
            )

        if request_body is None:
            raise ValueError(
                "Parameter `request_body` is required when calling `search`."
            )

        _data = {}
        if request_body is not None:
            _data = request_body

        return self._transporter.request(
            verb=Verb.POST,
            path="/1/compositions/{compositionID}/run".replace(
                "{compositionID}", quote(str(composition_id), safe="")
            ),
            request_options=self._request_options.merge(
                data=dumps(body_serializer(_data)),
                user_request_options=request_options,
            ),
            use_read_transporter=True,
        )

    def search(
        self,
        composition_id: Annotated[
            StrictStr, Field(description="Unique Composition ObjectID.")
        ],
        request_body: Union[RequestBody, dict[str, Any]],
        request_options: Optional[Union[dict, RequestOptions]] = None,
    ) -> SearchResponse:
        """
        Runs a query on a single composition and returns matching results.

        Required API Key ACLs:
          - search

        :param composition_id: Unique Composition ObjectID. (required)
        :type composition_id: str
        :param request_body: (required)
        :type request_body: RequestBody
        :param request_options: The request options to send along with the query, they will be merged with the transporter base parameters (headers, query params, timeouts, etc.). (optional)
        :return: Returns the deserialized response in a 'SearchResponse' result object.
        """
        resp = self.search_with_http_info(composition_id, request_body, request_options)
        return resp.deserialize(SearchResponse, resp.raw_data)

    def search_for_facet_values_with_http_info(
        self,
        composition_id: Annotated[
            StrictStr, Field(description="Unique Composition ObjectID.")
        ],
        facet_name: Annotated[
            StrictStr,
            Field(
                description="Facet attribute in which to search for values.  This attribute must be included in the `attributesForFaceting` index setting with the `searchable()` modifier. "
            ),
        ],
        search_for_facet_values_request: Union[
            Optional[SearchForFacetValuesRequest], dict[str, Any]
        ] = None,
        request_options: Optional[Union[dict, RequestOptions]] = None,
    ) -> ApiResponse[str]:
        """
        Searches for values of a specified facet attribute on the composition's main source's index.  - By default, facet values are sorted by decreasing count.   You can adjust this with the `sortFacetValueBy` parameter. - Searching for facet values doesn't work if you have **more than 65 searchable facets and searchable attributes combined**.

        Required API Key ACLs:
          - search

        :param composition_id: Unique Composition ObjectID. (required)
        :type composition_id: str
        :param facet_name: Facet attribute in which to search for values.  This attribute must be included in the `attributesForFaceting` index setting with the `searchable()` modifier.  (required)
        :type facet_name: str
        :param search_for_facet_values_request:
        :type search_for_facet_values_request: SearchForFacetValuesRequest
        :param request_options: The request options to send along with the query, they will be merged with the transporter base parameters (headers, query params, timeouts, etc.). (optional)
        :return: Returns the raw algoliasearch 'APIResponse' object.
        """

        if composition_id is None:
            raise ValueError(
                "Parameter `composition_id` is required when calling `search_for_facet_values`."
            )

        if facet_name is None:
            raise ValueError(
                "Parameter `facet_name` is required when calling `search_for_facet_values`."
            )

        _data = {}
        if search_for_facet_values_request is not None:
            _data = search_for_facet_values_request

        return self._transporter.request(
            verb=Verb.POST,
            path="/1/compositions/{compositionID}/facets/{facetName}/query".replace(
                "{compositionID}", quote(str(composition_id), safe="")
            ).replace("{facetName}", quote(str(facet_name), safe="")),
            request_options=self._request_options.merge(
                data=dumps(body_serializer(_data)),
                user_request_options=request_options,
            ),
            use_read_transporter=True,
        )

    def search_for_facet_values(
        self,
        composition_id: Annotated[
            StrictStr, Field(description="Unique Composition ObjectID.")
        ],
        facet_name: Annotated[
            StrictStr,
            Field(
                description="Facet attribute in which to search for values.  This attribute must be included in the `attributesForFaceting` index setting with the `searchable()` modifier. "
            ),
        ],
        search_for_facet_values_request: Union[
            Optional[SearchForFacetValuesRequest], dict[str, Any]
        ] = None,
        request_options: Optional[Union[dict, RequestOptions]] = None,
    ) -> SearchForFacetValuesResponse:
        """
        Searches for values of a specified facet attribute on the composition's main source's index.  - By default, facet values are sorted by decreasing count.   You can adjust this with the `sortFacetValueBy` parameter. - Searching for facet values doesn't work if you have **more than 65 searchable facets and searchable attributes combined**.

        Required API Key ACLs:
          - search

        :param composition_id: Unique Composition ObjectID. (required)
        :type composition_id: str
        :param facet_name: Facet attribute in which to search for values.  This attribute must be included in the `attributesForFaceting` index setting with the `searchable()` modifier.  (required)
        :type facet_name: str
        :param search_for_facet_values_request:
        :type search_for_facet_values_request: SearchForFacetValuesRequest
        :param request_options: The request options to send along with the query, they will be merged with the transporter base parameters (headers, query params, timeouts, etc.). (optional)
        :return: Returns the deserialized response in a 'SearchForFacetValuesResponse' result object.
        """
        resp = self.search_for_facet_values_with_http_info(
            composition_id, facet_name, search_for_facet_values_request, request_options
        )
        return resp.deserialize(SearchForFacetValuesResponse, resp.raw_data)
