from fastapi import APIRouter, UploadFile, File, Form, Request, Response
import base64

router = APIRouter(tags=["Reasoning Mode"])

@router.post("/reasoning/upload")
async def upload_reasoning_csv(
    request: Request, 
    grade: int = Form(...), 
    file: UploadFile = File(...)
):
    content = await file.read()
    success = request.app.state.container.reasoning_service.bulk_upload_questions(content, grade)
    return {"status": "success" if success else "error"}

@router.post("/reasoning/ask")
async def ask_reasoning(request: Request, student_id: str = Form(...)):
    container = request.app.state.container
    text, audio_bytes = container.reasoning_service.get_atom_challenge(student_id)
    
    encoded_text = base64.b64encode(text.encode('utf-8')).decode('utf-8')
    return Response(
        content=audio_bytes,
        media_type="audio/wav",
        headers={
            "X-Response-Text": encoded_text, 
            "X-Response-Type": "reasoning_ask",
            "Access-Control-Expose-Headers": "X-Response-Text, X-Response-Type" # Add this!
        }
    )
@router.post("/reasoning/evaluate")
async def evaluate_reasoning(
    request: Request, 
    student_id: str = Form(...), 
    file: UploadFile = File(...)
):
    container = request.app.state.container
    audio_content = await file.read()
    filename = file.filename  # نحصل على الاسم الأصلي مثل answer.webm
    
    feedback, audio_bytes, student_said = container.reasoning_service.evaluate_student_answer(
        student_id, audio_content, filename
    )
    
    encoded_feedback = base64.b64encode(feedback.encode('utf-8')).decode('utf-8')
    encoded_said = base64.b64encode(student_said.encode('utf-8')).decode('utf-8')
    
    return Response(
        content=audio_bytes,
        media_type="audio/wav",
        headers={
            "X-Response-Text": encoded_feedback,
            "X-Student-Said": encoded_said,
            "X-Response-Type": "reasoning_eval",
            "Access-Control-Expose-Headers": "X-Response-Text, X-Student-Said, X-Response-Type"
        }
    )