import base64
from fastapi import HTTPException
from fastapi.responses import FileResponse
from starlette.background import BackgroundTask
import sys
import os
sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), '..')))
from core import ResponseStatus
from services.response_manager import ResponseManager
from services.audio_service import AudioService


class ResponseService:
    def __init__(self, response_manager: ResponseManager, audio_service: AudioService):
        self.response_manager = response_manager
        self.audio_service = audio_service

    def get_agent_response(self):
        if not self.response_manager.is_response_fresh():
            raise HTTPException(status_code=404, detail="Agent response not ready or expired.")
        
        response_data = self.response_manager.get_response()
        
        if response_data["audio_file_path"]:
            file_path = response_data["audio_file_path"]
            response_text = response_data["text"]
            self.response_manager.clear_response()
            
            # Encode the text in Base64
            encoded_text = base64.b64encode(response_text.encode('utf-8')).decode('ascii')
            
            return FileResponse(
                path=file_path,
                media_type="audio/mpeg",
                filename="response.mp3",
                background=BackgroundTask(self.audio_service.cleanup_tempfile, file_path),
                headers={"X-Response-Text": encoded_text}
            )
        else:
            response_text = response_data["text"]
            self.response_manager.clear_response()
            
            return {
                "status": ResponseStatus.SUCCESS, 
                "message": "Text response available.", 
                "text": response_text
            }
