"""
OpenAI MCP Adapter

Integrates OpenAI models with the HoneyDB MCP server using OpenAI's
MCP tool support via the responses API.
"""

from typing import Any, Callable

from openai import OpenAI

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


class OpenAIMCPAdapter(MCPAdapter):
    """
    OpenAI adapter with MCP server integration.

    Uses OpenAI's responses.create() API with MCP tool configuration
    to allow the model to invoke HoneyDB tools via the MCP server.

    Reference: Original implementation in llm_client.py:155-184
    """

    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 OpenAI MCP adapter.

        Args:
            api_key: OpenAI 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 = OpenAI(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 OpenAI with MCP server integration.

        Uses OpenAI's responses.create() API which supports MCP tools.
        The model can autonomously invoke HoneyDB tools during response generation.

        Args:
            messages: Messages in OpenAI format [{"role": "user", "content": "..."}]
            model: OpenAI model (e.g., "gpt-4", "gpt-4-turbo")
            temperature: Sampling temperature
            max_tokens: Maximum response tokens

        Returns:
            LLMResponse with assistant's reply

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

            # Configure MCP tools with HoneyDB server
            # This allows the model to invoke HoneyDB tools via the MCP server
            mcp_tools = [
                {
                    "type": "mcp",
                    "server_label": "honeydb_mcp",
                    "server_url": self.mcp_server_url,
                    "require_approval": "never",  # Auto-approve tool calls
                    "headers": {
                        "X-HoneyDb-ApiId": self.honeydb_api_id,
                        "X-HoneyDb-ApiKey": self.honeydb_api_key,
                    },
                }
            ]

            # Call OpenAI responses API with MCP configuration
            response = self.client.responses.create(
                model=model,
                tools=mcp_tools,
                input=messages,
                # Note: temperature and max_tokens not directly supported in responses API
                # These are handled by the model's default behavior
            )

            # Extract response text
            content = response.output_text

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

            # Create LLMResponse
            return LLMResponse(
                content=content,
                model=model,
                finish_reason=getattr(response, "finish_reason", None),
                usage={},  # Usage info not readily available in responses API
                metadata={
                    "provider": "openai",
                    "mcp_enabled": True,
                }
            )

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

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

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

        OpenAI uses standard format: [{"role": "user|assistant|system", "content": "..."}]

        Args:
            messages: Messages in standard format

        Returns:
            Messages in OpenAI format (unchanged, as format matches)
        """
        return messages
