from fastapi import UploadFile, HTTPException
from abc import ABC, abstractmethod
import sys
import io
sys.path.append("../")
from repositories import WebhookClient, StorageRepository
from core import MessageType, ResponseStatus
from services import OpenAIService


class MessageHandler(ABC):
    @abstractmethod
    def handle(self, **kwargs) -> dict:
        pass


class AudioMessageHandler():
    def __init__(self, storage_repo: StorageRepository, webhook_client: WebhookClient, 
                 bucket: str, openai_service: OpenAIService):
        self.storage_repo = storage_repo
        self.webhook_client = webhook_client
        self.bucket = bucket
        self.openai_service = openai_service

    def handle(self, file: UploadFile, **kwargs) -> dict:
        try:
            # Read file content
            file.file.seek(0)
            file_content = file.file.read()
            
            if not file_content:
                raise HTTPException(status_code=400, detail="Empty audio file received")
            
            # Upload original file to MinIO for backup
            file_path = f"audio/{file.filename}"
            file_stream = io.BytesIO(file_content)
            self.storage_repo.upload_file(file_stream, self.bucket, file_path)
            print(f"Uploaded {file.filename} to MinIO at {file_path}")
            
            # Try to transcribe the audio using OpenAI service
            try:
                transcribed_text = self.openai_service.transcribe_audio(file_content, file.filename)
                
                # Send transcribed text to n8n
                payload = {
                    "type": MessageType.AUDIO, 
                    "message": transcribed_text,
                }
                
                self.webhook_client.send_webhook(payload)
                print(f"Sent transcribed text to n8n: {transcribed_text[:100]}...")
                
                return {
                    "status": ResponseStatus.SUCCESS, 
                    "message": "Audio transcribed and forwarded to n8n.",
                    "transcription": transcribed_text
                }
                
            except Exception as transcription_error:
                print(f"Transcription failed: {transcription_error}")
                
                # Fallback: send filename to n8n for processing there
                payload = {
                    "type": MessageType.AUDIO, 
                    "filename": file.filename,
                    "message": "تم تسجيل رسالة صوتية - فشل في التفريغ المحلي",
                    "transcription_source": "fallback",
                    "error": str(transcription_error)
                }
                
                self.webhook_client.send_webhook(payload)
                print(f"Sent filename to n8n as fallback: {file.filename}")
                
                return {
                    "status": ResponseStatus.SUCCESS, 
                    "message": "Audio uploaded, transcription failed - sent to n8n for processing.",
                    "filename": file.filename,
                    "transcription_error": str(transcription_error)
                }
            
        except Exception as e:
            print(f"Error processing audio message: {e}")
            raise HTTPException(status_code=500, detail=f"Failed to process audio message: {str(e)}")