"""Quota API endpoints.

Per-series quota management. Each subscription has its own quota
tracked independently via SeriesQuota.
"""

from __future__ import annotations

from typing import TYPE_CHECKING
from uuid import UUID

from vikdata.models.common import PaginatedResponse
from vikdata.models.billing import (
    SeriesQuota,
    QuotaRequest,
    CreateQuotaRequestModel,
    ReviewQuotaRequestModel,
)

if TYPE_CHECKING:
    from vikdata.client import VikdataClient


class QuotaRequestsAPI:
    """Quota request management."""

    def __init__(self, client: "VikdataClient") -> None:
        self._client = client

    async def list(
        self,
        *,
        page: int | None = None,
        per_page: int | None = None,
        series_id: UUID | None = None,
        status: str | None = None,
    ) -> PaginatedResponse[QuotaRequest]:
        """List quota requests.

        Users see their own tenant's requests.
        Admins with quotas:manage permission see all requests.

        Args:
            page: Page number (default: 1)
            per_page: Items per page (default: 20, max: 100)
            series_id: Filter by series
            status: Filter by status (from lookup)

        Returns:
            Paginated list of quota requests
        """
        params = {
            "page": page,
            "per_page": per_page,
            "series_id": str(series_id) if series_id else None,
            "status": status,
        }
        params = {k: v for k, v in params.items() if v is not None}

        return await self._client.request(
            "GET",
            "/api/v1/quotas/requests",
            params=params,
            response_model=PaginatedResponse[QuotaRequest],
        )

    async def get(self, request_id: UUID) -> QuotaRequest:
        """Get a quota request by ID.

        Args:
            request_id: Request ID

        Returns:
            Quota request details
        """
        return await self._client.request(
            "GET",
            f"/api/v1/quotas/requests/{request_id}",
            response_model=QuotaRequest,
        )

    async def create(self, data: CreateQuotaRequestModel) -> QuotaRequest:
        """Create a new quota request.

        Requests are additive - you request additional quota on top of plan limits.

        Args:
            data: Quota request data

        Returns:
            Created quota request
        """
        return await self._client.request(
            "POST",
            "/api/v1/quotas/requests",
            json=data,
            response_model=QuotaRequest,
        )

    async def review(
        self,
        request_id: UUID,
        data: ReviewQuotaRequestModel,
    ) -> QuotaRequest:
        """Review (approve/reject) a quota request (admin only).

        Approving adds the requested amounts to the series quota.

        Args:
            request_id: Request ID
            data: Review data with status and optional notes

        Returns:
            Updated quota request
        """
        return await self._client.request(
            "POST",
            f"/api/v1/quotas/requests/{request_id}/review",
            json=data,
            response_model=QuotaRequest,
        )


class QuotasAPI:
    """Quota API endpoints.

    Per-series quota management for tenants.
    """

    def __init__(self, client: "VikdataClient") -> None:
        self._client = client
        self.requests = QuotaRequestsAPI(client)

    async def list(self) -> list[SeriesQuota]:
        """List all series quotas for the current tenant.

        Returns one quota per subscribed series.

        Returns:
            List of series quotas
        """
        response = await self._client.request(
            "GET",
            "/api/v1/quotas",
        )
        # Handle response structure - may be wrapped in data key
        if isinstance(response, dict) and "data" in response:
            return [SeriesQuota.model_validate(q) for q in response["data"]]
        return [SeriesQuota.model_validate(q) for q in response]

    async def get_for_series(self, series_id: UUID) -> SeriesQuota:
        """Get quota for a specific series.

        Args:
            series_id: Series ID

        Returns:
            Series quota details
        """
        return await self._client.request(
            "GET",
            f"/api/v1/quotas/series/{series_id}",
            response_model=SeriesQuota,
        )
