# 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.jsonable_encoder import jsonable_encoder
from ..core.pydantic_utilities import parse_obj_as
from ..core.request_options import RequestOptions
from ..errors.unprocessable_entity_error import UnprocessableEntityError
from ..types.aggregation_response import AggregationResponse
from ..types.aggregation_result import AggregationResult
from ..types.continuous_query_task_history_response import ContinuousQueryTaskHistoryResponse
from ..types.http_validation_error import HttpValidationError
from ..types.query import Query
from ..types.query_config import QueryConfig
from .types.query_batch_timeframe import QueryBatchTimeframe

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


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

    def query_one(
        self,
        user_id: str,
        *,
        timeframe: QueryBatchTimeframe,
        queries: typing.Sequence[Query],
        config: typing.Optional[QueryConfig] = OMIT,
        request_options: typing.Optional[RequestOptions] = None,
    ) -> HttpResponse[AggregationResponse]:
        """
        Parameters
        ----------
        user_id : str

        timeframe : QueryBatchTimeframe

        queries : typing.Sequence[Query]

        config : typing.Optional[QueryConfig]

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

        Returns
        -------
        HttpResponse[AggregationResponse]
            Successful Response
        """
        _response = self._client_wrapper.httpx_client.request(
            f"aggregate/v1/user/{jsonable_encoder(user_id)}/query",
            method="POST",
            json={
                "timeframe": timeframe,
                "queries": queries,
                "config": config,
            },
            headers={
                "content-type": "application/json",
                "accept": "*/*",
            },
            request_options=request_options,
            omit=OMIT,
        )
        try:
            if 200 <= _response.status_code < 300:
                _data = typing.cast(
                    AggregationResponse,
                    parse_obj_as(
                        type_=AggregationResponse,  # type: ignore
                        object_=_response.json(),
                    ),
                )
                return HttpResponse(response=_response, data=_data)
            if _response.status_code == 422:
                raise UnprocessableEntityError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        HttpValidationError,
                        parse_obj_as(
                            type_=HttpValidationError,  # type: ignore
                            object_=_response.json(),
                        ),
                    ),
                )
            _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 get_result_table_for_continuous_query(
        self, user_id: str, query_id_or_slug: str, *, request_options: typing.Optional[RequestOptions] = None
    ) -> HttpResponse[AggregationResult]:
        """
        Parameters
        ----------
        user_id : str

        query_id_or_slug : str

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

        Returns
        -------
        HttpResponse[AggregationResult]
            Successful Response
        """
        _response = self._client_wrapper.httpx_client.request(
            f"aggregate/v1/user/{jsonable_encoder(user_id)}/continuous_query/{jsonable_encoder(query_id_or_slug)}/result_table",
            method="GET",
            headers={
                "accept": "*/*",
            },
            request_options=request_options,
        )
        try:
            if 200 <= _response.status_code < 300:
                _data = typing.cast(
                    AggregationResult,
                    parse_obj_as(
                        type_=AggregationResult,  # type: ignore
                        object_=_response.json(),
                    ),
                )
                return HttpResponse(response=_response, data=_data)
            if _response.status_code == 422:
                raise UnprocessableEntityError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        HttpValidationError,
                        parse_obj_as(
                            type_=HttpValidationError,  # type: ignore
                            object_=_response.json(),
                        ),
                    ),
                )
            _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 get_task_history_for_continuous_query(
        self,
        user_id: str,
        query_id_or_slug: str,
        *,
        next_cursor: typing.Optional[str] = None,
        limit: typing.Optional[int] = None,
        request_options: typing.Optional[RequestOptions] = None,
    ) -> HttpResponse[ContinuousQueryTaskHistoryResponse]:
        """
        Parameters
        ----------
        user_id : str

        query_id_or_slug : str

        next_cursor : typing.Optional[str]

        limit : typing.Optional[int]

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

        Returns
        -------
        HttpResponse[ContinuousQueryTaskHistoryResponse]
            Successful Response
        """
        _response = self._client_wrapper.httpx_client.request(
            f"aggregate/v1/user/{jsonable_encoder(user_id)}/continuous_query/{jsonable_encoder(query_id_or_slug)}/task_history",
            method="GET",
            params={
                "next_cursor": next_cursor,
                "limit": limit,
            },
            request_options=request_options,
        )
        try:
            if 200 <= _response.status_code < 300:
                _data = typing.cast(
                    ContinuousQueryTaskHistoryResponse,
                    parse_obj_as(
                        type_=ContinuousQueryTaskHistoryResponse,  # type: ignore
                        object_=_response.json(),
                    ),
                )
                return HttpResponse(response=_response, data=_data)
            if _response.status_code == 422:
                raise UnprocessableEntityError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        HttpValidationError,
                        parse_obj_as(
                            type_=HttpValidationError,  # type: ignore
                            object_=_response.json(),
                        ),
                    ),
                )
            _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 AsyncRawAggregateClient:
    def __init__(self, *, client_wrapper: AsyncClientWrapper):
        self._client_wrapper = client_wrapper

    async def query_one(
        self,
        user_id: str,
        *,
        timeframe: QueryBatchTimeframe,
        queries: typing.Sequence[Query],
        config: typing.Optional[QueryConfig] = OMIT,
        request_options: typing.Optional[RequestOptions] = None,
    ) -> AsyncHttpResponse[AggregationResponse]:
        """
        Parameters
        ----------
        user_id : str

        timeframe : QueryBatchTimeframe

        queries : typing.Sequence[Query]

        config : typing.Optional[QueryConfig]

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

        Returns
        -------
        AsyncHttpResponse[AggregationResponse]
            Successful Response
        """
        _response = await self._client_wrapper.httpx_client.request(
            f"aggregate/v1/user/{jsonable_encoder(user_id)}/query",
            method="POST",
            json={
                "timeframe": timeframe,
                "queries": queries,
                "config": config,
            },
            headers={
                "content-type": "application/json",
                "accept": "*/*",
            },
            request_options=request_options,
            omit=OMIT,
        )
        try:
            if 200 <= _response.status_code < 300:
                _data = typing.cast(
                    AggregationResponse,
                    parse_obj_as(
                        type_=AggregationResponse,  # type: ignore
                        object_=_response.json(),
                    ),
                )
                return AsyncHttpResponse(response=_response, data=_data)
            if _response.status_code == 422:
                raise UnprocessableEntityError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        HttpValidationError,
                        parse_obj_as(
                            type_=HttpValidationError,  # type: ignore
                            object_=_response.json(),
                        ),
                    ),
                )
            _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 get_result_table_for_continuous_query(
        self, user_id: str, query_id_or_slug: str, *, request_options: typing.Optional[RequestOptions] = None
    ) -> AsyncHttpResponse[AggregationResult]:
        """
        Parameters
        ----------
        user_id : str

        query_id_or_slug : str

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

        Returns
        -------
        AsyncHttpResponse[AggregationResult]
            Successful Response
        """
        _response = await self._client_wrapper.httpx_client.request(
            f"aggregate/v1/user/{jsonable_encoder(user_id)}/continuous_query/{jsonable_encoder(query_id_or_slug)}/result_table",
            method="GET",
            headers={
                "accept": "*/*",
            },
            request_options=request_options,
        )
        try:
            if 200 <= _response.status_code < 300:
                _data = typing.cast(
                    AggregationResult,
                    parse_obj_as(
                        type_=AggregationResult,  # type: ignore
                        object_=_response.json(),
                    ),
                )
                return AsyncHttpResponse(response=_response, data=_data)
            if _response.status_code == 422:
                raise UnprocessableEntityError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        HttpValidationError,
                        parse_obj_as(
                            type_=HttpValidationError,  # type: ignore
                            object_=_response.json(),
                        ),
                    ),
                )
            _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 get_task_history_for_continuous_query(
        self,
        user_id: str,
        query_id_or_slug: str,
        *,
        next_cursor: typing.Optional[str] = None,
        limit: typing.Optional[int] = None,
        request_options: typing.Optional[RequestOptions] = None,
    ) -> AsyncHttpResponse[ContinuousQueryTaskHistoryResponse]:
        """
        Parameters
        ----------
        user_id : str

        query_id_or_slug : str

        next_cursor : typing.Optional[str]

        limit : typing.Optional[int]

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

        Returns
        -------
        AsyncHttpResponse[ContinuousQueryTaskHistoryResponse]
            Successful Response
        """
        _response = await self._client_wrapper.httpx_client.request(
            f"aggregate/v1/user/{jsonable_encoder(user_id)}/continuous_query/{jsonable_encoder(query_id_or_slug)}/task_history",
            method="GET",
            params={
                "next_cursor": next_cursor,
                "limit": limit,
            },
            request_options=request_options,
        )
        try:
            if 200 <= _response.status_code < 300:
                _data = typing.cast(
                    ContinuousQueryTaskHistoryResponse,
                    parse_obj_as(
                        type_=ContinuousQueryTaskHistoryResponse,  # type: ignore
                        object_=_response.json(),
                    ),
                )
                return AsyncHttpResponse(response=_response, data=_data)
            if _response.status_code == 422:
                raise UnprocessableEntityError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        HttpValidationError,
                        parse_obj_as(
                            type_=HttpValidationError,  # type: ignore
                            object_=_response.json(),
                        ),
                    ),
                )
            _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)
