# 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
import json
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

    def get_agent_response(self, student_id: str):
        """
        Gets the agent response from the manager and streams the audio.
        It intelligently handles both text and structured MCQ data by encoding
        the payload in the 'X-Response-Text' header and signaling the type
        in the 'X-Response-Type' header.
        """
        if not self.response_manager.is_response_fresh(student_id):
            raise HTTPException(status_code=404, detail="Agent response not ready or expired.")

        response_data = self.response_manager.get_response(student_id)
        
        payload_data = response_data.get("text") # This can be a string or a dict
        audio_bytes = response_data.get("audio_bytes")

        if not payload_data or not audio_bytes:
            raise HTTPException(status_code=404, detail=f"Response for {student_id} was incomplete, claimed, or expired.")
        
        response_type = "text"
        encoded_text = ""

        # Check the type of the payload to decide how to encode it
        if isinstance(payload_data, dict):
            # It's an MCQ
            response_type = "mcq"
            # Serialize the dictionary to a JSON string
            json_string = json.dumps(payload_data, ensure_ascii=False)
            # Base64-encode the JSON string
            encoded_text = base64.b64encode(json_string.encode('utf-8')).decode('ascii')
        else:
            # It's a normal text string
            response_type = "text"
            # Base64-encode the string directly
            encoded_text = base64.b64encode(str(payload_data).encode('utf-8')).decode('ascii')
        
        # Stream the raw audio bytes
        return Response(
            content=audio_bytes,
            media_type="audio/wav",
            headers={
                "X-Response-Type": response_type, # Signal the payload type
                "X-Response-Text": encoded_text,
                "Access-Control-Expose-Headers": "X-Response-Text, X-Response-Type" # Expose the new header
            }
        )