"""
AgniPod — Python SDK
=====================

Quickstart::

    import agnipod

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

Or use the top-level helpers (reads ``AGNIPOD_API_KEY`` from env
or ``~/.agnipod/credentials``)::

    from agnipod import chat, generate

    print(chat("Hello!", model="qwen3:8b"))
    print(generate("Once upon a time", model="qwen3:8b"))
"""

from ._config import VERSION as __version__

# ── Primary client ───────────────────────────────────────────────────────
from .main import AgniPod, Agnipod  # Agnipod = backward-compat alias

# ── Resource classes (for type hints) ────────────────────────────────────
from .chat import Chat
from .generate import Generate
from .models import Models
from .batches import Batches
from .billing import Billing
from .keys import Keys

# ── Exception hierarchy ──────────────────────────────────────────────────
from ._exceptions import (
    AgniPodError,
    AuthenticationError,
    BadRequestError,
    ConfigurationError,
    APIConnectionError,
    InsufficientBalanceError,
    NotFoundError,
    PermissionDeniedError,
    RateLimitError,
    ServerError,
    ServiceUnavailableError,
    StreamError,
    APITimeoutError,
    ValidationError,
)

# ── Response types ───────────────────────────────────────────────────────
from ._types import (
    ApiKey,
    ApiKeyCreated,
    ApiKeyList,
    Balance,
    Batch,
    BatchCreateResult,
    BatchList,
    BatchProgress,
    Completion,
    Model,
    ModelList,
    StreamChunk,
    StreamDelta,
    StreamResponse,
    Transaction,
    TransactionList,
    UsageSummary,
    Wallet,
)


# ── Convenience top-level functions ──────────────────────────────────────
# Auto-create a default client from AGNIPOD_API_KEY env var or saved creds.

_default_client: AgniPod | None = None


def _get_client() -> AgniPod:
    """Return (and cache) a default client instance."""
    global _default_client
    if _default_client is None:
        _default_client = AgniPod()
    return _default_client


def chat(
    message: str | None = None,
    *,
    model: str = "qwen3:8b",
    messages: list | None = None,
    stream: bool = False,
    **kwargs,
) -> Completion | StreamResponse:
    """Quick chat completion.

    Accepts either a simple *message* string (auto-wrapped as a user
    message) or a full *messages* list.

    Examples::

        from agnipod import chat

        # Simple
        response = chat("What is AI?", model="qwen3:8b")
        print(response.content)

        # With full messages
        response = chat(messages=[
            {"role": "system", "content": "You are helpful."},
            {"role": "user", "content": "Hello!"},
        ], model="qwen3:8b")
    """
    if messages is None:
        if message is None:
            raise ValidationError("Provide either 'message' or 'messages'")
        messages = [{"role": "user", "content": message}]

    return _get_client().chat.create(
        model=model, messages=messages, stream=stream, **kwargs,
    )


def generate(
    prompt: str,
    *,
    model: str = "qwen3:8b",
    **kwargs,
) -> Completion:
    """Quick text generation.

    Example::

        from agnipod import generate

        response = generate("Once upon a time", model="qwen3:8b")
        print(response.content)
    """
    return _get_client().generate.create(model=model, prompt=prompt, **kwargs)


# ── Public API ───────────────────────────────────────────────────────────

__all__ = [
    # Client
    "AgniPod",
    "Agnipod",
    "__version__",
    # Resource classes
    "Chat",
    "Generate",
    "Models",
    "Batches",
    "Billing",
    "Keys",
    # Convenience functions
    "chat",
    "generate",
    # Exceptions
    "AgniPodError",
    "AuthenticationError",
    "BadRequestError",
    "ConfigurationError",
    "APIConnectionError",
    "InsufficientBalanceError",
    "NotFoundError",
    "PermissionDeniedError",
    "RateLimitError",
    "ServerError",
    "ServiceUnavailableError",
    "StreamError",
    "APITimeoutError",
    "ValidationError",
    # Types
    "ApiKey",
    "ApiKeyCreated",
    "ApiKeyList",
    "Balance",
    "Batch",
    "BatchCreateResult",
    "BatchList",
    "BatchProgress",
    "Completion",
    "Model",
    "ModelList",
    "StreamChunk",
    "StreamDelta",
    "StreamResponse",
    "Transaction",
    "TransactionList",
    "UsageSummary",
    "Wallet",
]