"""
Neural LAB - AI Solutions Platform
Async Billing Resource.

Author: Anderson Henrique da Silva
Location: Minas Gerais, Brasil
Created: 2026-01-25
"""

from typing import Any

from .billing import Credits, Subscription, Usage


class AsyncBillingResource:
    """Async billing resource for usage and subscription management."""

    def __init__(self, client):
        self._client = client

    async def get_usage(self) -> Usage:
        """Get current usage for billing period."""
        response = await self._client.get("/api/billing/client/usage")

        return Usage(
            total_requests=response.get("total_requests", 0),
            total_tokens=response.get("total_tokens", 0),
            total_cost=response.get("total_cost", 0),
            included_requests=response.get("included_requests"),
            included_tokens=response.get("included_tokens"),
            requests_percentage=response.get("requests_percentage", 0),
            tokens_percentage=response.get("tokens_percentage", 0),
            period_start=response.get("period_start", ""),
            period_end=response.get("period_end", ""),
            days_remaining=response.get("days_remaining", 0),
        )

    async def get_subscription(self) -> Subscription:
        """Get current subscription."""
        response = await self._client.get("/api/billing/client/subscription")
        plan = response.get("plan", {})

        return Subscription(
            id=response.get("id", ""),
            plan_name=plan.get("name", "free"),
            status=response.get("status", "active"),
            billing_cycle=response.get("billing_cycle", "monthly"),
            current_period_start=response.get("current_period_start", ""),
            current_period_end=response.get("current_period_end", ""),
        )

    async def get_credits(self) -> Credits:
        """Get current credits balance."""
        response = await self._client.get("/api/billing/client/credits")

        return Credits(
            current_balance=response.get("current_balance", 0),
            credit_limit=response.get("credit_limit", 0),
            available=response.get("available", 0),
        )

    async def get_invoices(
        self,
        limit: int = 10,
        offset: int = 0,
    ) -> list[dict[str, Any]]:
        """Get invoices with pagination."""
        response = await self._client.get(
            "/api/billing/client/invoices",
            params={"limit": limit, "offset": offset},
        )
        return response.get("invoices", [])

    async def get_me(self) -> dict[str, Any]:
        """Get current client info."""
        return await self._client.get("/api/billing/client/me")
