# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.

from __future__ import annotations

from typing_extensions import Literal

import httpx

from ..._types import Body, Omit, Query, Headers, NotGiven, omit, not_given
from ..._utils import maybe_transform, async_maybe_transform
from ..._compat import cached_property
from ..._resource import SyncAPIResource, AsyncAPIResource
from ..._response import (
    to_raw_response_wrapper,
    to_streamed_response_wrapper,
    async_to_raw_response_wrapper,
    async_to_streamed_response_wrapper,
)
from ..._base_client import make_request_options
from ...types.tenants import usage_retrieve_params, usage_retrieve_timeseries_params
from ...types.tenants.usage_retrieve_response import UsageRetrieveResponse
from ...types.tenants.usage_retrieve_timeseries_response import UsageRetrieveTimeseriesResponse

__all__ = ["UsageResource", "AsyncUsageResource"]


class UsageResource(SyncAPIResource):
    @cached_property
    def with_raw_response(self) -> UsageResourceWithRawResponse:
        """
        This property can be used as a prefix for any HTTP method call to return
        the raw response object instead of the parsed content.

        For more information, see https://www.github.com/ArkHQ-io/ark-python#accessing-raw-response-data-eg-headers
        """
        return UsageResourceWithRawResponse(self)

    @cached_property
    def with_streaming_response(self) -> UsageResourceWithStreamingResponse:
        """
        An alternative to `.with_raw_response` that doesn't eagerly read the response body.

        For more information, see https://www.github.com/ArkHQ-io/ark-python#with_streaming_response
        """
        return UsageResourceWithStreamingResponse(self)

    def retrieve(
        self,
        tenant_id: str,
        *,
        period: str | Omit = omit,
        timezone: str | Omit = omit,
        # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs.
        # The extra values given here take precedence over values defined on the client or passed to this method.
        extra_headers: Headers | None = None,
        extra_query: Query | None = None,
        extra_body: Body | None = None,
        timeout: float | httpx.Timeout | None | NotGiven = not_given,
    ) -> UsageRetrieveResponse:
        """
        Returns email sending statistics for a specific tenant over a time period.

        **Use cases:**

        - Display usage dashboard to your customers
        - Calculate per-tenant billing
        - Monitor tenant health and delivery rates

        **Period formats:**

        - Shortcuts: `today`, `yesterday`, `this_week`, `last_week`, `this_month`,
          `last_month`, `last_7_days`, `last_30_days`, `last_90_days`
        - Month: `2024-01` (full month)
        - Date range: `2024-01-01..2024-01-31`
        - Single day: `2024-01-15`

        **Response includes:**

        - `emails` - Counts for sent, delivered, soft_failed, hard_failed, bounced, held
        - `rates` - Delivery rate and bounce rate as decimals (0.95 = 95%)

        Args:
          period: Time period for usage data. Defaults to current month.

              **Formats:**

              - Shortcuts: `today`, `yesterday`, `this_week`, `last_week`, `this_month`,
                `last_month`, `last_7_days`, `last_30_days`, `last_90_days`
              - Month: `2024-01`
              - Range: `2024-01-01..2024-01-31`
              - Day: `2024-01-15`

          timezone: Timezone for period calculations (IANA format). Defaults to UTC.

          extra_headers: Send extra headers

          extra_query: Add additional query parameters to the request

          extra_body: Add additional JSON properties to the request

          timeout: Override the client-level default timeout for this request, in seconds
        """
        if not tenant_id:
            raise ValueError(f"Expected a non-empty value for `tenant_id` but received {tenant_id!r}")
        return self._get(
            f"/tenants/{tenant_id}/usage",
            options=make_request_options(
                extra_headers=extra_headers,
                extra_query=extra_query,
                extra_body=extra_body,
                timeout=timeout,
                query=maybe_transform(
                    {
                        "period": period,
                        "timezone": timezone,
                    },
                    usage_retrieve_params.UsageRetrieveParams,
                ),
            ),
            cast_to=UsageRetrieveResponse,
        )

    def retrieve_timeseries(
        self,
        tenant_id: str,
        *,
        granularity: Literal["hour", "day", "week", "month"] | Omit = omit,
        period: str | Omit = omit,
        timezone: str | Omit = omit,
        # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs.
        # The extra values given here take precedence over values defined on the client or passed to this method.
        extra_headers: Headers | None = None,
        extra_query: Query | None = None,
        extra_body: Body | None = None,
        timeout: float | httpx.Timeout | None | NotGiven = not_given,
    ) -> UsageRetrieveTimeseriesResponse:
        """
        Returns time-bucketed email statistics for a specific tenant.

        **Use cases:**

        - Build usage charts and graphs
        - Identify sending patterns
        - Detect anomalies in delivery rates

        **Granularity options:**

        - `hour` - Hourly buckets (best for last 7 days)
        - `day` - Daily buckets (best for last 30-90 days)
        - `week` - Weekly buckets (best for last 6 months)
        - `month` - Monthly buckets (best for year-over-year)

        The response includes a data point for each time bucket with all email metrics.

        Args:
          granularity: Time bucket size for data points

          period: Time period for timeseries data. Defaults to current month.

          timezone: Timezone for period calculations (IANA format). Defaults to UTC.

          extra_headers: Send extra headers

          extra_query: Add additional query parameters to the request

          extra_body: Add additional JSON properties to the request

          timeout: Override the client-level default timeout for this request, in seconds
        """
        if not tenant_id:
            raise ValueError(f"Expected a non-empty value for `tenant_id` but received {tenant_id!r}")
        return self._get(
            f"/tenants/{tenant_id}/usage/timeseries",
            options=make_request_options(
                extra_headers=extra_headers,
                extra_query=extra_query,
                extra_body=extra_body,
                timeout=timeout,
                query=maybe_transform(
                    {
                        "granularity": granularity,
                        "period": period,
                        "timezone": timezone,
                    },
                    usage_retrieve_timeseries_params.UsageRetrieveTimeseriesParams,
                ),
            ),
            cast_to=UsageRetrieveTimeseriesResponse,
        )


class AsyncUsageResource(AsyncAPIResource):
    @cached_property
    def with_raw_response(self) -> AsyncUsageResourceWithRawResponse:
        """
        This property can be used as a prefix for any HTTP method call to return
        the raw response object instead of the parsed content.

        For more information, see https://www.github.com/ArkHQ-io/ark-python#accessing-raw-response-data-eg-headers
        """
        return AsyncUsageResourceWithRawResponse(self)

    @cached_property
    def with_streaming_response(self) -> AsyncUsageResourceWithStreamingResponse:
        """
        An alternative to `.with_raw_response` that doesn't eagerly read the response body.

        For more information, see https://www.github.com/ArkHQ-io/ark-python#with_streaming_response
        """
        return AsyncUsageResourceWithStreamingResponse(self)

    async def retrieve(
        self,
        tenant_id: str,
        *,
        period: str | Omit = omit,
        timezone: str | Omit = omit,
        # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs.
        # The extra values given here take precedence over values defined on the client or passed to this method.
        extra_headers: Headers | None = None,
        extra_query: Query | None = None,
        extra_body: Body | None = None,
        timeout: float | httpx.Timeout | None | NotGiven = not_given,
    ) -> UsageRetrieveResponse:
        """
        Returns email sending statistics for a specific tenant over a time period.

        **Use cases:**

        - Display usage dashboard to your customers
        - Calculate per-tenant billing
        - Monitor tenant health and delivery rates

        **Period formats:**

        - Shortcuts: `today`, `yesterday`, `this_week`, `last_week`, `this_month`,
          `last_month`, `last_7_days`, `last_30_days`, `last_90_days`
        - Month: `2024-01` (full month)
        - Date range: `2024-01-01..2024-01-31`
        - Single day: `2024-01-15`

        **Response includes:**

        - `emails` - Counts for sent, delivered, soft_failed, hard_failed, bounced, held
        - `rates` - Delivery rate and bounce rate as decimals (0.95 = 95%)

        Args:
          period: Time period for usage data. Defaults to current month.

              **Formats:**

              - Shortcuts: `today`, `yesterday`, `this_week`, `last_week`, `this_month`,
                `last_month`, `last_7_days`, `last_30_days`, `last_90_days`
              - Month: `2024-01`
              - Range: `2024-01-01..2024-01-31`
              - Day: `2024-01-15`

          timezone: Timezone for period calculations (IANA format). Defaults to UTC.

          extra_headers: Send extra headers

          extra_query: Add additional query parameters to the request

          extra_body: Add additional JSON properties to the request

          timeout: Override the client-level default timeout for this request, in seconds
        """
        if not tenant_id:
            raise ValueError(f"Expected a non-empty value for `tenant_id` but received {tenant_id!r}")
        return await self._get(
            f"/tenants/{tenant_id}/usage",
            options=make_request_options(
                extra_headers=extra_headers,
                extra_query=extra_query,
                extra_body=extra_body,
                timeout=timeout,
                query=await async_maybe_transform(
                    {
                        "period": period,
                        "timezone": timezone,
                    },
                    usage_retrieve_params.UsageRetrieveParams,
                ),
            ),
            cast_to=UsageRetrieveResponse,
        )

    async def retrieve_timeseries(
        self,
        tenant_id: str,
        *,
        granularity: Literal["hour", "day", "week", "month"] | Omit = omit,
        period: str | Omit = omit,
        timezone: str | Omit = omit,
        # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs.
        # The extra values given here take precedence over values defined on the client or passed to this method.
        extra_headers: Headers | None = None,
        extra_query: Query | None = None,
        extra_body: Body | None = None,
        timeout: float | httpx.Timeout | None | NotGiven = not_given,
    ) -> UsageRetrieveTimeseriesResponse:
        """
        Returns time-bucketed email statistics for a specific tenant.

        **Use cases:**

        - Build usage charts and graphs
        - Identify sending patterns
        - Detect anomalies in delivery rates

        **Granularity options:**

        - `hour` - Hourly buckets (best for last 7 days)
        - `day` - Daily buckets (best for last 30-90 days)
        - `week` - Weekly buckets (best for last 6 months)
        - `month` - Monthly buckets (best for year-over-year)

        The response includes a data point for each time bucket with all email metrics.

        Args:
          granularity: Time bucket size for data points

          period: Time period for timeseries data. Defaults to current month.

          timezone: Timezone for period calculations (IANA format). Defaults to UTC.

          extra_headers: Send extra headers

          extra_query: Add additional query parameters to the request

          extra_body: Add additional JSON properties to the request

          timeout: Override the client-level default timeout for this request, in seconds
        """
        if not tenant_id:
            raise ValueError(f"Expected a non-empty value for `tenant_id` but received {tenant_id!r}")
        return await self._get(
            f"/tenants/{tenant_id}/usage/timeseries",
            options=make_request_options(
                extra_headers=extra_headers,
                extra_query=extra_query,
                extra_body=extra_body,
                timeout=timeout,
                query=await async_maybe_transform(
                    {
                        "granularity": granularity,
                        "period": period,
                        "timezone": timezone,
                    },
                    usage_retrieve_timeseries_params.UsageRetrieveTimeseriesParams,
                ),
            ),
            cast_to=UsageRetrieveTimeseriesResponse,
        )


class UsageResourceWithRawResponse:
    def __init__(self, usage: UsageResource) -> None:
        self._usage = usage

        self.retrieve = to_raw_response_wrapper(
            usage.retrieve,
        )
        self.retrieve_timeseries = to_raw_response_wrapper(
            usage.retrieve_timeseries,
        )


class AsyncUsageResourceWithRawResponse:
    def __init__(self, usage: AsyncUsageResource) -> None:
        self._usage = usage

        self.retrieve = async_to_raw_response_wrapper(
            usage.retrieve,
        )
        self.retrieve_timeseries = async_to_raw_response_wrapper(
            usage.retrieve_timeseries,
        )


class UsageResourceWithStreamingResponse:
    def __init__(self, usage: UsageResource) -> None:
        self._usage = usage

        self.retrieve = to_streamed_response_wrapper(
            usage.retrieve,
        )
        self.retrieve_timeseries = to_streamed_response_wrapper(
            usage.retrieve_timeseries,
        )


class AsyncUsageResourceWithStreamingResponse:
    def __init__(self, usage: AsyncUsageResource) -> None:
        self._usage = usage

        self.retrieve = async_to_streamed_response_wrapper(
            usage.retrieve,
        )
        self.retrieve_timeseries = async_to_streamed_response_wrapper(
            usage.retrieve_timeseries,
        )
