from fastapi import APIRouter, UploadFile, File, Form, HTTPException, Depends, Response
from typing import Optional
from starlette.requests import Request


router = APIRouter(tags=["Chat"])

@router.post("/chat")
async def chat_handler(
    request: Request,
    file: Optional[UploadFile] = File(None), 
    text: Optional[str] = Form(None),
    student_id: str = Form("student_001"),
    game_context: Optional[str] = Form(None) 
):
    """Handles incoming chat messages using the shared container instance."""
    container = request.app.state.container
    try:
        if not student_id.strip():
            raise HTTPException(status_code=400, detail="Student ID is required")
        
        result = container.chat_service.process_message(
            student_id=student_id, 
            file=file, 
            text=text,
            game_context=game_context
        )
        return result
    except Exception as e:
        print(f"Error in chat handler: {str(e)}")
        raise HTTPException(status_code=500, detail=f"Chat processing error: {str(e)}")

@router.get("/get-audio-response")
async def get_audio_response(request: Request, student_id: str = "student_001"):
    """Fetches the agent's text and audio response using the shared container."""
    container = request.app.state.container
    try:
        result = container.response_service.get_agent_response(student_id=student_id)
        if hasattr(result, 'status_code'):
            return result
        # This should be unreachable if response_service always returns a Response object
        return result
    except Exception as e:
        print(f"Error getting audio response: {str(e)}")
        raise HTTPException(status_code=500, detail=f"Audio response error: {str(e)}")
    

@router.options("/get-audio-response")
async def audio_response_options():
    """Handle preflight CORS requests for audio response endpoint"""
    return Response(status_code=204, headers={"Access-Control-Allow-Origin": "*", "Access-Control-Allow-Methods": "GET, OPTIONS", "Access-Control-Allow-Headers": "*", "Access-Control-Expose-Headers": "X-Response-Text"})
