"""OpenAI-compatible LLM provider."""
import logging
import os
from typing import Optional, Dict, Any

from .base import BaseLLMProvider

logger = logging.getLogger(__name__)


class OpenAIProvider(BaseLLMProvider):
    """
    OpenAI-compatible LLM provider.

    Status: Requires OpenAI API key
    - Can use OpenAI API or any OpenAI-compatible endpoint
    - Requires: OPENAI_API_KEY environment variable or config
    - If API unavailable: Returns graceful error
    """

    def __init__(
        self,
        api_key: Optional[str] = None,
        base_url: str = "https://api.openai.com/v1",
        model: str = "gpt-4o-mini",
        temperature: float = 0.1,
        max_tokens: int = 500,
        timeout: int = 30,
        retry_attempts: int = 3
    ):
        """Initialize OpenAI provider."""
        super().__init__(name="openai")
        self.api_key = api_key or os.getenv('OPENAI_API_KEY')
        self.base_url = base_url
        self.model = model
        self.temperature = temperature
        self.max_tokens = max_tokens
        self.timeout = timeout
        self.retry_attempts = retry_attempts
        self.client = None
        self._available = False

        self._initialize()

    def _initialize(self) -> None:
        """Initialize OpenAI client."""
        try:
            from openai import OpenAI

            if not self.api_key:
                self.logger.error("OpenAI API key not configured")
                self.logger.error("Set OPENAI_API_KEY environment variable or pass api_key parameter")
                self._available = False
                return

            self.client = OpenAI(
                api_key=self.api_key,
                base_url=self.base_url if self.base_url != "https://api.openai.com/v1" else None,
                timeout=self.timeout
            )

            self.logger.info(f"OpenAI provider initialized: {self.base_url}")

            # Test connection
            if self.test_connection():
                self._available = True
                self.logger.info(f"OpenAI connected, model: {self.model}")
            else:
                self.logger.warning("OpenAI connection test failed")
                self._available = False

        except ImportError:
            self.logger.error("openai package not installed: pip install openai")
            self._available = False
        except Exception as e:
            self.logger.error(f"OpenAI initialization failed: {e}")
            self._available = False

    def complete(self, prompt: str, **kwargs) -> str:
        """
        Get completion from OpenAI API.

        Args:
            prompt: Input prompt
            **kwargs: Override temperature, max_tokens, timeout

        Returns:
            LLM response
        """
        if not self._available or not self.client:
            self.logger.error("OpenAI not available")
            raise RuntimeError("OpenAI provider not initialized")

        temperature = kwargs.get('temperature', self.temperature)
        max_tokens = kwargs.get('max_tokens', self.max_tokens)

        attempt = 0
        while attempt < self.retry_attempts:
            try:
                self.logger.debug(f"OpenAI request: model={self.model}, tokens={max_tokens}")

                response = self.client.chat.completions.create(
                    model=self.model,
                    messages=[{"role": "user", "content": prompt}],
                    temperature=temperature,
                    max_tokens=max_tokens,
                    timeout=self.timeout
                )

                text = response.choices[0].message.content
                self.logger.debug(f"OpenAI response: {len(text)} chars")
                return text

            except Exception as e:
                attempt += 1
                if attempt < self.retry_attempts:
                    self.logger.warning(f"OpenAI request failed ({attempt}/{self.retry_attempts}), retrying: {e}")
                else:
                    self.logger.error(f"OpenAI request failed after {self.retry_attempts} attempts: {e}")
                    raise

    def test_connection(self) -> bool:
        """Test if OpenAI API is accessible."""
        if not self.client or not self.api_key:
            self.logger.warning("OpenAI client not initialized")
            return False

        try:
            # Try a minimal request
            response = self.client.chat.completions.create(
                model=self.model,
                messages=[{"role": "user", "content": "test"}],
                max_tokens=10
            )
            self.logger.info(f"OpenAI test passed")
            return True

        except Exception as e:
            self.logger.error(f"OpenAI connection test failed: {e}")
            return False

    def is_available(self) -> bool:
        """Check if provider is available."""
        return self._available
