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

import typing

from ..core.client_wrapper import AsyncClientWrapper, SyncClientWrapper
from ..core.request_options import RequestOptions
from ..types.api_key_usage_detail import ApiKeyUsageDetail
from ..types.limit_update_response import LimitUpdateResponse
from ..types.usage_limits_response import UsageLimitsResponse
from .raw_client import AsyncRawAnalyticsLimitsClient, RawAnalyticsLimitsClient

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


class AnalyticsLimitsClient:
    def __init__(self, *, client_wrapper: SyncClientWrapper):
        self._raw_client = RawAnalyticsLimitsClient(client_wrapper=client_wrapper)

    @property
    def with_raw_response(self) -> RawAnalyticsLimitsClient:
        """
        Retrieves a raw implementation of this client that returns raw responses.

        Returns
        -------
        RawAnalyticsLimitsClient
        """
        return self._raw_client

    def get_usage_limits(
        self,
        org_id: str,
        *,
        month: typing.Optional[int] = None,
        year: typing.Optional[int] = None,
        request_options: typing.Optional[RequestOptions] = None,
    ) -> UsageLimitsResponse:
        """
        Get usage limits for organization.

        Returns comprehensive usage limits including organization-level limits,
        API-level aggregated limits, and per-API-key breakdown.

        **Query Parameters:**
        - `month` (optional): Month to query (1-12), defaults to current month
        - `year` (optional): Year to query, defaults to current year

        **Response includes:**
        - Organization-level monthly limit, usage, utilization, and status
        - API-level aggregated usage against organization limit
        - Per-API-key breakdown with individual limits and status
        - Summary statistics (total keys, keys with limits, keys exceeded)

        **Status Values:**
        - `ok`: utilization < 80%
        - `warning`: 80% <= utilization < 100%
        - `exceeded`: utilization >= 100%
        - `no_limit`: No limit configured

        **Perfect for:**
        - Budget monitoring dashboards
        - Cost control and alerting
        - API key management
        - Usage forecasting

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

        month : typing.Optional[int]
            Month (1-12)

        year : typing.Optional[int]
            Year

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

        Returns
        -------
        UsageLimitsResponse
            Successful Response

        Examples
        --------
        from aitronos import Aitronos

        client = Aitronos(
            api_key="YOUR_API_KEY",
            token="YOUR_TOKEN",
        )
        client.analytics_limits.get_usage_limits(
            org_id="org_id",
        )
        """
        _response = self._raw_client.get_usage_limits(org_id, month=month, year=year, request_options=request_options)
        return _response.data

    def update_usage_limits(
        self,
        org_id: str,
        *,
        monthly_api_limit: typing.Optional[float] = OMIT,
        total_api_key_limit: typing.Optional[float] = OMIT,
        api_key_id: typing.Optional[str] = OMIT,
        api_key_limit: typing.Optional[float] = OMIT,
        request_options: typing.Optional[RequestOptions] = None,
    ) -> LimitUpdateResponse:
        """
        Update organization, total API key, and/or individual API key spending limits.

        Supports multiple update modes:
        1. Update organization limit only (provide `monthlyApiLimit`)
        2. Update total API key limit only (provide `totalApiKeyLimit`)
        3. Update individual API key limit only (provide `apiKeyId` and `apiKeyLimit`)
        4. Update any combination of the above limits atomically

        **Request Body:**
        - `monthlyApiLimit` (optional): Organization limit in CHF (must be > 0)
        - `totalApiKeyLimit` (optional): Total API key limit in CHF (must be > 0)
        - `apiKeyId` (optional): API key ID
        - `apiKeyLimit` (optional): Individual API key limit in CHF (must be > 0)

        **Validation:**
        - At least one field must be provided
        - All provided limits must be positive numbers (> 0)
        - If `apiKeyId` provided, `apiKeyLimit` must also be provided
        - API key must belong to the specified organization
        - Total API key limit cannot exceed organization limit

        **Cross-Limit Constraints:**
        - Total API key limit ≤ organization limit (if org limit configured)
        - Validation applies when updating either limit or both simultaneously
        - Returns 422 error if constraint violated

        **Cache Behavior:**
        - If limit is increased above current usage, exceeded cache is cleared
        - If limit is still below usage, exceeded cache is retained
        - Requests are immediately allowed/blocked based on new limits

        **Atomic Updates:**
        - When updating multiple limits, either all succeed or all fail
        - No partial updates on validation errors

        **Perfect for:**
        - Budget adjustments
        - API key provisioning
        - Cost control management
        - Emergency limit increases

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

        monthly_api_limit : typing.Optional[float]
            Organization limit in CHF (must be > 0)

        total_api_key_limit : typing.Optional[float]
            Total API key limit in CHF (must be > 0)

        api_key_id : typing.Optional[str]
            API key ID

        api_key_limit : typing.Optional[float]
            API key limit in CHF (must be > 0)

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

        Returns
        -------
        LimitUpdateResponse
            Successful Response

        Examples
        --------
        from aitronos import Aitronos

        client = Aitronos(
            api_key="YOUR_API_KEY",
            token="YOUR_TOKEN",
        )
        client.analytics_limits.update_usage_limits(
            org_id="org_id",
        )
        """
        _response = self._raw_client.update_usage_limits(
            org_id,
            monthly_api_limit=monthly_api_limit,
            total_api_key_limit=total_api_key_limit,
            api_key_id=api_key_id,
            api_key_limit=api_key_limit,
            request_options=request_options,
        )
        return _response.data

    def get_api_key_usage(
        self,
        org_id: str,
        api_key_id: str,
        *,
        month: typing.Optional[int] = None,
        year: typing.Optional[int] = None,
        request_options: typing.Optional[RequestOptions] = None,
    ) -> ApiKeyUsageDetail:
        """
        Get detailed usage for a specific API key.

        Returns comprehensive usage information for a single API key including
        total requests, cost, synapses, neurons, and limit utilization.

        **Query Parameters:**
        - `month` (optional): Month to query (1-12), defaults to current month
        - `year` (optional): Year to query, defaults to current year

        **Response includes:**
        - API key identification (ID, name, organization)
        - Usage metrics (requests, cost, synapses, neurons, average cost)
        - Limit information (monthly limit, utilization, remaining budget, status)

        **Status Values:**
        - `ok`: utilization < 80%
        - `warning`: 80% <= utilization < 100%
        - `exceeded`: utilization >= 100%
        - `no_limit`: No limit configured

        **Perfect for:**
        - API key monitoring
        - Per-key cost tracking
        - Usage analysis
        - Limit management

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

        api_key_id : str

        month : typing.Optional[int]
            Month (1-12)

        year : typing.Optional[int]
            Year

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

        Returns
        -------
        ApiKeyUsageDetail
            Successful Response

        Examples
        --------
        from aitronos import Aitronos

        client = Aitronos(
            api_key="YOUR_API_KEY",
            token="YOUR_TOKEN",
        )
        client.analytics_limits.get_api_key_usage(
            org_id="org_id",
            api_key_id="api_key_id",
        )
        """
        _response = self._raw_client.get_api_key_usage(
            org_id, api_key_id, month=month, year=year, request_options=request_options
        )
        return _response.data


class AsyncAnalyticsLimitsClient:
    def __init__(self, *, client_wrapper: AsyncClientWrapper):
        self._raw_client = AsyncRawAnalyticsLimitsClient(client_wrapper=client_wrapper)

    @property
    def with_raw_response(self) -> AsyncRawAnalyticsLimitsClient:
        """
        Retrieves a raw implementation of this client that returns raw responses.

        Returns
        -------
        AsyncRawAnalyticsLimitsClient
        """
        return self._raw_client

    async def get_usage_limits(
        self,
        org_id: str,
        *,
        month: typing.Optional[int] = None,
        year: typing.Optional[int] = None,
        request_options: typing.Optional[RequestOptions] = None,
    ) -> UsageLimitsResponse:
        """
        Get usage limits for organization.

        Returns comprehensive usage limits including organization-level limits,
        API-level aggregated limits, and per-API-key breakdown.

        **Query Parameters:**
        - `month` (optional): Month to query (1-12), defaults to current month
        - `year` (optional): Year to query, defaults to current year

        **Response includes:**
        - Organization-level monthly limit, usage, utilization, and status
        - API-level aggregated usage against organization limit
        - Per-API-key breakdown with individual limits and status
        - Summary statistics (total keys, keys with limits, keys exceeded)

        **Status Values:**
        - `ok`: utilization < 80%
        - `warning`: 80% <= utilization < 100%
        - `exceeded`: utilization >= 100%
        - `no_limit`: No limit configured

        **Perfect for:**
        - Budget monitoring dashboards
        - Cost control and alerting
        - API key management
        - Usage forecasting

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

        month : typing.Optional[int]
            Month (1-12)

        year : typing.Optional[int]
            Year

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

        Returns
        -------
        UsageLimitsResponse
            Successful Response

        Examples
        --------
        import asyncio

        from aitronos import AsyncAitronos

        client = AsyncAitronos(
            api_key="YOUR_API_KEY",
            token="YOUR_TOKEN",
        )


        async def main() -> None:
            await client.analytics_limits.get_usage_limits(
                org_id="org_id",
            )


        asyncio.run(main())
        """
        _response = await self._raw_client.get_usage_limits(
            org_id, month=month, year=year, request_options=request_options
        )
        return _response.data

    async def update_usage_limits(
        self,
        org_id: str,
        *,
        monthly_api_limit: typing.Optional[float] = OMIT,
        total_api_key_limit: typing.Optional[float] = OMIT,
        api_key_id: typing.Optional[str] = OMIT,
        api_key_limit: typing.Optional[float] = OMIT,
        request_options: typing.Optional[RequestOptions] = None,
    ) -> LimitUpdateResponse:
        """
        Update organization, total API key, and/or individual API key spending limits.

        Supports multiple update modes:
        1. Update organization limit only (provide `monthlyApiLimit`)
        2. Update total API key limit only (provide `totalApiKeyLimit`)
        3. Update individual API key limit only (provide `apiKeyId` and `apiKeyLimit`)
        4. Update any combination of the above limits atomically

        **Request Body:**
        - `monthlyApiLimit` (optional): Organization limit in CHF (must be > 0)
        - `totalApiKeyLimit` (optional): Total API key limit in CHF (must be > 0)
        - `apiKeyId` (optional): API key ID
        - `apiKeyLimit` (optional): Individual API key limit in CHF (must be > 0)

        **Validation:**
        - At least one field must be provided
        - All provided limits must be positive numbers (> 0)
        - If `apiKeyId` provided, `apiKeyLimit` must also be provided
        - API key must belong to the specified organization
        - Total API key limit cannot exceed organization limit

        **Cross-Limit Constraints:**
        - Total API key limit ≤ organization limit (if org limit configured)
        - Validation applies when updating either limit or both simultaneously
        - Returns 422 error if constraint violated

        **Cache Behavior:**
        - If limit is increased above current usage, exceeded cache is cleared
        - If limit is still below usage, exceeded cache is retained
        - Requests are immediately allowed/blocked based on new limits

        **Atomic Updates:**
        - When updating multiple limits, either all succeed or all fail
        - No partial updates on validation errors

        **Perfect for:**
        - Budget adjustments
        - API key provisioning
        - Cost control management
        - Emergency limit increases

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

        monthly_api_limit : typing.Optional[float]
            Organization limit in CHF (must be > 0)

        total_api_key_limit : typing.Optional[float]
            Total API key limit in CHF (must be > 0)

        api_key_id : typing.Optional[str]
            API key ID

        api_key_limit : typing.Optional[float]
            API key limit in CHF (must be > 0)

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

        Returns
        -------
        LimitUpdateResponse
            Successful Response

        Examples
        --------
        import asyncio

        from aitronos import AsyncAitronos

        client = AsyncAitronos(
            api_key="YOUR_API_KEY",
            token="YOUR_TOKEN",
        )


        async def main() -> None:
            await client.analytics_limits.update_usage_limits(
                org_id="org_id",
            )


        asyncio.run(main())
        """
        _response = await self._raw_client.update_usage_limits(
            org_id,
            monthly_api_limit=monthly_api_limit,
            total_api_key_limit=total_api_key_limit,
            api_key_id=api_key_id,
            api_key_limit=api_key_limit,
            request_options=request_options,
        )
        return _response.data

    async def get_api_key_usage(
        self,
        org_id: str,
        api_key_id: str,
        *,
        month: typing.Optional[int] = None,
        year: typing.Optional[int] = None,
        request_options: typing.Optional[RequestOptions] = None,
    ) -> ApiKeyUsageDetail:
        """
        Get detailed usage for a specific API key.

        Returns comprehensive usage information for a single API key including
        total requests, cost, synapses, neurons, and limit utilization.

        **Query Parameters:**
        - `month` (optional): Month to query (1-12), defaults to current month
        - `year` (optional): Year to query, defaults to current year

        **Response includes:**
        - API key identification (ID, name, organization)
        - Usage metrics (requests, cost, synapses, neurons, average cost)
        - Limit information (monthly limit, utilization, remaining budget, status)

        **Status Values:**
        - `ok`: utilization < 80%
        - `warning`: 80% <= utilization < 100%
        - `exceeded`: utilization >= 100%
        - `no_limit`: No limit configured

        **Perfect for:**
        - API key monitoring
        - Per-key cost tracking
        - Usage analysis
        - Limit management

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

        api_key_id : str

        month : typing.Optional[int]
            Month (1-12)

        year : typing.Optional[int]
            Year

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

        Returns
        -------
        ApiKeyUsageDetail
            Successful Response

        Examples
        --------
        import asyncio

        from aitronos import AsyncAitronos

        client = AsyncAitronos(
            api_key="YOUR_API_KEY",
            token="YOUR_TOKEN",
        )


        async def main() -> None:
            await client.analytics_limits.get_api_key_usage(
                org_id="org_id",
                api_key_id="api_key_id",
            )


        asyncio.run(main())
        """
        _response = await self._raw_client.get_api_key_usage(
            org_id, api_key_id, month=month, year=year, request_options=request_options
        )
        return _response.data
