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

from ..core.client_wrapper import SyncClientWrapper
import typing
from ..core.request_options import RequestOptions
from ..types.query_history import QueryHistory
from ..core.jsonable_encoder import jsonable_encoder
from ..core.pydantic_utilities import parse_obj_as
from ..errors.forbidden_error import ForbiddenError
from ..types.error import Error
from ..errors.not_found_error import NotFoundError
from ..types.not_found_error_body import NotFoundErrorBody
from json.decoder import JSONDecodeError
from ..core.api_error import ApiError
import datetime as dt
from ..types.list_query_histories_response import ListQueryHistoriesResponse
from ..core.datetime_utils import serialize_datetime
from ..errors.bad_request_error import BadRequestError
from ..types.bad_request_error_body import BadRequestErrorBody
from ..core.client_wrapper import AsyncClientWrapper


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

    def get_query_history(
        self,
        query_id: str,
        *,
        request_timeout: typing.Optional[int] = None,
        request_timeout_millis: typing.Optional[int] = None,
        request_options: typing.Optional[RequestOptions] = None,
    ) -> QueryHistory:
        """
        Retrieve a detailed history of previously executed query.

        Parameters
        ----------
        query_id : str
            The ID of the query history

        request_timeout : typing.Optional[int]
            The API will make a best effort to complete the request in the specified seconds or time out.

        request_timeout_millis : typing.Optional[int]
            The API will make a best effort to complete the request in the specified milliseconds or time out.

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

        Returns
        -------
        QueryHistory
            The query history.

        Examples
        --------
        from vectara import Vectara

        client = Vectara(
            api_key="YOUR_API_KEY",
            client_id="YOUR_CLIENT_ID",
            client_secret="YOUR_CLIENT_SECRET",
        )
        client.query_history.get_query_history(
            query_id="query_id",
        )
        """
        _response = self._client_wrapper.httpx_client.request(
            f"v2/queries/{jsonable_encoder(query_id)}",
            base_url=self._client_wrapper.get_environment().default,
            method="GET",
            headers={
                "Request-Timeout": str(request_timeout) if request_timeout is not None else None,
                "Request-Timeout-Millis": str(request_timeout_millis) if request_timeout_millis is not None else None,
            },
            request_options=request_options,
        )
        try:
            if 200 <= _response.status_code < 300:
                return typing.cast(
                    QueryHistory,
                    parse_obj_as(
                        type_=QueryHistory,  # type: ignore
                        object_=_response.json(),
                    ),
                )
            if _response.status_code == 403:
                raise ForbiddenError(
                    typing.cast(
                        Error,
                        parse_obj_as(
                            type_=Error,  # type: ignore
                            object_=_response.json(),
                        ),
                    )
                )
            if _response.status_code == 404:
                raise NotFoundError(
                    typing.cast(
                        NotFoundErrorBody,
                        parse_obj_as(
                            type_=NotFoundErrorBody,  # type: ignore
                            object_=_response.json(),
                        ),
                    )
                )
            _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)

    def get_query_histories(
        self,
        *,
        corpus_key: typing.Optional[str] = None,
        started_after: typing.Optional[dt.datetime] = None,
        started_before: typing.Optional[dt.datetime] = None,
        chat_id: typing.Optional[str] = None,
        limit: typing.Optional[int] = None,
        page_key: typing.Optional[str] = None,
        request_timeout: typing.Optional[int] = None,
        request_timeout_millis: typing.Optional[int] = None,
        request_options: typing.Optional[RequestOptions] = None,
    ) -> ListQueryHistoriesResponse:
        """
        Retrieve query histories.

        Parameters
        ----------
        corpus_key : typing.Optional[str]
            Specifies the `corpus_key` used in the query.

        started_after : typing.Optional[dt.datetime]
            Queries that started after a particular date-time.

        started_before : typing.Optional[dt.datetime]
            Queries that started before a particular date-time.

        chat_id : typing.Optional[str]
            Specifies the chat_id of the query, this will return all queries in the specified chat.

        limit : typing.Optional[int]
            Specifies the maximum number of query history listed.

        page_key : typing.Optional[str]
            Used to retrieve the next page of query histories after the limit has been reached.

        request_timeout : typing.Optional[int]
            The API will make a best effort to complete the request in the specified seconds or time out.

        request_timeout_millis : typing.Optional[int]
            The API will make a best effort to complete the request in the specified milliseconds or time out.

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

        Returns
        -------
        ListQueryHistoriesResponse
            An array of Query Histories.

        Examples
        --------
        from vectara import Vectara

        client = Vectara(
            api_key="YOUR_API_KEY",
            client_id="YOUR_CLIENT_ID",
            client_secret="YOUR_CLIENT_SECRET",
        )
        client.query_history.get_query_histories()
        """
        _response = self._client_wrapper.httpx_client.request(
            "v2/queries",
            base_url=self._client_wrapper.get_environment().default,
            method="GET",
            params={
                "corpus_key": corpus_key,
                "started_after": serialize_datetime(started_after) if started_after is not None else None,
                "started_before": serialize_datetime(started_before) if started_before is not None else None,
                "chat_id": chat_id,
                "limit": limit,
                "page_key": page_key,
            },
            headers={
                "Request-Timeout": str(request_timeout) if request_timeout is not None else None,
                "Request-Timeout-Millis": str(request_timeout_millis) if request_timeout_millis is not None else None,
            },
            request_options=request_options,
        )
        try:
            if 200 <= _response.status_code < 300:
                return typing.cast(
                    ListQueryHistoriesResponse,
                    parse_obj_as(
                        type_=ListQueryHistoriesResponse,  # type: ignore
                        object_=_response.json(),
                    ),
                )
            if _response.status_code == 400:
                raise BadRequestError(
                    typing.cast(
                        BadRequestErrorBody,
                        parse_obj_as(
                            type_=BadRequestErrorBody,  # type: ignore
                            object_=_response.json(),
                        ),
                    )
                )
            if _response.status_code == 403:
                raise ForbiddenError(
                    typing.cast(
                        Error,
                        parse_obj_as(
                            type_=Error,  # type: ignore
                            object_=_response.json(),
                        ),
                    )
                )
            _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 AsyncQueryHistoryClient:
    def __init__(self, *, client_wrapper: AsyncClientWrapper):
        self._client_wrapper = client_wrapper

    async def get_query_history(
        self,
        query_id: str,
        *,
        request_timeout: typing.Optional[int] = None,
        request_timeout_millis: typing.Optional[int] = None,
        request_options: typing.Optional[RequestOptions] = None,
    ) -> QueryHistory:
        """
        Retrieve a detailed history of previously executed query.

        Parameters
        ----------
        query_id : str
            The ID of the query history

        request_timeout : typing.Optional[int]
            The API will make a best effort to complete the request in the specified seconds or time out.

        request_timeout_millis : typing.Optional[int]
            The API will make a best effort to complete the request in the specified milliseconds or time out.

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

        Returns
        -------
        QueryHistory
            The query history.

        Examples
        --------
        import asyncio

        from vectara import AsyncVectara

        client = AsyncVectara(
            api_key="YOUR_API_KEY",
            client_id="YOUR_CLIENT_ID",
            client_secret="YOUR_CLIENT_SECRET",
        )


        async def main() -> None:
            await client.query_history.get_query_history(
                query_id="query_id",
            )


        asyncio.run(main())
        """
        _response = await self._client_wrapper.httpx_client.request(
            f"v2/queries/{jsonable_encoder(query_id)}",
            base_url=self._client_wrapper.get_environment().default,
            method="GET",
            headers={
                "Request-Timeout": str(request_timeout) if request_timeout is not None else None,
                "Request-Timeout-Millis": str(request_timeout_millis) if request_timeout_millis is not None else None,
            },
            request_options=request_options,
        )
        try:
            if 200 <= _response.status_code < 300:
                return typing.cast(
                    QueryHistory,
                    parse_obj_as(
                        type_=QueryHistory,  # type: ignore
                        object_=_response.json(),
                    ),
                )
            if _response.status_code == 403:
                raise ForbiddenError(
                    typing.cast(
                        Error,
                        parse_obj_as(
                            type_=Error,  # type: ignore
                            object_=_response.json(),
                        ),
                    )
                )
            if _response.status_code == 404:
                raise NotFoundError(
                    typing.cast(
                        NotFoundErrorBody,
                        parse_obj_as(
                            type_=NotFoundErrorBody,  # type: ignore
                            object_=_response.json(),
                        ),
                    )
                )
            _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)

    async def get_query_histories(
        self,
        *,
        corpus_key: typing.Optional[str] = None,
        started_after: typing.Optional[dt.datetime] = None,
        started_before: typing.Optional[dt.datetime] = None,
        chat_id: typing.Optional[str] = None,
        limit: typing.Optional[int] = None,
        page_key: typing.Optional[str] = None,
        request_timeout: typing.Optional[int] = None,
        request_timeout_millis: typing.Optional[int] = None,
        request_options: typing.Optional[RequestOptions] = None,
    ) -> ListQueryHistoriesResponse:
        """
        Retrieve query histories.

        Parameters
        ----------
        corpus_key : typing.Optional[str]
            Specifies the `corpus_key` used in the query.

        started_after : typing.Optional[dt.datetime]
            Queries that started after a particular date-time.

        started_before : typing.Optional[dt.datetime]
            Queries that started before a particular date-time.

        chat_id : typing.Optional[str]
            Specifies the chat_id of the query, this will return all queries in the specified chat.

        limit : typing.Optional[int]
            Specifies the maximum number of query history listed.

        page_key : typing.Optional[str]
            Used to retrieve the next page of query histories after the limit has been reached.

        request_timeout : typing.Optional[int]
            The API will make a best effort to complete the request in the specified seconds or time out.

        request_timeout_millis : typing.Optional[int]
            The API will make a best effort to complete the request in the specified milliseconds or time out.

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

        Returns
        -------
        ListQueryHistoriesResponse
            An array of Query Histories.

        Examples
        --------
        import asyncio

        from vectara import AsyncVectara

        client = AsyncVectara(
            api_key="YOUR_API_KEY",
            client_id="YOUR_CLIENT_ID",
            client_secret="YOUR_CLIENT_SECRET",
        )


        async def main() -> None:
            await client.query_history.get_query_histories()


        asyncio.run(main())
        """
        _response = await self._client_wrapper.httpx_client.request(
            "v2/queries",
            base_url=self._client_wrapper.get_environment().default,
            method="GET",
            params={
                "corpus_key": corpus_key,
                "started_after": serialize_datetime(started_after) if started_after is not None else None,
                "started_before": serialize_datetime(started_before) if started_before is not None else None,
                "chat_id": chat_id,
                "limit": limit,
                "page_key": page_key,
            },
            headers={
                "Request-Timeout": str(request_timeout) if request_timeout is not None else None,
                "Request-Timeout-Millis": str(request_timeout_millis) if request_timeout_millis is not None else None,
            },
            request_options=request_options,
        )
        try:
            if 200 <= _response.status_code < 300:
                return typing.cast(
                    ListQueryHistoriesResponse,
                    parse_obj_as(
                        type_=ListQueryHistoriesResponse,  # type: ignore
                        object_=_response.json(),
                    ),
                )
            if _response.status_code == 400:
                raise BadRequestError(
                    typing.cast(
                        BadRequestErrorBody,
                        parse_obj_as(
                            type_=BadRequestErrorBody,  # type: ignore
                            object_=_response.json(),
                        ),
                    )
                )
            if _response.status_code == 403:
                raise ForbiddenError(
                    typing.cast(
                        Error,
                        parse_obj_as(
                            type_=Error,  # type: ignore
                            object_=_response.json(),
                        ),
                    )
                )
            _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)
