import os
from typing import Dict, List, Optional, Union

from powermem.integrations.llm import LLMBase
from powermem.integrations.llm.config.anthropic import AnthropicConfig
from powermem.integrations.llm.config.base import BaseLLMConfig

try:
    import anthropic
except ImportError:
    raise ImportError("The 'anthropic' library is required. Please install it using 'pip install anthropic'.")


class AnthropicLLM(LLMBase):
    def __init__(self, config: Optional[Union[BaseLLMConfig, AnthropicConfig, Dict]] = None):
        # Convert to AnthropicConfig if needed
        if config is None:
            config = AnthropicConfig()
        elif isinstance(config, dict):
            config = AnthropicConfig(**config)
        elif isinstance(config, BaseLLMConfig) and not isinstance(config, AnthropicConfig):
            # Convert BaseLLMConfig to AnthropicConfig
            config = AnthropicConfig(
                model=config.model,
                temperature=config.temperature,
                api_key=config.api_key,
                max_tokens=config.max_tokens,
                top_p=config.top_p,
                top_k=config.top_k,
                enable_vision=config.enable_vision,
                vision_details=config.vision_details,
                http_client_proxies=config.http_client,
            )

        super().__init__(config)

        if not self.config.model:
            self.config.model = "claude-3-5-sonnet-20240620"

        api_key = self.config.api_key or os.getenv("ANTHROPIC_API_KEY")
        auth_token = ""
        if not api_key:
            auth_token = getattr(self.config, "auth_token", None) or os.getenv("ANTHROPIC_AUTH_TOKEN")
        base_url = getattr(self.config, "anthropic_base_url", None) or os.getenv("ANTHROPIC_BASE_URL")
        if auth_token and not base_url:
            raise ValueError(
                "ANTHROPIC_AUTH_TOKEN/LLM_AUTH_TOKEN requires "
                "ANTHROPIC_BASE_URL or ANTHROPIC_LLM_BASE_URL."
            )
        client_kwargs = {"base_url": base_url}
        if auth_token:
            client_kwargs["auth_token"] = auth_token
        else:
            client_kwargs["api_key"] = api_key
        self.client = anthropic.Anthropic(**client_kwargs)
        if not auth_token:
            # The Anthropic SDK also reads ANTHROPIC_AUTH_TOKEN from the process
            # environment. PowerMem gives API keys precedence, so clear any SDK
            # env-derived bearer token when this instance is using an API key.
            self.client.auth_token = None

    def generate_response(
            self,
            messages: List[Dict[str, str]],
            response_format=None,
            tools: Optional[List[Dict]] = None,
            tool_choice: str = "auto",
            **kwargs,
    ):
        """
        Generate a response based on the given messages using Anthropic.

        Args:
            messages (list): List of message dicts containing 'role' and 'content'.
            response_format (str or object, optional): Format of the response. Defaults to "text".
            tools (list, optional): List of tools that the model can call. Defaults to None.
            tool_choice (str, optional): Tool choice method. Defaults to "auto".
            **kwargs: Additional Anthropic-specific parameters.

        Returns:
            str: The generated response.
        """
        # Separate system message from other messages
        system_message = ""
        filtered_messages = []
        for message in messages:
            if message["role"] == "system":
                system_message = message["content"]
            else:
                filtered_messages.append(message)

        params = self._get_supported_params(messages=messages, **kwargs)
        # Anthropic API rejects requests where both temperature and top_p are set.
        # Keep temperature (more common); drop top_p.
        params.pop("top_p", None)
        params.update(
            {
                "model": self.config.model,
                "messages": filtered_messages,
                "system": system_message,
            }
        )

        if tools:  # TODO: Remove tools if no issues found with new memory addition logic
            params["tools"] = tools
            params["tool_choice"] = tool_choice

        response = self.client.messages.create(**params)
        return response.content[0].text
