from fastapi import APIRouter, Form, HTTPException, Request, Depends
from fastapi.responses import FileResponse
from typing import Optional
import logging
import os
from pathlib import Path
import sys
sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), '..')))
from schemas.mcq import MCQListResponse, QuizResponse, QuizSubmission



router = APIRouter(tags=["Quiz & MCQ"])
logger = logging.getLogger("uvicorn.error")



@router.post("/mcq/generate")
async def generate_mcqs_handler(
    request: Request,
    curriculum: str = Form(...),
    grade: str = Form(...),
    subject: str = Form(...),
    unit: str = Form(...),
    concept: str = Form(...),
    count: int = Form(5),
    is_arabic: bool = Form(False),
):
    """
    Generates and stores a new set of MCQs.
    NOTE: This endpoint intentionally returns the FULL question object,
    including curriculum, grade, etc., as it might be useful for the client
    that just initiated the generation. The GET endpoints will be filtered.
    """
    container = request.app.state.container
    try:
        generated_questions = container.mcq_service.generate_and_store_mcqs(
            curriculum=curriculum,
            grade=grade,
            subject=subject,
            unit=unit,
            concept=concept,
            num_questions=count,
            is_arabic=is_arabic,
        )
        return {
            "status": "success",
            "message": f"Successfully generated and stored {len(generated_questions)} MCQs.",
            "questions": generated_questions
        }
    except HTTPException as e:
        raise e
    except Exception as e:
        logger.error(f"Error in generate_mcqs_handler: {e}")
        raise HTTPException(status_code=500, detail=str(e))

# --- STEP 2: UPDATE THE /mcq ENDPOINT SIGNATURE ---
@router.get("/mcq", response_model=MCQListResponse)
async def get_mcqs_handler(
    request: Request,
    curriculum: str,
    grade: str, 
    subject: str,
    unit: str,
    concept: str,
    is_arabic: bool,
    limit: Optional[int] = None 
):
    """
    Retrieves existing MCQs, filtered to the 11-field response model.
    """
    container = request.app.state.container
    try:
        # The service layer still returns the full objects from the DB
        questions_from_db = container.mcq_service.pgvector.get_mcqs(
            curriculum=curriculum,
            grade=grade,
            subject=subject,
            unit=unit,
            concept=concept,
            is_arabic=is_arabic,
            limit=limit
        )
        # FastAPI will automatically filter `questions_from_db` to match the model
        return {
            "status": "success",
            "count": len(questions_from_db),
            "questions": questions_from_db
        }
    except Exception as e:
        logger.error(f"Error in get_mcqs_handler: {e}")
        raise HTTPException(status_code=500, detail=str(e))

# --- STEP 3: UPDATE THE /quiz/dynamic ENDPOINT SIGNATURE ---
@router.post("/quiz/dynamic", response_model=QuizResponse)
async def get_dynamic_quiz_handler(
    request: Request,
    curriculum: str = Form(...),
    grade: str = Form(...), 
    subject: str = Form(...),
    unit: str = Form(...),
    concept: str = Form(...),
    is_arabic: bool = Form(...),
    count: int = Form(5)
):
    """
    Generates a dynamic quiz, filtered to the 11-field response model.
    """
    container = request.app.state.container
    try:
        # The service layer still returns the full objects
        quiz_questions_full = container.mcq_service.get_dynamic_quiz(
            curriculum=curriculum,
            grade=grade,
            subject=subject,
            unit=unit,
            concept=concept,
            is_arabic=is_arabic,
            count=count
        )
        # FastAPI will automatically filter `quiz_questions_full` to match the model
        return {
            "status": "success",
            "message": f"Successfully generated a dynamic quiz with {len(quiz_questions_full)} questions.",
            "quiz": quiz_questions_full
        }
    except HTTPException as e:
        raise e
    except Exception as e:
        logger.error(f"Error in get_dynamic_quiz_handler: {e}")
        raise HTTPException(status_code=500, detail=str(e))


@router.post("/quiz/grade")
async def grade_quiz_handler(submission: QuizSubmission):
    """
    Receives a quiz submission, grades it, and returns the results.
    """
    correct_answers_count = 0
    results = []
    
    # Create a simple lookup map for correct answers from the full question objects
    correct_answer_map = {q['question_text']: q['correct_answer'] for q in submission.questions}
    
    for question_text, user_answer in submission.answers.items():
        correct_answer = correct_answer_map.get(question_text)
        is_correct = (user_answer == correct_answer)
        
        if is_correct:
            correct_answers_count += 1
        
        results.append({
            "question_text": question_text,
            "user_answer": user_answer,
            "correct_answer": correct_answer,
            "is_correct": is_correct
        })
        
    total_questions = len(submission.questions)
    percentage = (correct_answers_count / total_questions) * 100 if total_questions > 0 else 0
    
    return {
        "status": "success",
        "score": correct_answers_count,
        "total_questions": total_questions,
        "percentage": round(percentage, 2),
        "results": results
    }

    
@router.get("/quiz/options/curricula")
async def get_curricula_options(request: Request):
    container = request.app.state.container
    options = container.mcq_service.pgvector.get_distinct_curricula_from_structure()
    return {"options": options}

@router.get("/quiz/options/grades")
async def get_grades_options(request: Request, curriculum: str):
    container = request.app.state.container
    options = container.mcq_service.pgvector.get_distinct_grades_from_structure(curriculum)
    return {"options": options}

@router.get("/quiz/options/subjects")
async def get_subjects_options(request: Request, curriculum: str, grade: str):
    container = request.app.state.container
    options = container.mcq_service.pgvector.get_distinct_subjects_from_structure(curriculum, grade)
    return {"options": options}

@router.get("/quiz/options/units")
async def get_units_options(request: Request, curriculum: str, grade: str, subject: str):
    container = request.app.state.container
    options = container.mcq_service.pgvector.get_distinct_units_from_structure(curriculum, grade, subject)
    return {"options": options}

@router.get("/quiz/options/concepts")
async def get_concepts_options(request: Request, curriculum: str, grade: str, subject: str, unit: str):
    container = request.app.state.container
    options = container.mcq_service.pgvector.get_distinct_concepts_from_structure(curriculum, grade, subject, unit)
    return {"options": options}