from flask import render_template, redirect, url_for, flash, request, current_app
from app import db
from app.models.topic import Topic
from app.models.course import ShortCourse, LearningCourse
from app.forms.teacher import TopicForm
from app.routes.teacher import bp
from app.utils.decorators import teacher_required
from flask_login import login_required, current_user
from werkzeug.utils import secure_filename
import os
from datetime import datetime

def save_topic_image(image_file):
    """Save uploaded image and return the relative path"""
    if not image_file:
        return None
    
    # Create uploads directory if it doesn't exist
    upload_folder = os.path.join(current_app.root_path, 'static', 'uploads', 'topics')
    os.makedirs(upload_folder, exist_ok=True)
    
    # Generate unique filename
    timestamp = datetime.now().strftime('%Y%m%d_%H%M%S')
    filename = secure_filename(image_file.filename)
    name, ext = os.path.splitext(filename)
    unique_filename = f"{name}_{timestamp}{ext}"
    
    # Save file
    filepath = os.path.join(upload_folder, unique_filename)
    image_file.save(filepath)
    
    # Return relative path for database storage
    return f"uploads/topics/{unique_filename}"

@bp.route('/topics/add', methods=['GET', 'POST'])
@login_required
@teacher_required
def add_topic():
    form = TopicForm()
    if form.validate_on_submit():
        try:
            # Print form data for debugging
            print(f"Form submitted with data: {form.data}")
            
            # Determine course type
            course_id = form.course.data
            print(f"Selected course ID: {course_id}")
            
            # First try to find course with teacher_id, but if not found, try without teacher_id filter
            short_course = ShortCourse.query.filter_by(id=course_id, teacher_id=current_user.id).first()
            if not short_course:
                short_course = ShortCourse.query.filter_by(id=course_id).first()
                
            learning_course = LearningCourse.query.filter_by(id=course_id, teacher_id=current_user.id).first()
            if not learning_course:
                learning_course = LearningCourse.query.filter_by(id=course_id).first()
            
            print(f"Found courses - Short: {short_course}, Learning: {learning_course}")
            
            # Set course type based on which course was found
            if short_course:
                course_type = 'short'
            elif learning_course:
                course_type = 'learning'
            else:
                print(f"No course found with ID: {course_id}")
                flash('Selected course not found.', 'error')
                return redirect(url_for('teacher.add_topic'))
        except Exception as e:
            print(f"Error during form processing: {str(e)}")
            flash(f"An error occurred: {str(e)}", 'error')
            return redirect(url_for('teacher.add_topic'))
        
        try:
            print(f"Creating topic with course_type: {course_type}")
            
            # Handle image upload
            image_url = None
            if form.image.data:
                image_url = save_topic_image(form.image.data)
                print(f"Image saved: {image_url}")
            
            topic = Topic(
                title=form.title.data,
                category=form.category.data,
                reading_content=form.reading_content.data,
                image_url=image_url,
                speaking_prompt=form.speaking_prompt.data,
                writing_prompt=form.writing_prompt.data,
                teacher_id=current_user.id,
                course_id=course_id,
                course_type=course_type
            )
            
            print(f"New topic object created: {topic}")
            
            db.session.add(topic)
            db.session.commit()
            
            print(f"Topic saved to database with ID: {topic.id}")
            flash('Topic has been created successfully!', 'success')
            return redirect(url_for('teacher.manage_topics'))
        except Exception as e:
            db.session.rollback()
            print(f"Error saving topic to database: {str(e)}")
            flash(f"Error adding topic: {str(e)}", 'error')
            return redirect(url_for('teacher.add_topic'))
    return render_template('teacher/add_topic.html', form=form)

@bp.route('/topics/manage')
@login_required
@teacher_required
def manage_topics():
    topics = Topic.query.filter_by(teacher_id=current_user.id).all()
    return render_template('teacher/manage_topics.html', topics=topics)

@bp.route('/topics/<int:topic_id>/edit', methods=['GET', 'POST'])
@login_required
@teacher_required
def edit_topic(topic_id):
    topic = Topic.query.filter_by(id=topic_id, teacher_id=current_user.id).first_or_404()
    form = TopicForm()
    
    # Check if there are any courses available
    short_courses = ShortCourse.query.all()
    learning_courses = LearningCourse.query.all()
    total_courses = len(short_courses) + len(learning_courses)
    
    print(f"DEBUG - Found {total_courses} total courses ({len(short_courses)} short, {len(learning_courses)} learning)")
    
    if total_courses == 0:
        flash("Warning: No courses are available. Please create a course before editing topics.", "warning")
    
    if request.method == 'POST':
        print(f"DEBUG - Form submitted with data: {request.form}")
        
        # Check if the course field exists in the form data
        if 'course' not in request.form:
            flash("Error: Course field is required but was not submitted.", "error")
            print("ERROR - Course field not in form data!")
        
        if form.validate_on_submit():
            # Store original values for comparison
            old_title = topic.title
            old_category = topic.category
            old_reading = topic.reading_content
            old_course_id = topic.course_id
            
            # Update topic data
            topic.title = form.title.data
            topic.category = form.category.data
            topic.reading_content = form.reading_content.data
            topic.speaking_prompt = form.speaking_prompt.data
            topic.writing_prompt = form.writing_prompt.data
            
            # Handle image upload
            if form.image.data:
                # Delete old image if it exists
                if topic.image_url:
                    old_image_path = os.path.join(current_app.root_path, 'static', topic.image_url)
                    if os.path.exists(old_image_path):
                        try:
                            os.remove(old_image_path)
                            print(f"Deleted old image: {old_image_path}")
                        except Exception as e:
                            print(f"Error deleting old image: {str(e)}")
                
                # Save new image
                topic.image_url = save_topic_image(form.image.data)
                print(f"New image saved: {topic.image_url}")
            
            print(f"DEBUG - Course data: form.course.data={form.course.data}, topic.course_id={topic.course_id}")
            
            # Check if the course field is 0 (placeholder for no courses)
            if form.course.data == 0:
                flash("Warning: Using placeholder course. Please create real courses.", "warning")
                # Keep the existing course_id if available
                if not topic.course_id:
                    topic.course_id = 1  # Default to ID 1 as fallback
                    topic.course_type = 'short'  # Default type
            else:
                # Update the course relation
                topic.course_id = form.course.data
                # Determine course type
                short_course = ShortCourse.query.filter_by(id=form.course.data).first()
                if short_course:
                    topic.course_type = 'short'
                else:
                    learning_course = LearningCourse.query.filter_by(id=form.course.data).first()
                    if learning_course:
                        topic.course_type = 'learning'
                    else:
                        print(f"WARNING - Selected course ID {form.course.data} not found in either course type")
            
            try:
                db.session.commit()
                # Force a refresh to clear any cached data
                db.session.expire_all()  # Clear all cached objects
                db.session.refresh(topic)  # Reload this specific object
                
                print(f"DEBUG - Topic updated. Old: {old_title}/{old_category}/{old_course_id}/{old_reading[:30] if old_reading else 'None'}")
                print(f"DEBUG - Topic updated. New: {topic.title}/{topic.category}/{topic.course_id}/{topic.reading_content[:30] if topic.reading_content else 'None'}")
                
                flash('Topic has been updated successfully!', 'success')
                return redirect(url_for('teacher.manage_topics'))
            except Exception as e:
                db.session.rollback()
                print(f"ERROR - Failed to update topic: {str(e)}")
                flash(f'Error updating topic: {str(e)}', 'error')
        else:
            print(f"DEBUG - Form validation errors: {form.errors}")
            for field, errors in form.errors.items():
                for error in errors:
                    flash(f"{field}: {error}", "error")
    
    elif request.method == 'GET':
        # First populate the form with existing data
        form.title.data = topic.title
        form.category.data = topic.category
        form.reading_content.data = topic.reading_content
        form.speaking_prompt.data = topic.speaking_prompt
        form.writing_prompt.data = topic.writing_prompt
        
        # Make sure course field is populated (do this last to ensure choices are loaded)
        if topic.course_id:
            # Check if the course_id exists in the available choices
            course_ids = [c[0] for c in form.course.choices]
            if topic.course_id in course_ids:
                form.course.data = topic.course_id
                print(f"DEBUG - Setting form.course.data to {topic.course_id} (existing)")
            else:
                print(f"WARNING - Topic's course_id {topic.course_id} not in available choices {course_ids}")
                # If the course no longer exists, use the first available
                if form.course.choices:
                    form.course.data = form.course.choices[0][0]
                    print(f"DEBUG - Course not found, using first available: {form.course.data}")
        else:
            # If topic doesn't have a course_id, use the first available course
            if form.course.choices:
                form.course.data = form.course.choices[0][0]
                print(f"DEBUG - Setting default form.course.data to {form.course.data}")
            else:
                print("WARNING - No course choices available!")
    
    return render_template('teacher/edit_topic.html', form=form, topic=topic)

@bp.route('/topics/<int:topic_id>', methods=['DELETE'])
@login_required
@teacher_required
def delete_topic(topic_id):
    try:
        topic = Topic.query.filter_by(id=topic_id, teacher_id=current_user.id).first_or_404()
        db.session.delete(topic)
        db.session.commit()
        # Return JSON response for AJAX request
        return {'success': True, 'message': 'Topic has been deleted successfully!'}, 200
    except Exception as e:
        db.session.rollback()
        print(f"Error deleting topic: {str(e)}")
        return {'success': False, 'error': 'Failed to delete topic'}, 500

@bp.route('/topics/<int:topic_id>/delete', methods=['POST'])
@login_required
@teacher_required
def delete_topic_post(topic_id):
    # Keep the POST route for backward compatibility or non-JS fallback
    topic = Topic.query.filter_by(id=topic_id, teacher_id=current_user.id).first_or_404()
    db.session.delete(topic)
    db.session.commit()
    flash('Topic has been deleted successfully!', 'success')
    return redirect(url_for('teacher.manage_topics'))

@bp.route('/topics/<int:topic_id>/analytics')
@login_required
@teacher_required
def view_topic_analytics(topic_id):
    # Get the topic and validate it belongs to the current teacher
    topic = Topic.query.filter_by(id=topic_id, teacher_id=current_user.id).first_or_404()
    
    # In a real application, you would get this data from your database
    # For now, we'll use placeholder data to match the template expectations
    analytics = {
        'completion_rate': 65,
        'average_scores': {
            'comprehension': '72/100',
            'speaking': '68/100',
            'writing': '70/100',
            'overall': '70/100'
        },
        'stage_breakdown': {
            'reading': {'count': 24, 'percentage': 80},
            'comprehension': {'count': 20, 'percentage': 67},
            'writing': {'count': 18, 'percentage': 60},
            'speaking': {'count': 15, 'percentage': 50}
        }
    }
    
    return render_template('teacher/topic_analytics.html', topic=topic, analytics=analytics)