import os
import time
import tempfile
import io
from typing import Optional
from fastapi import HTTPException
from openai import OpenAI


class OpenAIService:
    """Service class for handling OpenAI API operations (TTS and Whisper)"""
    
    def __init__(self):
        self.api_key = os.getenv("OPENAI_API_KEY")
        if not self.api_key:
            print("Warning: OPENAI_API_KEY not found. OpenAI services will be disabled.")
            self.client = None
        else:
            self.client = OpenAI(api_key=self.api_key)
    
    def is_available(self) -> bool:
        """Check if OpenAI service is available"""
        return self.client is not None
    
    def transcribe_audio(self, file_content: bytes, filename: str, language: Optional[str] = "ar") -> str:
        """
        Transcribe audio using OpenAI Whisper
        
        Args:
            file_content: Audio file content as bytes
            filename: Original filename for context
            language: Language code (optional, defaults to Arabic)
        
        Returns:
            Transcribed text
        
        Raises:
            HTTPException: If transcription fails or service unavailable
        """
        if not self.is_available():
            raise HTTPException(status_code=500, detail="OpenAI service not available")
        
        try:
            # Create file-like object for the API
            audio_file = io.BytesIO(file_content)
            audio_file.name = filename
            
            print(f"Transcribing audio: {filename}")
            
            # Call Whisper API
            transcript = self.client.audio.transcriptions.create(
                model="whisper-1",
                file=audio_file,
                language=language if language else None  # Auto-detect if None
            )
            
            transcribed_text = transcript.text.strip()
            
            if not transcribed_text:
                raise ValueError("Empty transcription result")
            
            print(f"Transcription successful: {transcribed_text[:100]}...")
            return transcribed_text
            
        except Exception as e:
            print(f"Error during transcription: {e}")
            raise HTTPException(status_code=500, detail=f"Transcription failed: {str(e)}")
    
    def generate_speech(self, text: str, voice: str = "alloy", model: str = "tts-1") -> str:
        """
        Generate speech from text using OpenAI TTS
        
        Args:
            text: Text to convert to speech
            voice: Voice to use (alloy, echo, fable, onyx, nova, shimmer)
            model: TTS model to use (tts-1 or tts-1-hd)
        
        Returns:
            Path to temporary file containing the generated audio
        
        Raises:
            HTTPException: If TTS generation fails or service unavailable
        """
        if not self.is_available():
            raise HTTPException(status_code=500, detail="OpenAI service not available")
        
        temp_file_path = None
        try:
            # Create temporary file
            temp_file = tempfile.NamedTemporaryFile(delete=False, suffix=".mp3")
            temp_file_path = temp_file.name
            temp_file.close()
            
            print(f"Generating TTS audio: {text[:50]}...")
            
            # Generate audio using OpenAI TTS
            with self.client.audio.speech.with_streaming_response.create(
                model=model,
                voice=voice,
                input=text,
                response_format="mp3"
            ) as response:
                response.stream_to_file(temp_file_path)
            
            print(f"TTS generation successful, saved to: {temp_file_path}")
            return temp_file_path
            
        except Exception as e:
            # Clean up temp file on error
            if temp_file_path and os.path.exists(temp_file_path):
                os.unlink(temp_file_path)
            
            print(f"Error during TTS generation: {e}")
            raise HTTPException(status_code=500, detail=f"TTS generation failed: {str(e)}")
    
    def cleanup_temp_file(self, file_path: str) -> None:
        """Clean up temporary file"""
        if file_path and os.path.exists(file_path):
            try:
                os.unlink(file_path)
                print(f"Cleaned up temporary file: {file_path}")
            except Exception as e:
                print(f"Warning: Could not clean up temp file {file_path}: {e}")