from __future__ import annotations

from ..models import ProviderResponse, ToolProposal
from ..scenarios import Scenario
from .base import (
    SYSTEM_INSTRUCTION,
    TOOL_PARAMETERS,
    ProviderAdapter,
    post_json,
    scenario_prompt,
)


class AnthropicAdapter(ProviderAdapter):
    provider = "anthropic"

    def propose(self, scenario: Scenario) -> ProviderResponse:
        payload = {
            "model": self.model,
            "max_tokens": 500,
            "system": SYSTEM_INSTRUCTION,
            "messages": [{"role": "user", "content": scenario_prompt(scenario)}],
            "tools": [
                {
                    "name": "propose_action",
                    "description": "Propose one synthetic action for policy evaluation.",
                    "input_schema": TOOL_PARAMETERS,
                }
            ],
            "tool_choice": {"type": "tool", "name": "propose_action"},
        }
        raw = post_json(
            "https://api.anthropic.com/v1/messages",
            {
                "x-api-key": self._api_key,
                "anthropic-version": "2023-06-01",
                "Content-Type": "application/json",
            },
            payload,
            self.timeout_seconds,
        )
        proposals: list[ToolProposal] = []
        text_parts: list[str] = []
        for block in raw.get("content", []):
            if block.get("type") == "tool_use":
                proposals.append(
                    ToolProposal(
                        name=str(block.get("name", "")),
                        arguments=dict(block.get("input", {})),
                        call_id=str(block.get("id", "")),
                    )
                )
            elif block.get("type") == "text":
                text_parts.append(str(block.get("text", "")))
        usage = raw.get("usage", {})
        return ProviderResponse(
            provider=self.provider,
            model=self.model,
            text="\n".join(text_parts),
            proposals=tuple(proposals),
            input_tokens=int(usage.get("input_tokens", 0)),
            output_tokens=int(usage.get("output_tokens", 0)),
            raw_stop_reason=str(raw.get("stop_reason", "")),
        )
