from flask import render_template, redirect, url_for, flash, request, jsonify
from app import db
from app.models.course import ShortCourse, LearningCourse
from app.models.topic import Topic
from app.forms.teacher import CourseOutlineForm
from flask_login import login_required, current_user
from app.routes.teacher import bp
from sqlalchemy import and_, or_

@bp.route('/courses/<course_type>/<int:course_id>/outline/add', methods=['GET', 'POST'])
@login_required
def add_course_outline(course_type, course_id):
    """Add a new outline to a course"""
    # Validate course type and get course
    if course_type not in ['short', 'learning']:
        flash('Invalid course type.', 'error')
        return redirect(url_for('teacher.manage_courses'))
    
    CourseModel = ShortCourse if course_type == 'short' else LearningCourse
    # Allow teachers to add outlines to any course, not just their own
    course = CourseModel.query.filter_by(id=course_id).first_or_404()
    
    form = CourseOutlineForm()
    
    if request.method == 'POST':
        try:
            # Get sections data from form
            sections_data = []
            for key in request.form:
                if key.startswith('sections[') and '][title]' in key:
                    section_idx = int(key.split('[')[1].split(']')[0])
                    section_title = request.form[key]
                    topics = request.form.getlist(f'sections[{section_idx}][topics][]')
                    sections_data.append({
                        'title': section_title,
                        'topics': topics,
                        'order': section_idx + 1
                    })
            
            # Delete existing topics if any
            Topic.query.filter_by(course_id=course_id).delete()
            
            # Create new topics with order
            for section in sections_data:
                for topic_idx, topic_title in enumerate(section['topics'], 1):
                    # Debug print to check section title
                    print(f"Creating topic with section_title: {section['title']}")
                    
                    topic = Topic(
                        title=topic_title,
                        course_id=course_id,
                        course_type=course_type,  # Set course_type (short or learning)
                        section_title=section['title'] if section['title'] else "Default Section",  # Ensure not None
                        teacher_id=current_user.id,  # Set the current teacher as the owner
                        order=(section['order'] - 1) * 100 + topic_idx  # Allows for up to 99 topics per section
                    )
                    db.session.add(topic)
            
            db.session.commit()
            flash('Course outline has been created successfully!', 'success')
            return redirect(url_for('teacher.manage_courses'))
            
        except Exception as e:
            db.session.rollback()
            import traceback
            print(f"Error saving outline: {str(e)}")
            print(traceback.format_exc())
            flash(f'An error occurred while saving the outline: {str(e)}', 'error')
    
    return render_template('teacher/add_course_outline.html', form=form, course=course)

@bp.route('/courses/<course_type>/<int:course_id>/outline/edit', methods=['GET', 'POST'])
@login_required
def edit_course_outline(course_type, course_id):
    """Edit an existing course outline"""
    # Validate course type and get course
    if course_type not in ['short', 'learning']:
        flash('Invalid course type.', 'error')
        return redirect(url_for('teacher.manage_courses'))
    
    CourseModel = ShortCourse if course_type == 'short' else LearningCourse
    # Allow teachers to edit outlines for any course, not just their own
    course = CourseModel.query.filter_by(id=course_id).first_or_404()
    
    form = CourseOutlineForm()
    
    # Get existing topics grouped by sections
    topics = Topic.query.filter_by(course_id=course_id).order_by(Topic.order).all()
    sections = {}
    for topic in topics:
        if topic.section_title not in sections:
            sections[topic.section_title] = []
        sections[topic.section_title].append(topic)
    
    if request.method == 'POST':
        try:
            # Similar to add_course_outline, but first delete existing topics
            Topic.query.filter_by(course_id=course_id).delete()
            
            # Get sections data from form
            sections_data = []
            for key in request.form:
                if key.startswith('sections[') and '][title]' in key:
                    section_idx = int(key.split('[')[1].split(']')[0])
                    section_title = request.form[key]
                    topics = request.form.getlist(f'sections[{section_idx}][topics][]')
                    sections_data.append({
                        'title': section_title,
                        'topics': topics,
                        'order': section_idx + 1
                    })
            
            # Create new topics with order
            for section in sections_data:
                for topic_idx, topic_title in enumerate(section['topics'], 1):
                    # Debug print to check section title
                    print(f"Creating topic with section_title: {section['title']}")
                    
                    topic = Topic(
                        title=topic_title,
                        course_id=course_id,
                        course_type=course_type,  # Set course_type (short or learning)
                        section_title=section['title'] if section['title'] else "Default Section",  # Ensure not None
                        teacher_id=current_user.id,  # Set the current teacher as the owner
                        order=(section['order'] - 1) * 100 + topic_idx
                    )
                    db.session.add(topic)
            
            db.session.commit()
            flash('Course outline has been updated successfully!', 'success')
            return redirect(url_for('teacher.manage_courses'))
            
        except Exception as e:
            db.session.rollback()
            flash('An error occurred while updating the outline. Please try again.', 'error')
    
    return render_template('teacher/edit_course_outline.html', 
                         form=form, 
                         course=course, 
                         sections=sections)

@bp.route('/courses/<course_type>/<int:course_id>/outline/delete', methods=['POST'])
@login_required
def delete_course_outline(course_type, course_id):
    """Delete all topics (outline) for a course"""
    # Validate course type and get course
    if course_type not in ['short', 'learning']:
        return jsonify({'success': False, 'message': 'Invalid course type'})
    
    CourseModel = ShortCourse if course_type == 'short' else LearningCourse
    # Allow teachers to delete outlines for any course, not just their own
    course = CourseModel.query.filter_by(id=course_id).first_or_404()
    
    try:
        # Delete all topics for the course
        Topic.query.filter_by(course_id=course_id).delete()
        db.session.commit()
        return jsonify({'success': True, 'message': 'Course outline has been deleted successfully'})
    except Exception as e:
        db.session.rollback()
        return jsonify({'success': False, 'message': 'An error occurred while deleting the outline'})

@bp.route('/courses/outline/select')
@login_required
def select_course_for_outline():
    """Select a course to add an outline to"""
    # Get all courses - both the teacher's own courses and all other courses
    # First get courses assigned to this teacher
    teacher_short_courses = ShortCourse.query.filter_by(teacher_id=current_user.id).all()
    teacher_learning_courses = LearningCourse.query.filter_by(teacher_id=current_user.id).all()
    
    # Then get all other courses (excluding the teacher's own courses)
    other_short_courses = ShortCourse.query.filter(
        or_(
            ShortCourse.teacher_id != current_user.id,
            ShortCourse.teacher_id == None
        )
    ).all()
    
    other_learning_courses = LearningCourse.query.filter(
        or_(
            LearningCourse.teacher_id != current_user.id,
            LearningCourse.teacher_id == None
        )
    ).all()
    
    # Get highlight parameters (used to highlight a specific course)
    highlight_course_id = request.args.get('highlight')
    course_type = request.args.get('type')
    
    # Load course info with topics to show outline status
    # We'll preload all courses with their topics to avoid N+1 queries
    course_ids = [c.id for c in teacher_short_courses + teacher_learning_courses + 
                 other_short_courses + other_learning_courses]
    
    topics_by_course = {}
    if course_ids:
        topics = Topic.query.filter(Topic.course_id.in_(course_ids)).all()
        for topic in topics:
            if topic.course_id not in topics_by_course:
                topics_by_course[topic.course_id] = []
            topics_by_course[topic.course_id].append(topic)
    
    return render_template('teacher/select_course_for_outline.html',
                         teacher_short_courses=teacher_short_courses,
                         teacher_learning_courses=teacher_learning_courses,
                         other_short_courses=other_short_courses,
                         other_learning_courses=other_learning_courses,
                         topics_by_course=topics_by_course,
                         highlight_course_id=highlight_course_id,
                         course_type=course_type)

@bp.route('/courses/<course_type>/<int:course_id>/outline/view')
@login_required
def view_course_outline(course_type, course_id):
    """View the outline of a course"""
    # Validate course type and get course
    if course_type not in ['short', 'learning']:
        flash('Invalid course type.', 'error')
        return redirect(url_for('teacher.manage_courses'))
    
    CourseModel = ShortCourse if course_type == 'short' else LearningCourse
    
    # Allow teachers to view any course outline, students see any course
    course = CourseModel.query.filter_by(id=course_id).first_or_404()
    is_teacher = current_user.role == 'teacher'
    
    # Get topics for this course, ordered by their position
    topics = Topic.query.filter_by(course_id=course_id).order_by(Topic.order).all()
    
    # Fix any None section titles
    for topic in topics:
        if topic.section_title is None:
            # Look for the section title based on ordering - sections are in blocks of 100
            section_num = (topic.order // 100) + 1
            topic.section_title = f"Week {section_num}"
    
    return render_template('teacher/view_course_outline.html', 
                          course=course,
                          topics=topics,
                          course_type=course_type,
                          is_teacher=is_teacher)