from flask import Blueprint, render_template, redirect, url_for, flash, request, jsonify
from flask_login import login_required, current_user
from app import db
from app.models.quiz import TeacherQuiz, TeacherQuestion, QuizAttempt
from app.models.user import User
import json

# Import the student blueprint and the student_required decorator
from app.routes.student import student_bp, student_required

@student_bp.route('/quizzes')
@login_required
@student_required
def quiz_list():
    """List all available teacher-created quizzes"""
    quizzes = TeacherQuiz.query.filter(TeacherQuiz.questions.any()).all()  # Only show quizzes with questions

    # Get attempt information for each quiz
    quiz_attempts = {}
    for quiz in quizzes:
        attempt = QuizAttempt.query.filter_by(
            student_id=current_user.id,
            quiz_id=quiz.id
        ).first()
        quiz_attempts[quiz.id] = attempt

    return render_template('student/quiz/list.html', quizzes=quizzes, quiz_attempts=quiz_attempts)

@student_bp.route('/quiz/<int:quiz_id>')
@login_required
@student_required
def take_quiz(quiz_id):
    """Take a teacher-created quiz"""
    quiz = TeacherQuiz.query.get_or_404(quiz_id)
    questions = quiz.questions

    if not questions:
        flash('This quiz has no questions yet.', 'error')
        return redirect(url_for('student.quiz_list'))

    # Check if student has already attempted this quiz
    existing_attempt = QuizAttempt.query.filter_by(
        student_id=current_user.id,
        quiz_id=quiz_id
    ).first()

    if existing_attempt:
        flash('You have already attempted this quiz.', 'info')
        return redirect(url_for('student.quiz_results', attempt_id=existing_attempt.id))

    return render_template('student/quiz/take.html', quiz=quiz, questions=questions)

@student_bp.route('/quiz/<int:quiz_id>/submit', methods=['POST'])
@login_required
@student_required
def submit_quiz(quiz_id):
    """Submit answers for a teacher-created quiz"""
    quiz = TeacherQuiz.query.get_or_404(quiz_id)

    if not quiz.questions:
        flash('This quiz has no questions.', 'error')
        return redirect(url_for('student.quiz_list'))

    # Check if student has already attempted this quiz
    existing_attempt = QuizAttempt.query.filter_by(
        student_id=current_user.id,
        quiz_id=quiz_id
    ).first()

    if existing_attempt:
        flash('You have already attempted this quiz.', 'info')
        return redirect(url_for('student.quiz_results', attempt_id=existing_attempt.id))

    answers = {}
    score = 0
    total_questions = len(quiz.questions)

    for question in quiz.questions:
        answer_key = f'question_{question.id}'
        student_answer = request.form.get(answer_key, '').strip()

        if question.question_type == 'mcq':
            # For MCQ, check if the selected option matches the correct answer
            if student_answer and student_answer == question.correct_answer:
                score += 1
        elif question.question_type == 'qa':
            # For Q&A, we'll do a simple text match for now
            # In a real app, you might want more sophisticated text matching
            if student_answer.lower() == question.expected_answer.lower():
                score += 1

        answers[question.id] = student_answer

    percentage = (score / total_questions) * 100 if total_questions > 0 else 0

    # Save the quiz attempt to database
    attempt = QuizAttempt(
        student_id=current_user.id,
        quiz_id=quiz_id,
        score=score,
        total_questions=total_questions,
        percentage=percentage,
        answers=json.dumps(answers)
    )
    db.session.add(attempt)
    db.session.commit()

    flash('Quiz submitted successfully!', 'success')
    return redirect(url_for('student.quiz_results', attempt_id=attempt.id))

@student_bp.route('/quiz/results/<int:attempt_id>')
@login_required
def quiz_results(attempt_id):
    """View results of a completed quiz attempt"""
    attempt = QuizAttempt.query.get_or_404(attempt_id)

    # Allow access if user is the student who took the quiz OR any teacher
    quiz = TeacherQuiz.query.get(attempt.quiz_id)  # Query quiz directly
    if not quiz:
        flash('Quiz not found.', 'error')
        return redirect(url_for('student.quiz_list'))
    
    if attempt.student_id != current_user.id and current_user.role != 'teacher':
        flash('Access denied.', 'error')
        return redirect(url_for('student.quiz_list'))

    answers = attempt.get_answers()

    return render_template('student/quiz/results.html',
                         quiz=quiz,
                         attempt=attempt,
                         answers=answers,
                         score=attempt.score,
                         total_questions=attempt.total_questions,
                         percentage=attempt.percentage)