"""Minimal OpenAI client using httpx.

We intentionally avoid adding a hard dependency on the official OpenAI SDK.
"""

from __future__ import annotations

import httpx
from typing import Any, Dict, List, Optional

OPENAI_CHAT_URL = "https://api.openai.com/v1/chat/completions"


class OpenAIClient:
    def __init__(self, api_key: str, model: str = "gpt-4o-mini", timeout: float = 60.0):
        if not api_key:
            raise ValueError("OpenAI API key is required")
        self.api_key = api_key
        self.model = model
        self.timeout = timeout

    def chat(self, messages: List[Dict[str, str]], temperature: float = 0.7, max_tokens: int = 1200) -> str:
        headers = {
            "Authorization": f"Bearer {self.api_key}",
            "Content-Type": "application/json",
        }
        payload: Dict[str, Any] = {
            "model": self.model,
            "messages": messages,
            "temperature": temperature,
            "max_tokens": max_tokens,
        }

        with httpx.Client(timeout=self.timeout) as client:
            r = client.post(OPENAI_CHAT_URL, headers=headers, json=payload)
            r.raise_for_status()
            data = r.json()

        # Compatible with Chat Completions response
        return data["choices"][0]["message"]["content"]
