from fastapi import HTTPException
from pydantic import BaseModel
from typing import Optional
from enum import Enum
import sys
import os
import time
import tempfile
from openai import OpenAI
sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), '..')))
from core import ResponseStatus
from schemas import WebhookResponse
from services.response_manager import ResponseManager
from repositories import StorageRepository

class WebhookService:
    def __init__(self, response_manager: ResponseManager, storage_repo: StorageRepository, bucket: str):
        self.response_manager = response_manager
        self.storage_repo = storage_repo
        self.bucket = bucket
        
        # Initialize OpenAI client
        openai_api_key = os.getenv("OPENAI_API_KEY")
        if not openai_api_key:
            print("Warning: OPENAI_API_KEY not found. TTS functionality will be disabled.")
            self.openai_client = None
        else:
            self.openai_client = OpenAI(api_key=openai_api_key)

    def generate_audio_from_text(self, text: str) -> str:
        """Generate audio from text using OpenAI TTS and upload to MinIO"""
        if not self.openai_client:
            raise HTTPException(status_code=500, detail="OpenAI API key not configured")
            
        try:
            # Create temporary file for audio
            temp_file = tempfile.NamedTemporaryFile(delete=False, suffix=".mp3")
            temp_file_path = temp_file.name
            temp_file.close()
            
            print(f"Generating TTS audio for text: {text[:50]}...")
            
            # Generate audio using OpenAI TTS
            with self.openai_client.audio.speech.with_streaming_response.create(
                model="gpt-4o-mini-tts",  
                voice="alloy",  # Available voices: alloy, echo, fable, onyx, nova, shimmer
                input=text,
                response_format="mp3"
            ) as response:
                response.stream_to_file(temp_file_path)
            
            # Generate unique filename for MinIO 
            timestamp = int(time.time())
            filename = f"tts_response_{timestamp}.mp3"
            # The full path in MinIO will be audio/filename
            minio_file_path = f"audio/{filename}"
            
            print(f"Uploading generated audio to MinIO: {minio_file_path}")
            
            # Upload to MinIO
            with open(temp_file_path, 'rb') as audio_file:
                self.storage_repo.upload_file(audio_file, self.bucket, minio_file_path)
            
            # Clean up temporary file
            if os.path.exists(temp_file_path):
                os.unlink(temp_file_path)
                print(f"Cleaned up temporary file: {temp_file_path}")
            
            print(f"Successfully generated and uploaded TTS audio: {filename}")
            # Return just the filename, the audio service will add the audio/ prefix
            return filename
            
        except Exception as e:
            # Clean up temporary file in case of error
            if 'temp_file_path' in locals() and os.path.exists(temp_file_path):
                os.unlink(temp_file_path)
            
            print(f"Error generating TTS audio: {e}")
            raise HTTPException(status_code=500, detail=f"Failed to generate audio: {str(e)}")

    def process_webhook_response(self, response: WebhookResponse) -> dict:
        """Process webhook response from n8n and generate TTS audio"""
        print("Received webhook data from n8n:", response.dict())
        
        if response.agent_responded == 'yes' and response.agent_response:
            try:
                # Generate audio from the text response
                audio_filename = self.generate_audio_from_text(response.agent_response)
                
                # Store response with generated audio filename (just the filename, not the path)
                self.response_manager.store_response(response.agent_response, audio_filename)
                print("Agent response with generated TTS audio stored successfully.")
                
            except HTTPException:
                # Re-raise HTTP exceptions
                raise
            except Exception as e:
                print(f"Error generating TTS audio, storing text-only response: {e}")
                # Fallback to text-only response if audio generation fails
                self.response_manager.store_response(response.agent_response)
                print("Stored text-only response as fallback.")
        else:
            print("No valid agent response received from webhook.")
        
        return {"status": ResponseStatus.SUCCESS, "message": "Webhook received and processed successfully."}