"""
TokenVault SDK - Agent Usage Tracking Library

A lightweight Python SDK for AI agents to track LLM usage and forward billing data to TokenVault.
Provides simple functions for balance checking and usage tracking without wrapping your LLM client.
"""

from tokenvault_sdk.config import SDKConfig
from tokenvault_sdk.tracker import UsageTracker
from tokenvault_sdk.exceptions import (
    InsufficientBalanceError,
    SDKConfigurationError,
    TrackingError,
)
from tokenvault_sdk.logging_config import configure_logging, get_logger

__version__ = "0.1.7"
__all__ = [
    "SDKConfig",
    "UsageTracker",
    "InsufficientBalanceError",
    "SDKConfigurationError",
    "TrackingError",
    "configure_logging",
    "get_logger",
    "quickstart",
]


async def quickstart(
    organization_id: str,
    agent_name: str = "agent",
    user_id: str = None,
) -> tuple[UsageTracker, str]:
    """
    ONE LINE. ZERO PARAMETERS. PERFECT.

    Organization onboarding grants are automatically handled by the backend.
    Check your backend configuration for free trial amounts.

    Usage:
        tracker, agent_id = await quickstart("acme", "sales-bot")
    """
    import uuid
    import httpx

    config = SDKConfig.from_env()
    tracker = UsageTracker(
        redis_url=config.redis_url,
        tokenvault_api_url=config.tokenvault_api_url,
    )

    # Auto-fill safe defaults (moved from BootstrapConfig)
    organization_name = f"Org {organization_id}"
    user_id = user_id or f"user_{uuid.uuid4().hex[:12]}"
    user_name = "Auto User"
    user_email = f"{user_id}@local"
    profile_id = f"agent_{agent_name}_{uuid.uuid4().hex[:8]}"

    api = config.tokenvault_api_url
    created = []

    # 1. Organization - API is idempotent, so just create it
    async with httpx.AsyncClient(timeout=15.0) as client:
        print(f"Ensuring organization exists: {organization_name}")
        await client.post(f"{api}/v1/wallet/organizations", json={
            "id": organization_id,
            "name": organization_name,
            "profile_id": profile_id,  # Use the profile_id that will be used for tracking
        })
        created.append("organization")

    # Note: User and profile creation endpoints not implemented yet
    # For now, just use the profile_id as-is
    print(f"Using profile: {profile_id}")
    created.extend(["user", "profile"])  # Mark as created for compatibility

    # 4. Check balance (onboarding grant is handled by backend)
    async with httpx.AsyncClient(timeout=15.0) as client:
        bal_resp = await client.get(f"{api}/v1/wallet/organizations/{organization_id}/balance")
        balance = bal_resp.json().get("balance", 0)
        print(f"Organization balance: {balance} credits")
        if balance > 0:
            created.append("credits")

    print(f"TokenVault Ready → Created: {', '.join(created) or 'nothing (already exists)'}")

    return tracker, profile_id
