import os
import httpx
import logging
import uuid
from typing import Dict, Any, Optional

from src.services.provider.base import BaseAudioService, ServiceResponse, TaskStatus, GenerationResult
from src.services.storage_service import storage_manager
from src.config.settings import OPENAI_BASE_URL

logger = logging.getLogger(__name__)


class OpenAIAudioService(BaseAudioService):
    """
    OpenAI TTS service.
    Voice names are natively OpenAI format — no mapping needed.
    Supported voices: alloy, echo, fable, onyx, nova, shimmer
    """
    def __init__(self, model_name: str = "tts-1", api_key: Optional[str] = None, **kwargs):
        super().__init__(model_name, api_key=api_key, **kwargs)
        if not self.api_key:
            logger.warning("API Key is not set. OpenAI audio generation will fail.")

    async def generate(self, text: str, voice: str = "alloy", **kwargs) -> ServiceResponse:
        """Generate audio using OpenAI TTS."""
        api_key = self.api_key
        base_url = OPENAI_BASE_URL or "https://api.openai.com/v1"
        url = f"{base_url}/audio/speech"

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

        response_format = kwargs.get("response_format", "mp3")

        payload = {
            "model": self.model_name,
            "input": text,
            "voice": voice or "alloy",
            "response_format": response_format,
            "speed": kwargs.get("speed", 1.0)
        }

        try:
            logger.info(f"OpenAI TTS request: model={self.model_name}, voice={voice}, text_len={len(text)}")
            async with httpx.AsyncClient(timeout=120.0) as client:
                response = await client.post(url, headers=headers, json=payload)
                response.raise_for_status()

                audio_data = response.content

            # Save via storage_manager for unified path handling
            task_id = f"openai-tts-{uuid.uuid4()}"
            file_name = f"{uuid.uuid4()}.{response_format}"
            storage_path = f"generations/audio/{task_id}/{file_name}"

            saved_url = storage_manager.save(storage_path, audio_data)

            return ServiceResponse(
                task_id=task_id,
                status=TaskStatus.SUCCEEDED,
                results=[GenerationResult(url=saved_url)]
            )

        except Exception as e:
            logger.error(f"OpenAI TTS Failed: {str(e)}")
            raise RuntimeError(f"OpenAI TTS Service Error: {str(e)}")
