# coding=utf-8
# --------------------------------------------------------------------------
# Code generated by Microsoft (R) AutoRest Code Generator (autorest: 3.9.5, generator: @autorest/python@6.39.0)
# Changes may cause incorrect behavior and will be lost if the code is regenerated.
# --------------------------------------------------------------------------
from collections.abc import MutableMapping
from io import IOBase
from typing import Any, Callable, IO, Optional, TypeVar, Union, overload

from azure.core import PipelineClient
from azure.core.exceptions import (
    ClientAuthenticationError,
    HttpResponseError,
    ResourceExistsError,
    ResourceNotFoundError,
    ResourceNotModifiedError,
    map_error,
)
from azure.core.pipeline import PipelineResponse
from azure.core.rest import HttpRequest, HttpResponse
from azure.core.tracing.decorator import distributed_trace
from azure.core.utils import case_insensitive_dict

from .. import models as _models
from .._configuration import KnowledgeAgentRetrievalClientConfiguration
from .._utils.serialization import Deserializer, Serializer

T = TypeVar("T")
ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, dict[str, Any]], Any]]

_SERIALIZER = Serializer()
_SERIALIZER.client_side_validation = False


def build_retrieve_request(
    *,
    x_ms_client_request_id: Optional[str] = None,
    x_ms_query_source_authorization: Optional[str] = None,
    **kwargs: Any
) -> HttpRequest:
    _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
    _params = case_insensitive_dict(kwargs.pop("params", {}) or {})

    api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2025-08-01-preview"))
    content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None))
    accept = _headers.pop("Accept", "application/json")

    # Construct URL
    _url = kwargs.pop("template_url", "/retrieve")

    # Construct parameters
    _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str")

    # Construct headers
    if x_ms_client_request_id is not None:
        _headers["x-ms-client-request-id"] = _SERIALIZER.header("x_ms_client_request_id", x_ms_client_request_id, "str")
    if x_ms_query_source_authorization is not None:
        _headers["x-ms-query-source-authorization"] = _SERIALIZER.header(
            "x_ms_query_source_authorization", x_ms_query_source_authorization, "str"
        )
    if content_type is not None:
        _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str")
    _headers["Accept"] = _SERIALIZER.header("accept", accept, "str")

    return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs)


class KnowledgeRetrievalOperations:
    """
    .. warning::
        **DO NOT** instantiate this class directly.

        Instead, you should access the following operations through
        :class:`~azure.search.documents.agent.KnowledgeAgentRetrievalClient`'s
        :attr:`knowledge_retrieval` attribute.
    """

    models = _models

    def __init__(self, *args, **kwargs) -> None:
        input_args = list(args)
        self._client: PipelineClient = input_args.pop(0) if input_args else kwargs.pop("client")
        self._config: KnowledgeAgentRetrievalClientConfiguration = (
            input_args.pop(0) if input_args else kwargs.pop("config")
        )
        self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer")
        self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer")

    @overload
    def retrieve(
        self,
        retrieval_request: _models.KnowledgeAgentRetrievalRequest,
        x_ms_query_source_authorization: Optional[str] = None,
        request_options: Optional[_models.RequestOptions] = None,
        *,
        content_type: str = "application/json",
        **kwargs: Any
    ) -> _models.KnowledgeAgentRetrievalResponse:
        """KnowledgeAgent retrieves relevant data from backing stores.

        :param retrieval_request: The retrieval request to process. Required.
        :type retrieval_request: ~azure.search.documents.agent.models.KnowledgeAgentRetrievalRequest
        :param x_ms_query_source_authorization: Token identifying the user for which the query is being
         executed. This token is used to enforce security restrictions on documents. Default value is
         None.
        :type x_ms_query_source_authorization: str
        :param request_options: Parameter group. Default value is None.
        :type request_options: ~azure.search.documents.agent.models.RequestOptions
        :keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
         Default value is "application/json".
        :paramtype content_type: str
        :return: KnowledgeAgentRetrievalResponse or the result of cls(response)
        :rtype: ~azure.search.documents.agent.models.KnowledgeAgentRetrievalResponse
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @overload
    def retrieve(
        self,
        retrieval_request: IO[bytes],
        x_ms_query_source_authorization: Optional[str] = None,
        request_options: Optional[_models.RequestOptions] = None,
        *,
        content_type: str = "application/json",
        **kwargs: Any
    ) -> _models.KnowledgeAgentRetrievalResponse:
        """KnowledgeAgent retrieves relevant data from backing stores.

        :param retrieval_request: The retrieval request to process. Required.
        :type retrieval_request: IO[bytes]
        :param x_ms_query_source_authorization: Token identifying the user for which the query is being
         executed. This token is used to enforce security restrictions on documents. Default value is
         None.
        :type x_ms_query_source_authorization: str
        :param request_options: Parameter group. Default value is None.
        :type request_options: ~azure.search.documents.agent.models.RequestOptions
        :keyword content_type: Body Parameter content-type. Content type parameter for binary body.
         Default value is "application/json".
        :paramtype content_type: str
        :return: KnowledgeAgentRetrievalResponse or the result of cls(response)
        :rtype: ~azure.search.documents.agent.models.KnowledgeAgentRetrievalResponse
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @distributed_trace
    def retrieve(
        self,
        retrieval_request: Union[_models.KnowledgeAgentRetrievalRequest, IO[bytes]],
        x_ms_query_source_authorization: Optional[str] = None,
        request_options: Optional[_models.RequestOptions] = None,
        **kwargs: Any
    ) -> _models.KnowledgeAgentRetrievalResponse:
        """KnowledgeAgent retrieves relevant data from backing stores.

        :param retrieval_request: The retrieval request to process. Is either a
         KnowledgeAgentRetrievalRequest type or a IO[bytes] type. Required.
        :type retrieval_request: ~azure.search.documents.agent.models.KnowledgeAgentRetrievalRequest or
         IO[bytes]
        :param x_ms_query_source_authorization: Token identifying the user for which the query is being
         executed. This token is used to enforce security restrictions on documents. Default value is
         None.
        :type x_ms_query_source_authorization: str
        :param request_options: Parameter group. Default value is None.
        :type request_options: ~azure.search.documents.agent.models.RequestOptions
        :return: KnowledgeAgentRetrievalResponse or the result of cls(response)
        :rtype: ~azure.search.documents.agent.models.KnowledgeAgentRetrievalResponse
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
        _params = case_insensitive_dict(kwargs.pop("params", {}) or {})

        api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version))
        content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None))
        cls: ClsType[_models.KnowledgeAgentRetrievalResponse] = kwargs.pop("cls", None)

        _x_ms_client_request_id = None
        if request_options is not None:
            _x_ms_client_request_id = request_options.x_ms_client_request_id
        content_type = content_type or "application/json"
        _json = None
        _content = None
        if isinstance(retrieval_request, (IOBase, bytes)):
            _content = retrieval_request
        else:
            _json = self._serialize.body(retrieval_request, "KnowledgeAgentRetrievalRequest")

        _request = build_retrieve_request(
            x_ms_client_request_id=_x_ms_client_request_id,
            x_ms_query_source_authorization=x_ms_query_source_authorization,
            api_version=api_version,
            content_type=content_type,
            json=_json,
            content=_content,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True),
            "agentName": self._serialize.url("self._config.agent_name", self._config.agent_name, "str"),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _stream = False
        pipeline_response: PipelineResponse = self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200]:
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response)
            raise HttpResponseError(response=response, model=error)

        deserialized = self._deserialize("KnowledgeAgentRetrievalResponse", pipeline_response.http_response)

        if cls:
            return cls(pipeline_response, deserialized, {})  # type: ignore

        return deserialized  # type: ignore
