"""OpenAI API provider."""

from __future__ import annotations

from typing import Any

from openai import OpenAI

from ..utils.logger import Logger
from .base_provider import BaseProvider


class OpenAIProvider(BaseProvider):
    """Provider using OpenAI API."""

    name = "OpenAI"
    type = "api"

    def __init__(self, api_key: str, model: str = "gpt-4o") -> None:
        self.api_key = api_key
        self.model = model
        self.client = OpenAI(api_key=api_key)

    def test_connection(self) -> bool:
        """Test API connection."""
        try:
            # Make a simple models list call
            self.client.models.list()
            return True
        except Exception as e:
            Logger.error("OpenAI connection test failed", e)
            return False

    def execute(self, skill_content: str, user_input: str, context: dict[str, Any]) -> str:
        """Execute task using OpenAI API."""
        system_prompt = self._build_system_prompt(skill_content, context)

        Logger.info("Executing with OpenAI", {"model": self.model, "input": user_input[:100]})

        try:
            response = self.client.chat.completions.create(
                model=self.model,
                messages=[
                    {"role": "system", "content": system_prompt},
                    {"role": "user", "content": user_input},
                ],
                temperature=0.7,
                max_tokens=4000,
            )

            return response.choices[0].message.content or ""

        except Exception as e:
            Logger.error("OpenAI execution failed", e)
            raise RuntimeError(f"OpenAI API error: {e}")

    def _build_system_prompt(self, skill_content: str, context: dict[str, Any]) -> str:
        """Build system prompt."""
        prompt = (
            "You are a marketing assistant for Reply Cash, "
            "a stablecoin-to-mobile-money payment platform."
        )

        if skill_content:
            prompt += f"\n\n{skill_content}"

        skill = context.get("skill")
        if skill:
            prompt += f"\n\nCurrent task: Use the {skill} skill to help the user."

        prompt += """

Guidelines:
- Be concise and actionable
- Focus on Reply Cash's value proposition
- Always suggest next steps
- If creating content, mention you'll submit it for approval"""

        return prompt

    def get_model(self) -> str:
        """Get model name."""
        return self.model
