from flask import render_template, redirect, url_for, flash, request, jsonify
from app import db
from app.models.user import User
from app.models.topic import Topic
from app.models.progress import Progress
from app.forms.teacher import AddStudentForm
from app.routes.teacher import bp
from app.utils.decorators import teacher_required
from flask_login import login_required, current_user
from app.services.email_service import send_approval_email, send_rejection_email

@bp.route('/students/add', methods=['GET', 'POST'])
@login_required
@teacher_required
def add_student():
    form = AddStudentForm()
    if form.validate_on_submit():
        student = User(
            username=form.student_name.data,
            email=form.email.data,
            role='student',
            roll_number=form.roll_number.data,
            department=form.department.data,
            program=form.program.data,
            semester=form.semester.data,
            section=form.section.data,
            phone_number=form.phone_number.data,
            teacher_id=current_user.id,
            is_approved=True  # Auto-approve when teacher adds student
        )
        student.set_password(form.password.data)
        db.session.add(student)
        try:
            db.session.commit()
            flash('Student has been added successfully!', 'success')
            return redirect(url_for('teacher.manage_students'))
        except Exception as e:
            db.session.rollback()
            if 'UNIQUE constraint' in str(e):
                flash('A student with this email or roll number already exists.', 'error')
            else:
                flash('An error occurred while adding the student. Please try again.', 'error')
    
    return render_template('teacher/add_student.html', form=form)

@bp.route('/students/manage')
@login_required
@teacher_required
def manage_students():
    students = User.query.filter_by(teacher_id=current_user.id, role='student').all()
    
    # Calculate progress for each student
    for student in students:
        # Get all progress entries for the student
        progress_entries = Progress.query.filter_by(student_id=student.id).all()
        
        # Calculate reading, speaking, and writing progress
        total_topics = Topic.query.count()
        if total_topics > 0:
            # Reading progress
            reading_completed = sum(1 for p in progress_entries if p.reading_completed)
            student.reading_progress = round((reading_completed / total_topics) * 100)
            
            # Speaking progress (renamed from writing_progress for consistency)
            speaking_completed = sum(1 for p in progress_entries if p.speaking_completed)
            student.speaking_progress = round((speaking_completed / total_topics) * 100)
            
            # Comprehension progress (added as writing_progress in template)
            comprehension_completed = sum(1 for p in progress_entries if p.comprehension_completed)
            student.writing_progress = round((comprehension_completed / total_topics) * 100)
        else:
            student.reading_progress = 0
            student.speaking_progress = 0
            student.writing_progress = 0
    
    return render_template('teacher/manage_students.html', students=students)

@bp.route('/students/<int:student_id>/approve', methods=['POST'])
@login_required
@teacher_required
def approve_student(student_id):
    student = User.query.filter_by(id=student_id, role='student').first_or_404()
    
    # Only allow approving students with no teacher assigned
    if student.teacher_id is not None:
        flash('This student is already assigned to a teacher.', 'error')
        return redirect(url_for('teacher.dashboard'))
    
    student.teacher_id = current_user.id
    student.is_approved = True
    db.session.commit()
    
    # Send approval email
    try:
        send_approval_email(student)
        flash('Student has been approved and notified via email.', 'success')
    except Exception as e:
        flash('Student approved but email notification failed.', 'warning')
    
    return redirect(url_for('teacher.dashboard'))

@bp.route('/students/<int:student_id>/reject', methods=['POST'])
@login_required
@teacher_required
def reject_student(student_id):
    student = User.query.filter_by(id=student_id, role='student').first_or_404()
    
    # Only allow rejecting students with no teacher assigned
    if student.teacher_id is not None:
        flash('This student is already assigned to a teacher.', 'error')
        return redirect(url_for('teacher.dashboard'))
    
    # Send rejection email before deleting
    try:
        send_rejection_email(student)
    except Exception as e:
        flash('Could not send rejection notification email.', 'warning')
    
    db.session.delete(student)
    db.session.commit()
    flash('Student application has been rejected.', 'success')
    
    return redirect(url_for('teacher.dashboard'))
    
@bp.route('/students/<int:student_id>/remove', methods=['POST'])
@login_required
@teacher_required
def remove_student(student_id):
    student = User.query.filter_by(id=student_id, role='student').first_or_404()
    
    # Check if the student belongs to the current teacher
    if student.teacher_id != current_user.id:
        return jsonify({'success': False, 'message': 'You are not authorized to remove this student'}), 403
    
    try:
        # Delete student progress records first to avoid constraint issues
        Progress.query.filter_by(student_id=student.id).delete()
        
        # Delete student
        db.session.delete(student)
        db.session.commit()
        
        return jsonify({'success': True, 'message': 'Student removed successfully'})
    except Exception as e:
        db.session.rollback()
        return jsonify({'success': False, 'message': f'An error occurred: {str(e)}'}), 500