# services/response_service.py

import base64
import io
from fastapi import HTTPException
from fastapi.responses import Response, StreamingResponse
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 # Keep for now if used elsewhere


class ResponseService:
    def __init__(self, response_manager: ResponseManager, audio_service: AudioService):
        self.response_manager = response_manager
        self.audio_service = audio_service # Keep for now if used elsewhere

    # --- REWRITTEN and IMPROVED ---
    def get_agent_response(self):
        """
        Gets the agent response from the manager and streams the raw audio bytes
        directly, avoiding temporary files and re-downloading from MinIO.
        """
        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()
        self.response_manager.clear_response() # Clear after getting it

        text_response = response_data.get("text")
        audio_bytes = response_data.get("audio_bytes")

        if not audio_bytes:
            # Handle text-only response if audio failed
            return {
                "status": ResponseStatus.SUCCESS, 
                "message": "Text response available (audio generation failed).", 
                "text": text_response
            }
        
        # Determine content type based on filename extension
        filename = response_data.get("audio_filename", "")
        media_type = "audio/wav" if filename.endswith(".wav") else "audio/mpeg"
        
        # Encode the text in Base64 for the header
        encoded_text = base64.b64encode(text_response.encode('utf-8')).decode('ascii')
        
        # Stream the raw bytes directly
        return Response(
            content=audio_bytes,
            media_type=media_type,
            headers={
                "X-Response-Text": encoded_text,
                "Access-Control-Expose-Headers": "X-Response-Text"
            }
        )