"""Native Anthropic (Claude) connector using the stable Messages API.

Unlike OpenAI, Anthropic takes the system prompt as a top-level ``system``
argument and *requires* ``max_tokens``. Text is reassembled from the response's
content blocks (thinking blocks, when enabled, are ignored here).
"""

from __future__ import annotations

from typing import Any

from pentestgpt_legacy.llm.base import BaseProvider, Message
from pentestgpt_legacy.llm.registry import ModelSpec

# Anthropic requires an explicit output cap; generous enough for detailed steps.
_DEFAULT_MAX_TOKENS = 8192


class AnthropicProvider(BaseProvider):
    """Async Anthropic Messages API provider."""

    async def acomplete(
        self,
        messages: list[Message],
        system: str | None,
        spec: ModelSpec,
        *,
        max_output_tokens: int | None = None,
        temperature: float | None = None,
    ) -> str:
        try:
            from anthropic import AsyncAnthropic
        except ImportError as exc:  # pragma: no cover - install-time guard
            raise RuntimeError(
                "The 'anthropic' package is required. Install with: uv add anthropic"
            ) from exc

        kwargs: dict[str, Any] = {
            "model": spec.api_id,
            "messages": list(messages),
            "max_tokens": max_output_tokens or _DEFAULT_MAX_TOKENS,
        }
        if system:
            kwargs["system"] = system
        if temperature is not None:
            kwargs["temperature"] = temperature

        async with AsyncAnthropic(api_key=self.api_key or "") as client:
            response = await client.messages.create(**kwargs)

        parts = [block.text for block in response.content if getattr(block, "type", None) == "text"]
        return "".join(parts)
