"""OpenAI Media APIs - Direct OpenAI integration for non-chat capabilities.

OpenRouter handles text/vision, but DALL-E image generation requires direct
OpenAI API access.

This adapter provides image generation using the OpenAI API directly.
The OPENAI_API_KEY is managed by AlbusOS infrastructure.
"""

from __future__ import annotations

import logging
from typing import Any, Literal

import httpx
from pydantic import BaseModel

logger = logging.getLogger(__name__)


class ImageGenerationResult(BaseModel):
    """Result from image generation."""

    images: list[str]
    model: str
    revised_prompt: str | None = None


class OpenAIMediaAdapter:
    """Direct OpenAI API adapter for media capabilities."""

    BASE_URL = "https://api.openai.com/v1"

    def __init__(self, api_key: str | None = None):
        if api_key is None:
            from core.config import get_settings

            api_key = get_settings().openai_api_key
        self.api_key = api_key
        self._client: httpx.AsyncClient | None = None

    def _ensure_client(self) -> httpx.AsyncClient:
        if not self.api_key:
            raise ValueError("OPENAI_API_KEY not configured")

        if self._client is None:
            self._client = httpx.AsyncClient(
                base_url=self.BASE_URL,
                headers={
                    "Authorization": f"Bearer {self.api_key}",
                },
                timeout=300.0,  # Media APIs can be slow
            )
        return self._client

    async def aclose(self) -> None:
        """Close the client connection."""
        if self._client is not None:
            await self._client.aclose()
            self._client = None

    async def generate_image(
        self,
        prompt: str,
        *,
        model: str = "dall-e-3",
        size: Literal["1024x1024", "1792x1024", "1024x1792"] = "1024x1024",
        quality: Literal["standard", "hd"] = "standard",
        style: Literal["vivid", "natural"] = "vivid",
        n: int = 1,
        response_format: Literal["url", "b64_json"] = "b64_json",
    ) -> ImageGenerationResult:
        """Generate images using DALL-E.

        Args:
            prompt: Image description
            model: DALL-E model (dall-e-2 or dall-e-3)
            size: Image dimensions
            quality: Image quality (dall-e-3 only)
            style: Image style (dall-e-3 only)
            n: Number of images (1 for dall-e-3, 1-10 for dall-e-2)
            response_format: Return URLs or base64

        Returns
        -------
            ImageGenerationResult with generated images
        """
        client = self._ensure_client()

        request_data: dict[str, Any] = {
            "model": model,
            "prompt": prompt,
            "size": size,
            "response_format": response_format,
        }

        if model == "dall-e-3":
            request_data["quality"] = quality
            request_data["style"] = style
            request_data["n"] = 1  # DALL-E 3 only supports n=1
        else:
            request_data["n"] = min(n, 10)

        response = await client.post("/images/generations", json=request_data)
        try:
            response.raise_for_status()
        except httpx.HTTPStatusError as e:
            from core.llm.providers import LLMProviderError

            raise LLMProviderError(
                message=f"OpenAI image generation failed ({response.status_code}): {response.text}",
                provider="openai",
                model=model,
                is_transient=response.status_code >= 500,
            ) from e
        result = response.json()

        images = []
        for item in result.get("data", []):
            if response_format == "b64_json":
                images.append(item.get("b64_json", ""))
            else:
                images.append(item.get("url", ""))

        return ImageGenerationResult(
            images=images,
            model=model,
            revised_prompt=result.get("data", [{}])[0].get("revised_prompt"),
        )


# Singleton instance
_adapter: OpenAIMediaAdapter | None = None


def get_openai_media_adapter() -> OpenAIMediaAdapter:
    """Get or create the OpenAI media adapter."""
    global _adapter
    if _adapter is None:
        _adapter = OpenAIMediaAdapter()
    return _adapter


__all__ = [
    "ImageGenerationResult",
    "OpenAIMediaAdapter",
    "get_openai_media_adapter",
]
