"""Token counter using Anthropic's SDK (Claude models)."""

from __future__ import annotations

from context_manager.budget.base import TokenCounter


class AnthropicCounter(TokenCounter):
    """Count tokens for Anthropic Claude models via the Messages API.

    Requires the ``anthropic`` package and a valid API key
    (passed explicitly or set as ``ANTHROPIC_API_KEY`` env var).
    """

    def __init__(self, model: str = "claude-sonnet-4-20250514", api_key: str | None = None) -> None:
        try:
            import anthropic
        except ImportError as exc:
            raise ImportError(
                "anthropic is required for Claude models. "
                "Install with: pip install llm-ctx-mgr[anthropic]"
            ) from exc

        self._model = model
        self._client = anthropic.Anthropic(api_key=api_key) if api_key else anthropic.Anthropic()

    def count(self, text: str) -> int:
        """Return token count via the Anthropic count_tokens API."""
        response = self._client.messages.count_tokens(
            model=self._model,
            messages=[{"role": "user", "content": text}],
        )
        return response.input_tokens

    def model_name(self) -> str:
        return self._model
