import anthropic

from .base import LLMProvider
from .json_utils import parse_json_response


class AnthropicProvider(LLMProvider):
    """Native Anthropic Messages API. Unlike the OpenAI wire format, the system
    prompt is its own top-level parameter and the messages list may only contain
    "user"/"assistant" roles - both handled here so callers never need to know that.
    """

    def __init__(self, api_key: str | None, model: str, max_tokens: int = 4096) -> None:
        self.client = anthropic.Anthropic(api_key=api_key)
        self.model = model
        self.max_tokens = max_tokens

    def complete_json(self, system_prompt: str, messages: list[dict]) -> dict:
        response = self.client.messages.create(
            model=self.model,
            max_tokens=self.max_tokens,
            system=system_prompt,
            messages=messages,
        )
        text = "".join(block.text for block in response.content if block.type == "text")
        return parse_json_response(text)
