from __future__ import annotations
from typing import Iterable
import os

try:
    from openai import OpenAI  # type: ignore
except Exception:  # pragma: no cover - optional dependency
    OpenAI = None  # type: ignore

from .base import LLMRequest, LLMResponse
from ..config import settings

class OpenAIProvider:
    def __init__(self):
        self.api_key = settings.openai_api_key or os.getenv("OPENAI_API_KEY")
        if OpenAI and self.api_key:
            self.client = OpenAI(api_key=self.api_key)
        else:
            self.client = None

    def complete(self, req: LLMRequest) -> LLMResponse:
        if not self.client:
            return LLMResponse(text="")
        try:
            resp = self.client.chat.completions.create(
                model=req.model or settings.llm_model or "gpt-5-2025-08-07",
                messages=[{"role": "user", "content": req.prompt}],
                temperature=req.temperature,
            )
            text = resp.choices[0].message.content or ""
            return LLMResponse(text=text.strip())
        except Exception:
            return LLMResponse(text="")

    def stream(self, req: LLMRequest) -> Iterable[str]:
        if not self.client:
            yield ""
            return
        try:
            stream = self.client.chat.completions.create(
                model=req.model or settings.llm_model or "gpt-5-2025-08-07",
                messages=[{"role": "user", "content": req.prompt}],
                temperature=req.temperature,
                stream=True,
            )
            for part in stream:
                delta = part.choices[0].delta.content
                if delta:
                    yield delta
        except Exception:
            return
