from typing import Dict, Any, Optional
import httpx
import logging
import json

from src.services.provider.base import BaseImageService, ServiceResponse, TaskStatus, GenerationResult
from src.config.settings import OPENAI_BASE_URL

logger = logging.getLogger(__name__)

class OpenAIImageService(BaseImageService):
    def __init__(self, model_name: str = "dall-e-3", api_key: Optional[str] = None, **kwargs):
        super().__init__(model_name, api_key=api_key, **kwargs)
        if not self.api_key:
            # Fallback for standalone usage
            import os
            self.api_key = os.environ.get("OPENAI_API_KEY")

        if not self.api_key:
            logger.warning("API Key is not set. OpenAI image generation will fail.")

    async def generate(self, prompt: str, **kwargs) -> ServiceResponse:
        """Generate image using OpenAI DALL-E 3."""
        api_key = self.api_key
        base_url = OPENAI_BASE_URL or "https://api.openai.com/v1"
        url = f"{base_url}/images/generations"

        headers = {
            "Content-Type": "application/json",
            "Authorization": f"Bearer {api_key}"
        }

        payload = {
            "model": self.model_name,
            "prompt": prompt,
            "n": kwargs.get("n", 1),
            "size": kwargs.get("size", "1024x1024"),
            "quality": kwargs.get("quality", "standard"),
            "style": kwargs.get("style", "vivid"),
            "response_format": "url"
        }

        try:
            async with httpx.AsyncClient(timeout=120.0) as client:
                response = await client.post(url, headers=headers, json=payload)
                response.raise_for_status()

            data = response.json()

            result_data = data.get("data", [])
            if not result_data:
                raise ValueError("No image data returned from OpenAI")

            results = []
            for item in result_data:
                results.append(GenerationResult(
                    url=item.get("url"),
                    actual_prompt=item.get("revised_prompt")
                ))

            return ServiceResponse(
                task_id=f"openai-img-{data.get('created')}",
                status=TaskStatus.SUCCEEDED,
                results=results,
                output={
                    "provider_response": data
                }
            )

        except Exception as e:
            logger.error(f"OpenAI Image Generation Failed: {str(e)}")
            return ServiceResponse(
                task_id="failed",
                status=TaskStatus.FAILED,
                error=str(e)
            )

    async def check_status(self, task_id: str) -> ServiceResponse:
        """OpenAI DALL-E 3 generation is synchronous; status checking is not applicable."""
        return ServiceResponse(
            status=TaskStatus.UNKNOWN,
            task_id=task_id,
            error="OpenAI image generation is synchronous; status checking is not applicable."
        )
