# simple_anthropic/core.py
import os
from typing import Optional, Any
from openai import OpenAI


class SimpleAnthropic:
    """
    Simple Anthropic API client using OpenAI SDK compatibility
    """

    def __init__(
            self,
            model: str = "claude-3-sonnet-20240229",
            api_key: Optional[str] = None,
            base_url: str = "https://api.anthropic.com/v1/",
            **default_kwargs: Any
    ):
        # Get API key from environment if not provided
        self.api_key = api_key or os.getenv("ANTHROPIC_API_KEY")
        if not self.api_key:
            raise ValueError("ANTHROPIC_API_KEY environment variable or api_key parameter is required")

        # Initialize OpenAI client with Anthropic endpoint
        self.client = OpenAI(api_key=self.api_key, base_url=base_url)
        self.model = model
        self.default_kwargs = default_kwargs

    def generate_text(
            self,
            prompt: str,
            system: Optional[str] = None,
            **kwargs: Any
    ) -> str:
        """
        Generate text using Anthropic's API

        Args:
            prompt: The user's message
            system: Optional system message
            **kwargs: Additional parameters like temperature, max_tokens etc.

        Returns:
            Generated text as string
        """
        # Prepare messages
        messages = [{"role": "user", "content": prompt}]

        # Merge default and provided parameters
        params = {**self.default_kwargs, **kwargs}

        # Set default max_tokens if not provided
        if "max_tokens" not in params:
            params["max_tokens"] = 1000

        # Add system message if provided
        if system:
            params["system"] = system

        # Make API call
        response = self.client.chat.completions.create(
            model=self.model,
            messages=messages,
            **params
        )

        # Return the text content
        return response.choices[0].message.content or ""


def anthropic_generate(
        prompt: str,
        model: str = "claude-3-sonnet-20240229",
        system: Optional[str] = None,
        api_key: Optional[str] = None,
        **kwargs: Any
) -> str:
    """
    One-line function to generate text with Anthropic

    Args:
        prompt: Your message to Claude
        model: Anthropic model to use
        system: Optional system message
        api_key: Your Anthropic API key (or use ANTHROPIC_API_KEY env var)
        **kwargs: Additional parameters like temperature, max_tokens

    Returns:
        Generated text
    """
    client = SimpleAnthropic(model=model, api_key=api_key)
    return client.generate_text(prompt, system=system, **kwargs)