"""OpenAI API provider for ShelfAI."""

from shelfai.providers import LLMProvider


class OpenAIProvider(LLMProvider):
    """
    LLM provider using the OpenAI Chat Completions API.

    Also works with OpenAI-compatible APIs (Together, Groq, etc.)
    by setting a custom base_url.

    Requires: pip install shelfai[openai]
    """

    def __init__(
        self,
        model: str = "gpt-4o",
        api_key: str = None,
        base_url: str = None,
    ):
        """
        Initialize the OpenAI provider.

        Args:
            model: Model name (default: gpt-4o)
            api_key: API key. If None, uses OPENAI_API_KEY env var.
            base_url: Optional custom base URL for compatible APIs.
        """
        try:
            import openai
        except ImportError:
            raise ImportError(
                "OpenAI SDK not installed. Run: pip install shelfai[openai]"
            )

        kwargs = {}
        if api_key:
            kwargs["api_key"] = api_key
        if base_url:
            kwargs["base_url"] = base_url

        self.client = openai.OpenAI(**kwargs)
        self.model = model

        # Fix #33: Declare retryable errors for the retry logic
        self.retryable_errors = (
            openai.RateLimitError,
            openai.InternalServerError,
            openai.APIConnectionError,
        )

    def complete(self, system: str, user: str, max_tokens: int = 4096) -> str:
        """Send a completion request to the OpenAI API."""
        response = self.client.chat.completions.create(
            model=self.model,
            max_tokens=max_tokens,
            messages=[
                {"role": "system", "content": system},
                {"role": "user", "content": user},
            ],
        )
        return response.choices[0].message.content
