from fastapi import UploadFile, HTTPException
import sys
import os
sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), '..')))
from core import MessageType, ResponseStatus
from repositories import StorageRepository
from services.openai_service import OpenAIService


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

    def handle(self, file: UploadFile, **kwargs) -> dict:
        """Process audio message - transcribe locally using OpenAI Whisper"""
        try:
            print(f"Processing audio file: {file.filename}")
            
            # Read file content
            file_content = file.file.read()
            
            if not self.openai_service.is_available():
                raise HTTPException(status_code=500, detail="OpenAI service not available for transcription")
            
            # Transcribe using OpenAI Whisper
            try:
                transcribed_text = self.openai_service.transcribe_audio(file_content, file.filename)
                print(f"Transcription successful: {transcribed_text}")
                
                return {
                    "status": ResponseStatus.SUCCESS,
                    "message": "Audio transcribed successfully",
                    "transcription": transcribed_text,
                    "message_type": MessageType.AUDIO
                }
                
            except Exception as transcription_error:
                print(f"Local transcription failed: {transcription_error}")
                raise HTTPException(status_code=500, detail=f"Transcription failed: {str(transcription_error)}")
                
        except HTTPException:
            # Re-raise HTTP exceptions
            raise
        except Exception as e:
            print(f"Error processing audio message: {e}")
            raise HTTPException(status_code=500, detail=f"Failed to process audio: {str(e)}")
        finally:
            # Reset file pointer for potential reuse
            file.file.seek(0)