"""
Anthropic MCP Adapter

Integrates Anthropic Claude models with the HoneyDB MCP server using
Anthropic's beta MCP server support.
"""

from typing import Any, Callable

import anthropic

from honeydb_ai.domain.models import LLMResponse
from honeydb_ai.infrastructure.mcp.base import MCPAdapter
from honeydb_ai.utils.logging import get_logger


class AnthropicMCPAdapter(MCPAdapter):
    """
    Anthropic adapter with MCP server integration.

    Uses Anthropic's beta messages API with mcp_servers parameter
    to allow Claude models to invoke HoneyDB tools via the MCP server.

    Reference: Original implementation in llm_client.py:187-224
    """

    def __init__(
        self,
        api_key: str,
        mcp_server_url: str,
        honeydb_api_id: str,
        honeydb_api_key: str,
        event_callback: Callable[[str, dict[str, Any]], None] | None = None,
    ):
        """
        Initialize Anthropic MCP adapter.

        Args:
            api_key: Anthropic API key
            mcp_server_url: HoneyDB MCP server URL (e.g., https://honeydb.ai/sse/)
            honeydb_api_id: HoneyDB API ID
            honeydb_api_key: HoneyDB API key
            event_callback: Optional callback for tool invocation events
        """
        super().__init__(api_key, mcp_server_url, honeydb_api_id, honeydb_api_key, event_callback)
        self.client = anthropic.Anthropic(api_key=api_key)
        self.logger = get_logger()

    async def send_message(
        self,
        messages: list[dict[str, Any]],
        model: str,
        temperature: float = 0.7,
        max_tokens: int | None = None,
    ) -> LLMResponse:
        """
        Send message to Anthropic with MCP server integration.

        Uses Anthropic's beta messages API with mcp_servers configuration.
        The model can autonomously invoke HoneyDB tools during response generation.

        Args:
            messages: Messages in Anthropic format [{"role": "user|assistant", "content": "..."}]
            model: Anthropic model (e.g., "claude-sonnet-4-20250514")
            temperature: Sampling temperature
            max_tokens: Maximum response tokens (default: 4096)

        Returns:
            LLMResponse with assistant's reply

        Raises:
            Exception: If the API call fails
        """
        try:
            self.logger.debug(f"Sending request to Anthropic model: {model}")
            self._emit_event("request_started", {"model": model, "provider": "anthropic"})

            # Configure MCP server with HoneyDB credentials
            # Anthropic uses special authorization token format: HONEYDB<id>HONEYDB<key>
            mcp_servers = [
                {
                    "type": "url",
                    "url": self.mcp_server_url,
                    "name": "honeydb_mcp",
                    "authorization_token": f"HONEYDB{self.honeydb_api_id}HONEYDB{self.honeydb_api_key}",
                }
            ]

            # Call Anthropic beta messages API with MCP configuration
            # Note: Requires beta header for MCP support
            response = self.client.beta.messages.create(
                model=model,
                max_tokens=max_tokens or 4096,
                messages=messages,
                mcp_servers=mcp_servers,
                extra_headers={"anthropic-beta": "mcp-client-2025-04-04"},
            )

            # Extract text content from response
            # Anthropic returns content as list of blocks
            content_parts = []
            for block in response.content:
                if block.type == "text":
                    content_parts.append(block.text)

            content = "\n".join(content_parts)

            self.logger.debug(f"Received response from Anthropic: {len(content)} characters")
            self._emit_event("response_received", {
                "model": model,
                "provider": "anthropic",
                "content_length": len(content)
            })

            # Create LLMResponse
            return LLMResponse(
                content=content,
                model=model,
                finish_reason=response.stop_reason,
                usage={
                    "input_tokens": response.usage.input_tokens,
                    "output_tokens": response.usage.output_tokens,
                },
                metadata={
                    "provider": "anthropic",
                    "mcp_enabled": True,
                    "stop_sequence": response.stop_sequence,
                }
            )

        except Exception as e:
            self.logger.error(f"Anthropic API error: {e}")
            raise

    def get_provider_name(self) -> str:
        """Get provider name."""
        return "anthropic"

    def format_messages(self, messages: list[dict[str, str]]) -> list[dict[str, Any]]:
        """
        Format messages to Anthropic format.

        Anthropic requires:
        - Only "user" and "assistant" roles (no "system")
        - System messages should be passed separately
        - Content is just a string

        Args:
            messages: Messages in standard format

        Returns:
            Messages in Anthropic format
        """
        formatted = []
        for msg in messages:
            role = msg["role"]
            # Skip system messages (should be handled separately)
            if role == "system":
                continue
            formatted.append({
                "role": role,
                "content": msg["content"]
            })
        return formatted
