"""Global configuration for the Savvy SDK."""

import os
from typing import Optional

# Global configuration (module-level state)
api_key: Optional[str] = None
api_url: str = "https://api.savvy-mcp.com"


def configure(
    *,
    api_key: Optional[str] = None,
    api_url: Optional[str] = None,
) -> None:
    """
    Configure the Savvy SDK globally.

    Args:
        api_key: Your Savvy API key. Can also be set via SAVVY_API_KEY env var.
        api_url: Override the API URL (for development/testing).

    Example:
        >>> import savvy
        >>> savvy.configure(api_key="sk_...")
    """
    import savvy._config as config

    if api_key is not None:
        config.api_key = api_key
    if api_url is not None:
        config.api_url = api_url


def get_api_key() -> str:
    """
    Get the API key from config or environment.

    Returns:
        The API key.

    Raises:
        AuthenticationError: If no API key is configured.
    """
    from savvy.exceptions import AuthenticationError

    key = api_key or os.environ.get("SAVVY_API_KEY")
    if not key:
        raise AuthenticationError(
            "API key required. Set SAVVY_API_KEY environment variable "
            "or call savvy.configure(api_key='sk_...')"
        )
    return key


def get_api_url() -> str:
    """Get the API URL from config or environment."""
    return os.environ.get("SAVVY_API_URL", api_url)
