
from exams.models import ModelQuestion, DataQualityIssue

def generate_ai_answer(question_text, medium="EN"):
    """
    Generates a short, exam-focused answer. 
    In production, this calls the Gemini/OpenAI API.
    For now, it returns a structured placeholder and queues for teacher review.
    """
    prompt = f"Provide a short, exam-focused answer for: {question_text} in {medium}. Max 5 sentences."
    
    # Simulated AI response
    simulated_answer = f"[AI Generated Draft] The answer to '{question_text[:30]}...' focuses on the core concepts. (Pending Teacher Review)."
    return simulated_answer

def queue_for_teacher_review(question, generated_answer):
    """
    Human-in-the-Loop Gate: We do not show AI answers directly to students.
    We save them and create a DataQualityIssue for the teacher to approve.
    """
    # Save draft to the question
    question.model_answer = generated_answer
    question.needs_teacher_review = True
    question.save(update_fields=['model_answer', 'needs_teacher_review'])
    
    # Create a task for the teacher
    DataQualityIssue.objects.get_or_create(
        entity_type="ModelQuestion",
        entity_id=question.id,
        defect_class="MISSING",
        defaults={
            'severity': 'MINOR',
            'evidence': {'ai_draft': generated_answer},
            'status': 'TASK_ASSIGNED'
        }
    )
