"""Auto-resolve the best available token counter for a given model."""

from __future__ import annotations

from context_manager.budget.base import TokenCounter

# Known prefixes that map to each provider's counter.
_TIKTOKEN_PREFIXES = ("gpt-", "text-", "davinci", "o1", "o3", "o4")
_GOOGLE_PREFIXES = ("gemini-", "gemma-")
_ANTHROPIC_PREFIXES = ("claude-",)


def get_counter(model: str) -> TokenCounter:
    """Return an appropriate TokenCounter for *model*.

    Resolution order:
    1. tiktoken — if available and model looks like an OpenAI model.
    2. GoogleCounter — if model looks like a Gemini / Gemma model.
    3. AnthropicCounter — if model looks like a Claude model.
    4. HuggingFace tokenizers — if available and model contains '/'.
    5. tiktoken — general fallback.
    6. CharCounter — zero-dependency fallback.
    """
    lower = model.lower()

    if any(lower.startswith(p) for p in _TIKTOKEN_PREFIXES):
        try:
            from context_manager.budget.tiktoken_counter import TiktokenCounter

            return TiktokenCounter(model)
        except ImportError:
            pass

    if any(lower.startswith(p) for p in _GOOGLE_PREFIXES):
        try:
            from context_manager.budget.google_counter import GoogleCounter

            return GoogleCounter(model)
        except ImportError:
            pass

    if any(lower.startswith(p) for p in _ANTHROPIC_PREFIXES):
        try:
            from context_manager.budget.anthropic_counter import AnthropicCounter

            return AnthropicCounter(model)
        except ImportError:
            pass

    if "/" in model:
        try:
            from context_manager.budget.hf_counter import HFTokenCounter

            return HFTokenCounter(model)
        except ImportError:
            pass

    # Try tiktoken as a general fallback before char counter.
    try:
        from context_manager.budget.tiktoken_counter import TiktokenCounter

        return TiktokenCounter(model)
    except ImportError:
        pass

    from context_manager.budget.char_counter import CharCounter

    return CharCounter()
