"""
AgniPod SDK — High-Level Client
==================================

The ``AgniPod`` class is the primary entry point.  It lazily wires up
resource namespaces (``chat``, ``generate``, ``models``, ``batches``,
``billing``, ``keys``) on first access.
"""

from __future__ import annotations
from typing import Optional

from ._client import HttpClient
from .chat import Chat
from .generate import Generate
from .models import Models
from .batches import Batches
from .billing import Billing
from .keys import Keys


class AgniPod:
    """AgniPod API client.

    Parameters
    ----------
    api_key : str, optional
        Your API key (``agni_...``).  Falls back to the
        ``AGNIPOD_API_KEY`` environment variable, then
        ``~/.agnipod/credentials`` (saved via ``agnipod login``).
    timeout : float, optional
        Default request timeout in seconds (default 120).
    max_retries : int, optional
        Number of automatic retries on transient errors (default 2).

    Examples
    --------
    ::

        import agnipod

        client = agnipod.AgniPod()
        response = client.chat.create(
            model="qwen3:8b",
            messages=[{"role": "user", "content": "Hello!"}],
        )
        print(response.content)
    """

    def __init__(
        self,
        api_key: Optional[str] = None,
        *,
        timeout: Optional[float] = None,
        max_retries: Optional[int] = None,
    ):
        self._http = HttpClient(
            api_key=api_key,
            timeout=timeout,
            max_retries=max_retries,
        )

        # Lazy-initialised resource namespaces
        self._chat: Optional[Chat] = None
        self._generate: Optional[Generate] = None
        self._models: Optional[Models] = None
        self._batches: Optional[Batches] = None
        self._billing: Optional[Billing] = None
        self._keys: Optional[Keys] = None

    # ── Resource accessors (lazy) ────────────────────────────────────────

    @property
    def chat(self) -> Chat:
        """Chat completion operations."""
        if self._chat is None:
            self._chat = Chat(self._http)
        return self._chat

    @property
    def generate(self) -> Generate:
        """Text generation / completion operations."""
        if self._generate is None:
            self._generate = Generate(self._http)
        return self._generate

    @property
    def models(self) -> Models:
        """Model listing operations."""
        if self._models is None:
            self._models = Models(self._http)
        return self._models

    @property
    def batches(self) -> Batches:
        """Batch processing operations."""
        if self._batches is None:
            self._batches = Batches(self._http)
        return self._batches

    @property
    def billing(self) -> Billing:
        """Wallet & billing operations."""
        if self._billing is None:
            self._billing = Billing(self._http)
        return self._billing

    @property
    def keys(self) -> Keys:
        """API key management operations."""
        if self._keys is None:
            self._keys = Keys(self._http)
        return self._keys

    # ── Lifecycle ────────────────────────────────────────────────────────

    def close(self):
        """Close the underlying HTTP session."""
        self._http.close()

    def __enter__(self):
        return self

    def __exit__(self, *exc):
        self.close()

    def __repr__(self) -> str:
        return f"AgniPod(api_url='{self._http.base_url}')"


# Backward-compat alias
Agnipod = AgniPod