from fastapi import HTTPException
from pydantic import BaseModel
from typing import Optional
import sys
import os
import time
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 services.openai_service import OpenAIService
from repositories import StorageRepository


class WebhookService:
    def __init__(self, response_manager: ResponseManager, storage_repo: StorageRepository, 
                 bucket: str, openai_service: OpenAIService):
        self.response_manager = response_manager
        self.storage_repo = storage_repo
        self.bucket = bucket
        self.openai_service = openai_service

    def generate_and_upload_audio(self, text: str) -> str:
        """Generate audio from text and upload to MinIO, return filename"""
        try:
            # Generate audio using OpenAI service
            temp_file_path = self.openai_service.generate_speech(text)
            
            # Generate unique filename for MinIO
            timestamp = int(time.time())
            filename = f"tts_response_{timestamp}.mp3"
            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
            self.openai_service.cleanup_temp_file(temp_file_path)
            
            print(f"Successfully generated and uploaded TTS audio: {filename}")
            return filename
            
        except Exception as e:
            print(f"Error generating and uploading 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 using OpenAI service
                audio_filename = self.generate_and_upload_audio(response.agent_response)
                
                # Store response with generated audio filename
                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."}