import os
import time
import tempfile
import io
from typing import Optional, List
from fastapi import HTTPException
from openai import OpenAI
import sys
sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), '..')))
from core import Models


class OpenAIService:
    """Service class for handling OpenAI API operations (TTS, Whisper, Embeddings)"""
    
    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
    
    # ------------------- Whisper -------------------
    def transcribe_audio(self, file_content: bytes, filename: str, language: Optional[str] = "ar") -> str:
        """Transcribe audio using OpenAI Whisper"""
        if not self.is_available():
            raise HTTPException(status_code=500, detail="OpenAI service not available")
        
        try:
            audio_file = io.BytesIO(file_content)
            audio_file.name = filename
            print(f"Transcribing audio: {filename}")
            
            transcript = self.client.audio.transcriptions.create(
                model=Models.transcription.value,
                file=audio_file,
                language=language if language else 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)}")
    
    # ------------------- TTS -------------------
    def generate_speech(self, text: str, voice: str = "alloy") -> str:
        """Generate speech from text using OpenAI TTS"""
        if not self.is_available():
            raise HTTPException(status_code=500, detail="OpenAI service not available")
        
        temp_file_path = None
        try:
            temp_file = tempfile.NamedTemporaryFile(delete=False, suffix=".mp3")
            temp_file_path = temp_file.name
            temp_file.close()
            
            print(f"Generating TTS audio: {text[:50]}...")
            
            with self.client.audio.speech.with_streaming_response.create(
                model=Models.tts,
                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:
            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)}")
    
    # ------------------- Embeddings -------------------
    def generate_embedding(self, text: str) -> List[float]:
        """
        Generate an embedding vector for input text.
        
        Args:
            text: Input string
            model: Embedding model (default: text-embedding-3-small)
        
        Returns:
            List[float]: Embedding vector
        """
        if not self.is_available():
            raise HTTPException(status_code=500, detail="OpenAI service not available")
        
        try:
            response = self.client.embeddings.create(
                model=Models.embedding,
                input=text
            )
            embedding = response.data[0].embedding
            if not embedding:
                raise ValueError("Empty embedding generated")
            
            return embedding
        except Exception as e:
            print(f"Error during embedding generation: {e}")
            raise HTTPException(status_code=500, detail=f"Embedding generation failed: {str(e)}")
    
    # ------------------- Utils -------------------
    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}")
