from __future__ import annotations

from temporal.core.models import LLMResponse


class OpenAIClient:
    """LLM client backed by the OpenAI Responses API.

    Requires the ``openai`` optional dependency::

        pip install temporal[openai]
    """

    def __init__(
        self,
        api_key: str | None = None,
        model: str = "gpt-4.1-mini",
    ) -> None:
        try:
            from openai import AsyncOpenAI
        except ImportError:
            raise ImportError(
                "The openai package is required for OpenAIClient. "
                "Install it with: pip install temporal[openai]"
            ) from None

        self._client = AsyncOpenAI(api_key=api_key)
        self.default_model = model

    async def complete(
        self,
        prompt: str,
        model: str | None = None,
        max_tokens: int = 4096,
    ) -> LLMResponse:
        response = await self._client.responses.create(
            model=model or self.default_model,
            input=[{"role": "user", "content": prompt}],
            max_output_tokens=max_tokens,
        )
        usage = getattr(response, "usage", None)
        return LLMResponse(
            text=response.output_text.strip() if response.output_text else "",
            input_tokens=getattr(usage, "input_tokens", 0) or 0,
            output_tokens=getattr(usage, "output_tokens", 0) or 0,
        )
