# 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.api_key_daily_usage_response import ApiKeyDailyUsageResponse
from ..types.api_key_usage_summary import ApiKeyUsageSummary


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

    def get_api_key_usage_summary(
        self,
        org_id: str,
        *,
        year: typing.Optional[int] = None,
        month: typing.Optional[int] = None,
        request_options: typing.Optional[RequestOptions] = None,
    ) -> HttpResponse[ApiKeyUsageSummary]:
        """
        Get API Key Usage Summary.

        Returns summary statistics for API key usage only (programmatic access).
        This excludes bearer token usage from web applications.

        **Use Case:** API Management Pages - show only programmatic usage

        **Metrics:**
        - Total API key requests
        - Total cost in CHF
        - Average cost per request
        - Total synapses
        - Total neurons

        Parameters
        ----------
        org_id : str

        year : typing.Optional[int]
            Year

        month : typing.Optional[int]
            Month

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

        Returns
        -------
        HttpResponse[ApiKeyUsageSummary]
            Successful Response
        """
        _response = self._client_wrapper.httpx_client.request(
            f"v1/analytics/api-keys/summary/{jsonable_encoder(org_id)}",
            method="GET",
            params={
                "year": year,
                "month": month,
            },
            request_options=request_options,
        )
        try:
            if 200 <= _response.status_code < 300:
                _data = typing.cast(
                    ApiKeyUsageSummary,
                    parse_obj_as(
                        type_=ApiKeyUsageSummary,  # 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(
                        typing.Any,
                        parse_obj_as(
                            type_=typing.Any,  # 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_api_key_daily_usage(
        self,
        org_id: str,
        *,
        year: typing.Optional[int] = None,
        month: typing.Optional[int] = None,
        request_options: typing.Optional[RequestOptions] = None,
    ) -> HttpResponse[ApiKeyDailyUsageResponse]:
        """
        Get API Key Daily Usage.

        Returns daily breakdown of API key usage only (programmatic access).
        This excludes bearer token usage from web applications.

        **Use Case:** API Management Pages - show daily API usage patterns

        **Metrics per Day:**
        - Request count
        - Total cost in CHF
        - Total synapses
        - Total neurons

        Parameters
        ----------
        org_id : str

        year : typing.Optional[int]
            Year

        month : typing.Optional[int]
            Month

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

        Returns
        -------
        HttpResponse[ApiKeyDailyUsageResponse]
            Successful Response
        """
        _response = self._client_wrapper.httpx_client.request(
            f"v1/analytics/api-keys/daily/{jsonable_encoder(org_id)}",
            method="GET",
            params={
                "year": year,
                "month": month,
            },
            request_options=request_options,
        )
        try:
            if 200 <= _response.status_code < 300:
                _data = typing.cast(
                    ApiKeyDailyUsageResponse,
                    parse_obj_as(
                        type_=ApiKeyDailyUsageResponse,  # 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(
                        typing.Any,
                        parse_obj_as(
                            type_=typing.Any,  # 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_top_api_keys(
        self,
        org_id: str,
        month: int,
        year: int,
        *,
        limit: typing.Optional[int] = None,
        period: typing.Optional[str] = None,
        request_options: typing.Optional[RequestOptions] = None,
    ) -> HttpResponse[typing.Dict[str, typing.Any]]:
        """
        Get top API keys by usage.

        Returns the top API keys ranked by total cost for the specified period.
        Always returns data even when no usage exists (empty list).

        Args:
            org_id: Organization ID
            month: Month (1-12)
            year: Year
            auth: Authenticated user
            db: Database session
            limit: Number of top keys to return (1-100)
            period: Period type (daily, monthly)

        Returns:
            Top API keys with usage metrics

        Parameters
        ----------
        org_id : str

        month : int

        year : int

        limit : typing.Optional[int]
            Number of top keys to return

        period : typing.Optional[str]
            Period type (daily, monthly)

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

        Returns
        -------
        HttpResponse[typing.Dict[str, typing.Any]]
            Successful Response
        """
        _response = self._client_wrapper.httpx_client.request(
            f"v1/analytics/{jsonable_encoder(org_id)}/api-keys/top/{jsonable_encoder(month)}/{jsonable_encoder(year)}",
            method="GET",
            params={
                "limit": limit,
                "period": period,
            },
            request_options=request_options,
        )
        try:
            if 200 <= _response.status_code < 300:
                _data = typing.cast(
                    typing.Dict[str, typing.Any],
                    parse_obj_as(
                        type_=typing.Dict[str, typing.Any],  # 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(
                        typing.Any,
                        parse_obj_as(
                            type_=typing.Any,  # 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 AsyncRawAnalyticsApiKeysClient:
    def __init__(self, *, client_wrapper: AsyncClientWrapper):
        self._client_wrapper = client_wrapper

    async def get_api_key_usage_summary(
        self,
        org_id: str,
        *,
        year: typing.Optional[int] = None,
        month: typing.Optional[int] = None,
        request_options: typing.Optional[RequestOptions] = None,
    ) -> AsyncHttpResponse[ApiKeyUsageSummary]:
        """
        Get API Key Usage Summary.

        Returns summary statistics for API key usage only (programmatic access).
        This excludes bearer token usage from web applications.

        **Use Case:** API Management Pages - show only programmatic usage

        **Metrics:**
        - Total API key requests
        - Total cost in CHF
        - Average cost per request
        - Total synapses
        - Total neurons

        Parameters
        ----------
        org_id : str

        year : typing.Optional[int]
            Year

        month : typing.Optional[int]
            Month

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

        Returns
        -------
        AsyncHttpResponse[ApiKeyUsageSummary]
            Successful Response
        """
        _response = await self._client_wrapper.httpx_client.request(
            f"v1/analytics/api-keys/summary/{jsonable_encoder(org_id)}",
            method="GET",
            params={
                "year": year,
                "month": month,
            },
            request_options=request_options,
        )
        try:
            if 200 <= _response.status_code < 300:
                _data = typing.cast(
                    ApiKeyUsageSummary,
                    parse_obj_as(
                        type_=ApiKeyUsageSummary,  # 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(
                        typing.Any,
                        parse_obj_as(
                            type_=typing.Any,  # 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_api_key_daily_usage(
        self,
        org_id: str,
        *,
        year: typing.Optional[int] = None,
        month: typing.Optional[int] = None,
        request_options: typing.Optional[RequestOptions] = None,
    ) -> AsyncHttpResponse[ApiKeyDailyUsageResponse]:
        """
        Get API Key Daily Usage.

        Returns daily breakdown of API key usage only (programmatic access).
        This excludes bearer token usage from web applications.

        **Use Case:** API Management Pages - show daily API usage patterns

        **Metrics per Day:**
        - Request count
        - Total cost in CHF
        - Total synapses
        - Total neurons

        Parameters
        ----------
        org_id : str

        year : typing.Optional[int]
            Year

        month : typing.Optional[int]
            Month

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

        Returns
        -------
        AsyncHttpResponse[ApiKeyDailyUsageResponse]
            Successful Response
        """
        _response = await self._client_wrapper.httpx_client.request(
            f"v1/analytics/api-keys/daily/{jsonable_encoder(org_id)}",
            method="GET",
            params={
                "year": year,
                "month": month,
            },
            request_options=request_options,
        )
        try:
            if 200 <= _response.status_code < 300:
                _data = typing.cast(
                    ApiKeyDailyUsageResponse,
                    parse_obj_as(
                        type_=ApiKeyDailyUsageResponse,  # 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(
                        typing.Any,
                        parse_obj_as(
                            type_=typing.Any,  # 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_top_api_keys(
        self,
        org_id: str,
        month: int,
        year: int,
        *,
        limit: typing.Optional[int] = None,
        period: typing.Optional[str] = None,
        request_options: typing.Optional[RequestOptions] = None,
    ) -> AsyncHttpResponse[typing.Dict[str, typing.Any]]:
        """
        Get top API keys by usage.

        Returns the top API keys ranked by total cost for the specified period.
        Always returns data even when no usage exists (empty list).

        Args:
            org_id: Organization ID
            month: Month (1-12)
            year: Year
            auth: Authenticated user
            db: Database session
            limit: Number of top keys to return (1-100)
            period: Period type (daily, monthly)

        Returns:
            Top API keys with usage metrics

        Parameters
        ----------
        org_id : str

        month : int

        year : int

        limit : typing.Optional[int]
            Number of top keys to return

        period : typing.Optional[str]
            Period type (daily, monthly)

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

        Returns
        -------
        AsyncHttpResponse[typing.Dict[str, typing.Any]]
            Successful Response
        """
        _response = await self._client_wrapper.httpx_client.request(
            f"v1/analytics/{jsonable_encoder(org_id)}/api-keys/top/{jsonable_encoder(month)}/{jsonable_encoder(year)}",
            method="GET",
            params={
                "limit": limit,
                "period": period,
            },
            request_options=request_options,
        )
        try:
            if 200 <= _response.status_code < 300:
                _data = typing.cast(
                    typing.Dict[str, typing.Any],
                    parse_obj_as(
                        type_=typing.Dict[str, typing.Any],  # 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(
                        typing.Any,
                        parse_obj_as(
                            type_=typing.Any,  # 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)
