"""
Admin/Content Management routes - courses, videos, topics, quizzes
With instructor filtering - instructors only see their assigned content
"""
from flask import Blueprint, request, jsonify
from sqlalchemy import or_
import urllib.parse as urlparse

from config import db
from models.user import Admin, Courses, Category, Instructor, User, Topic
from models.videoandrecent import Video
from models.quiz import Questions, Options
from models.institute import Enrollment
from utils.decorators import token_required

admin_bp = Blueprint('admin', __name__, url_prefix='/api')


@admin_bp.route('/users', methods=['POST'])
@token_required
def get_all_users(current_user, user_role, institute_id, instructor_id):
    """Get all users/students"""
    data = request.get_json() or {}
    query = data.get('query')
    filter_by = data.get('filter')
    
    query_builder = User.query
    if institute_id:
        query_builder = query_builder.filter(User.id.in_(
            db.session.query(Enrollment.user_id)
            .join(Courses, Enrollment.course_id == Courses.id)
            .filter(Courses.institute_id == institute_id)
        ))

    if query:
        if filter_by == 'fullname':
            users = query_builder.filter(User.fullname.ilike(f'%{query}%')).all()
        else:
            users = query_builder.filter(User.email.ilike(f'%{query}%')).all()
    else:
        users = query_builder.all()
    
    output = []
    for use in users:
        user_data = {
            'username': use.username,
            'id': use.id,
            'fullname': use.fullname,
            'profile_img_url': use.profile_img_url,
            'email': use.email
        }
        output.append(user_data)
    
    return jsonify({'users': output}), 200


@admin_bp.route('/courses', methods=['POST'])
@token_required
def fetch_courses(current_user, user_role, institute_id, instructor_id):
    """Get courses - filtered by instructor for instructor users"""
    data = request.get_json() or {}
    query_text = data.get('query')

    # Start with base query
    query = Courses.query
    
    if institute_id:
        query = query.filter_by(institute_id=institute_id)
    
    # Filter by instructor_id if user is an instructor
    if user_role in ['instructor', 'teacher']:
        if instructor_id:
            query = query.filter_by(instructor_id=instructor_id)
        elif hasattr(current_user, 'name'):
            query = query.filter(Courses.instructor_name == current_user.name)

    # Apply search filter
    if query_text:
        query = query.filter(
            or_(
                Courses.title.ilike(f'%{query_text}%'),
                Courses.description.ilike(f'%{query_text}%')
            )
        )

    courses = query.all()
    output = [course.to_dict() for course in courses]
    instructors = Instructor.query.all()

    return jsonify({'courses': output, 'instructor': [inst.to_dict() for inst in instructors]}), 200


@admin_bp.route('/categories', methods=['POST'])
@token_required
def fetch_categories(current_user, user_role, institute_id, instructor_id):
    """Get all categories"""
    data = request.get_json() or {}
    query = data.get('query')

    if query:
        categories = Category.query.filter(Category.name.ilike(f'%{query}%')).all()
    else:
        categories = Category.query.all()

    output = [cat.to_dict() for cat in categories]
    return jsonify({'categories': output}), 200


@admin_bp.route('/videos', methods=['POST'])
@token_required
def get_all_videos(current_user, user_role, institute_id, instructor_id):
    """Get videos - filtered by instructor's courses for instructor users"""
    data = request.get_json() or {}
    query_text = data.get('query')
    topic_id = data.get('topic_id')
    course_filter = data.get('filter')

    # Start building the query
    video_query = Video.query
    
    if institute_id:
        video_query = video_query.join(Courses, Video.course_id == Courses.id).filter(Courses.institute_id == institute_id)
    
    # For instructors, only show videos from their courses
    if user_role in ['instructor', 'teacher']:
        if instructor_id:
            instructor_course_ids = [c.id for c in Courses.query.filter_by(instructor_id=instructor_id).all()]
            if instructor_course_ids:
                video_query = video_query.filter(Video.course_id.in_(instructor_course_ids))
            else:
                return jsonify({'videos': []}), 200
    
    # Apply filters
    if course_filter:
        video_query = video_query.filter(Video.course_id == course_filter)
    
    if topic_id:
        video_query = video_query.filter(Video.topic_id == topic_id)
    
    if query_text:
        video_query = video_query.filter(Video.title.ilike(f'%{query_text}%'))

    videos = video_query.all()

    output = []
    for use in videos:
        try:
            url_data = urlparse.urlparse(use.video_url)
            qs = urlparse.parse_qs(url_data.query)
            video_id = qs.get('v', [None])[0]
            thumbnail = f'https://img.youtube.com/vi/{video_id}/0.jpg' if video_id else ''
        except Exception:
            thumbnail = ''

        user_data = {
            'id': use.id,
            'title': use.title,
            'video_url': use.video_url,
            'type': use.type,
            'description': use.description or None,
            'credit': use.credit,
            'for_which': use.for_which,
            'level': use.level,
            'image_url': thumbnail,
            'video_duration': str(use.video_duration),
            'count_exercises': use.count_exercises,
            'count_students': use.count_students,
            'count_plays': use.count_plays,
            'count_views': use.count_views,
            'count_likes': use.count_likes,
            'count_comments': use.count_comments,
            'short_description': use.short_description,
            'course_id': use.course_id,
            'is_live': use.is_live,
            'chat_id': use.chat_id,
            'is_active': use.is_active,
            'free': use.free,
            'created_at': use.created_at.strftime('%Y-%m-%dT%H:%M:%S') if use.created_at else None,
            'updated_at': use.updated_at.strftime('%Y-%m-%dT%H:%M:%S') if use.updated_at else None,
            'topic_id': use.topic_id,
        }
        output.append(user_data)

    return jsonify({'videos': output}), 200


@admin_bp.route('/topics', methods=['POST'])
@token_required
def get_all_topics(current_user, user_role, institute_id, instructor_id):
    """Get topics - filtered by instructor's courses for instructor users"""
    data = request.get_json() or {}
    query_text = data.get('query')
    course_filter = data.get('filter')

    # Start building the query
    topic_query = Topic.query
    
    if institute_id:
        topic_query = topic_query.join(Courses, Topic.course_id == Courses.id).filter(Courses.institute_id == institute_id)

    # For instructors, only show topics from their courses
    if user_role in ['instructor', 'teacher']:
        if instructor_id:
            instructor_course_ids = [c.id for c in Courses.query.filter_by(instructor_id=instructor_id).all()]
            if instructor_course_ids:
                topic_query = topic_query.filter(Topic.course_id.in_(instructor_course_ids))
            else:
                return jsonify({'topics': []}), 200

    # Apply course filter
    if course_filter:
        topic_query = topic_query.filter(Topic.course_id == course_filter)
    
    # Apply search filter
    if query_text:
        topic_query = topic_query.filter(Topic.title.ilike(f'%{query_text}%'))

    # Order by hierarchy
    topic_query = topic_query.order_by(Topic.level.asc(), Topic.parent_topic_id.asc(), Topic.order.asc())

    topics = topic_query.all()

    output = []
    for topic in topics:
        topic_data = {
            'id': topic.id,
            'title': topic.title,
            'description': topic.description,
            'content_type': topic.content_type,
            'content_url': topic.content_url,
            'order': topic.order,
            'duration_minutes': topic.duration_minutes,
            'is_previewable': topic.is_previewable,
            'status': topic.status,
            'course_id': topic.course_id,
            'parent_topic_id': topic.parent_topic_id,
            'level': topic.level,
            'full_path': topic.full_path,
            'created_at': topic.created_at.strftime('%Y-%m-%dT%H:%M:%S') if topic.created_at else None,
            'updated_at': topic.updated_at.strftime('%Y-%m-%dT%H:%M:%S') if topic.updated_at else None,
        }
        output.append(topic_data)

    return jsonify({'topics': output}), 200


@admin_bp.route('/get_quiz_details', methods=['POST'])
@token_required
def quiz_details(current_user, user_role, institute_id, instructor_id):
    """Get quiz details"""
    from quiz import get_quiz_details
    return get_quiz_details(request, Questions, Options, Topic)


# ==========================================
# CREATE/UPDATE ENDPOINTS
# ==========================================

@admin_bp.route('/add-question', methods=['POST'])
@token_required
def add_question(current_user, user_role, institute_id, instructor_id):
    """Add a new quiz question"""
    try:
        data = request.get_json()
        question_text = data.get('question_text')
        correct_answer = data.get('correct_answer')
        topic_id = data.get('topic_id')
        options = data.get('options', [])

        if not question_text or not topic_id:
            return jsonify({'message': 'Question text and topic_id are required!'}), 400

        # Verify instructor has access to this topic's course
        if user_role in ['instructor', 'teacher'] and instructor_id:
            topic = Topic.query.get(topic_id)
            if topic:
                course = Courses.query.get(topic.course_id)
                if course and course.instructor_id != instructor_id:
                    return jsonify({'message': 'Unauthorized: This topic belongs to another instructor'}), 403

        # Create question - question_id is auto-increment
        new_question = Questions(
            question_text=question_text,
            topic_id=topic_id,
            correct_answer=correct_answer
        )
        db.session.add(new_question)
        db.session.flush()  # Get the auto-generated question_id

        # Add options using the generated question_id
        for opt in options:
            new_option = Options(
                question_id=new_question.question_id,
                option_text=opt.get('option_text', ''),
                is_correct=opt.get('is_correct', False)
            )
            db.session.add(new_option)

        db.session.commit()
        return jsonify({'message': 'Question added successfully!', 'question_id': new_question.question_id}), 201

    except Exception as e:
        db.session.rollback()
        return jsonify({'message': f'Error adding question: {str(e)}'}), 500


@admin_bp.route('/add-video', methods=['POST'])
@token_required
def add_video(current_user, user_role, institute_id, instructor_id):
    """Add a new video"""
    try:
        # Handle both FormData and JSON
        if request.content_type and 'multipart/form-data' in request.content_type:
            title = request.form.get('title')
            video_url = request.form.get('videoUrl')
            video_type = request.form.get('type')
            description = request.form.get('description', '')
            credit = request.form.get('credit', '')
            level = request.form.get('level', 'beginner')
            short_description = request.form.get('shortDescription', '')
            course_id = request.form.get('courseId')
            topic_id = request.form.get('topic_id')
        else:
            data = request.get_json() or {}
            title = data.get('title')
            video_url = data.get('videoUrl')
            video_type = data.get('type')
            description = data.get('description', '')
            credit = data.get('credit', '')
            level = data.get('level', 'beginner')
            short_description = data.get('shortDescription', '')
            course_id = data.get('courseId')
            topic_id = data.get('topic_id')

        if not title or not video_url:
            return jsonify({'message': 'Title and video URL are required!'}), 400

        # Verify instructor has access to this course
        if user_role in ['instructor', 'teacher'] and instructor_id and course_id:
            course = Courses.query.get(int(course_id))
            if course and course.instructor_id != instructor_id:
                return jsonify({'message': 'Unauthorized: This course belongs to another instructor'}), 403

        new_video = Video(
            title=title,
            video_url=video_url,
            type=video_type,
            description=description,
            credit=credit,
            level=level,
            short_description=short_description,
            course_id=int(course_id) if course_id else None,
            topic_id=int(topic_id) if topic_id else None
        )
        db.session.add(new_video)
        db.session.commit()

        return jsonify({'message': 'Video added successfully!', 'video_id': new_video.id}), 201

    except Exception as e:
        db.session.rollback()
        return jsonify({'message': f'Error adding video: {str(e)}'}), 500


@admin_bp.route('/add-course', methods=['POST'])
@token_required
def add_course(current_user, user_role, institute_id, instructor_id):
    """Add a new course"""
    try:
        # Handle FormData
        title = request.form.get('title')
        subtitle = request.form.get('subtitle', '')
        description = request.form.get('description', '')
        video_url = request.form.get('videoUrl', '')
        price = request.form.get('price', 0)
        discount = request.form.get('discount', 0)
        final_price = request.form.get('finalPrice', 0)
        level = request.form.get('level', 'Beginner')
        category_id = request.form.get('categoryId')
        course_type = request.form.get('type', 'Self-paced')
        publication_date = request.form.get('publicationDate')
        is_featured = request.form.get('isFeatured', 'false') == 'true'
        is_top_selling = request.form.get('isTopSelling', 'false') == 'true'
        is_trending = request.form.get('isTrending', 'false') == 'true'
        prerequisites = request.form.get('prerequisites', '')
        outcomes = request.form.get('outcomes', '')
        target_audience = request.form.get('targetAudience', '')
        language = request.form.get('language', 'English')
        status = request.form.get('status', 'active')
        form_instructor_name = request.form.get('instructorName', '')
        form_instructor_id = request.form.get('instructorId')

        if not title:
            return jsonify({'message': 'Title is required!'}), 400

        # For instructors, always use their own instructor_id
        if user_role in ['instructor', 'teacher'] and instructor_id:
            assigned_instructor_id = instructor_id
            instructor = Instructor.query.get(instructor_id)
            assigned_instructor_name = instructor.name if instructor else form_instructor_name
        else:
            assigned_instructor_id = int(form_instructor_id) if form_instructor_id else None
            assigned_instructor_name = form_instructor_name

        # Handle image upload
        image_url = ''
        if 'image' in request.files:
            image_file = request.files['image']
            if image_file.filename:
                import os
                from werkzeug.utils import secure_filename
                filename = secure_filename(image_file.filename)
                upload_folder = os.path.join(os.path.dirname(__file__), '..', 'uploads')
                os.makedirs(upload_folder, exist_ok=True)
                filepath = os.path.join(upload_folder, filename)
                image_file.save(filepath)
                image_url = f'/static/uploads/{filename}'

        # Parse publication date
        from datetime import datetime as dt
        pub_date = None
        if publication_date:
            try:
                pub_date = dt.strptime(publication_date, '%Y-%m-%d').date()
            except:
                pub_date = dt.now().date()
        else:
            pub_date = dt.now().date()

        new_course = Courses(
            title=title,
            subtitle=subtitle,
            description=description or 'No description provided',
            video_preview_url=video_url,  # Field is video_preview_url not video_url
            price=float(price) if price else 0,
            discount=float(discount) if discount else 0,
            # final_price is computed automatically, don't set it
            level=level,
            category_id=int(category_id) if category_id else 1,
            type=course_type,
            publication_date=pub_date,
            is_featured=is_featured,
            is_top_selling=is_top_selling,
            is_trending=is_trending,
            prerequisites=prerequisites,
            outcomes=outcomes,
            target_audience=target_audience,
            language=language,
            image_url=image_url,
            status=status,
            instructor_id=assigned_instructor_id or 1,
            instructor_name=assigned_instructor_name or 'Instructor',
            institute_id=institute_id
        )
        db.session.add(new_course)
        db.session.commit()

        return jsonify({'message': 'Course added successfully!', 'course_id': new_course.id}), 201

    except Exception as e:
        db.session.rollback()
        return jsonify({'message': f'Error adding course: {str(e)}'}), 500


@admin_bp.route('/add-topic', methods=['POST'])
@token_required
def add_topic(current_user, user_role, institute_id, instructor_id):
    """Add a new topic"""
    try:
        # Check if form data or JSON
        if request.content_type and 'multipart/form-data' in request.content_type:
            data = request.form
        else:
            data = request.get_json() or {}
            
        title = data.get('title')
        description = data.get('description', '')
        course_id = data.get('course_id')
        content_type = data.get('content_type', 'video')
        content_url = data.get('content_url', '')
        order = data.get('order', 1)
        duration_minutes = data.get('duration_minutes', 0)
        is_previewable = str(data.get('is_previewable', 'false')).lower() == 'true'
        status = data.get('status', 'active')
        note_content = data.get('content') # Support attached Topic Notes
        markdown_format = str(data.get('markdown_format', 'true')).lower() == 'true'
        topic_id = data.get('topicId') or data.get('topic_id')  # Support updates
        parent_topic_id = data.get('parent_topic_id')

        if not title or not course_id:
            return jsonify({'message': 'Title and course_id are required!'}), 400

        # Verify instructor has access to this course
        if user_role in ['instructor', 'teacher'] and instructor_id:
            course = Courses.query.get(int(course_id))
            if course and course.instructor_id != instructor_id:
                return jsonify({'message': 'Unauthorized: This course belongs to another instructor'}), 403

        # Hierarchy calculation
        level = 0
        full_path = title
        parent_id_val = None
        if parent_topic_id and str(parent_topic_id).strip():
            parent_id_val = int(parent_topic_id)
            parent_topic = Topic.query.get(parent_id_val)
            if parent_topic:
                level = (parent_topic.level or 0) + 1
                parent_path = parent_topic.full_path or parent_topic.title
                full_path = f"{parent_path} > {title}"

        # Add logic for Create vs Update
        if topic_id:
            topic = Topic.query.get(int(topic_id))
            if not topic:
                return jsonify({'message': 'Topic not found'}), 404
                
            topic.title = title
            topic.description = description
            topic.content_type = content_type
            topic.content_url = content_url
            if order:
                topic.order = int(order)
            if duration_minutes:
                topic.duration_minutes = int(duration_minutes)
            topic.is_previewable = is_previewable
            topic.status = status
            topic.parent_topic_id = parent_id_val
            topic.level = level
            topic.full_path = full_path
            is_new = False
            target_topic_id = topic.id
        else:
            topic = Topic(
                title=title,
                description=description,
                course_id=int(course_id),
                content_type=content_type,
                content_url=content_url,
                order=int(order) if order else 1,
                duration_minutes=int(duration_minutes) if duration_minutes else 0,
                is_previewable=is_previewable,
                status=status,
                parent_topic_id=parent_id_val,
                level=level,
                full_path=full_path
            )
            db.session.add(topic)
            db.session.flush() # Flush to get the new_topic.id
            is_new = True
            target_topic_id = topic.id

        # Insert or Update Topic Notes if provided
        if note_content is not None and str(note_content).strip():
            from models.user import CourseNotesContent
            existing_note = CourseNotesContent.query.filter_by(topic_id=target_topic_id).first()
            if existing_note:
                existing_note.content = note_content
                existing_note.markdown_format = markdown_format
            else:
                new_note = CourseNotesContent(
                    topic_id=target_topic_id,
                    content=note_content,
                    markdown_format=markdown_format
                )
                db.session.add(new_note)

        # Handle Audio Upload
        if 'audio_file' in request.files:
            audio_file = request.files['audio_file']
            if audio_file.filename:
                import os
                from werkzeug.utils import secure_filename
                filename = secure_filename(f"topic_{target_topic_id}_{audio_file.filename}")
                # Store in static/uploads/audio/
                base_dir = os.path.abspath(os.path.dirname(__file__))
                upload_folder = os.path.join(base_dir, '..', 'static', 'uploads', 'audio')
                os.makedirs(upload_folder, exist_ok=True)
                filepath = os.path.join(upload_folder, filename)
                audio_file.save(filepath)
                
                audio_url = f'/static/uploads/audio/{filename}'
                audio_language = data.get('audio_language', 'English')
                
                from models.user import CourseAudioContent
                existing_audio = CourseAudioContent.query.filter_by(topic_id=target_topic_id, language=audio_language).first()
                if existing_audio:
                    existing_audio.file_path = audio_url
                    existing_audio.file_size = os.path.getsize(filepath)
                else:
                    new_audio = CourseAudioContent(
                        topic_id=target_topic_id,
                        title=title + ' Audio',
                        file_path=audio_url,
                        duration=0, # Need library like mutagen to get duration, leave at 0 for now
                        file_size=os.path.getsize(filepath),
                        language=audio_language
                    )
                    db.session.add(new_audio)

        db.session.commit()

        msg = 'Topic added successfully!' if is_new else 'Topic updated successfully!'
        return jsonify({'message': msg, 'topic_id': target_topic_id}), 201

    except Exception as e:
        db.session.rollback()
        return jsonify({'message': f'Error processing topic: {str(e)}'}), 500


active_ocr_jobs = {}

def bg_process_ocr(topic_id, pdf_path, language, vision_model, rewrite_model):
    from utils.ai_ocr import process_pdf
    from models.user import CourseNotesContent
    from config import db
    from app import app
    import os
    
    
    active_ocr_jobs[topic_id] = {'status': 'processing', 'progress': 'Starting OCR pipeline...'}
    
    try:
        current_dir = os.path.dirname(os.path.abspath(__file__))
        temp_out = os.path.join(current_dir, '..', 'temp_ocr_out', str(topic_id))
        os.makedirs(temp_out, exist_ok=True)
        
        with app.app_context():
            process_pdf(
                pdf_path=pdf_path,
                output_dir=temp_out,
                language=language,
                vision_model_key=vision_model,
                rewrite_model_key=rewrite_model,
                force_single_chapter=True
            )
            
            pdf_stem = os.path.splitext(os.path.basename(pdf_path))[0]
            lang_suffix = f"_{language}" if language != "en" else ""
            target_md = os.path.join(temp_out, f"{pdf_stem}_complete{lang_suffix}.md")
            combined_md = os.path.join(temp_out, "combined.md")
            
            # Try the _complete file first, then fall back to combined.md
            content = ''
            for candidate in [target_md, combined_md]:
                if os.path.exists(candidate) and os.path.getsize(candidate) > 0:
                    with open(candidate, 'r', encoding='utf-8') as f:
                        content = f.read()
                    break
            
            if content.strip():
                note = CourseNotesContent.query.filter_by(topic_id=topic_id).first()
                if note:
                    note.content = content
                    note.markdown_format = True
                else:
                    new_note = CourseNotesContent(topic_id=topic_id, content=content, markdown_format=True)
                    db.session.add(new_note)
                db.session.commit()
                active_ocr_jobs[topic_id] = {'status': 'completed', 'progress': 'Done!'}
            else:
                active_ocr_jobs[topic_id] = {'status': 'failed', 'progress': 'Output file not found or empty after processing.'}
    except Exception as e:
        active_ocr_jobs[topic_id] = {'status': 'failed', 'progress': f'Error: {str(e)}'}

@admin_bp.route('/generate-topic-audio', methods=['POST'])
@token_required
def api_generate_topic_audio(current_user, user_role, institute_id, instructor_id):
    data = request.get_json()
    topic_id = data.get('topic_id')
    language = data.get('language', 'English')
    
    if not topic_id:
        return jsonify({'message': 'Missing topic_id'}), 400
        
    topic = Topic.query.get(topic_id)
    if not topic:
        return jsonify({'message': 'Topic not found'}), 404
        
    from models.user import CourseNotesContent
    note = CourseNotesContent.query.filter_by(topic_id=topic_id).first()
    if not note or not note.content.strip():
        return jsonify({'message': 'No markdown notes found to generate audio. Please add notes first.'}), 400
        
    import os
    from utils.ai_audio import generate_topic_audio
    base_dir = os.path.abspath(os.path.dirname(__file__))
    upload_folder = os.path.join(base_dir, '..', 'static', 'uploads', 'audio')
    os.makedirs(upload_folder, exist_ok=True)
    filename = f"topic_{topic_id}_ai_overview.mp3"
    filepath = os.path.join(upload_folder, filename)
    
    success = generate_topic_audio(note.content, topic.title, filepath)
    
    if success:
        audio_url = f'/static/uploads/audio/{filename}'
        audio_size = os.path.getsize(filepath) if os.path.exists(filepath) else 0
        
        from models.user import CourseAudioContent
        existing_audio = CourseAudioContent.query.filter_by(topic_id=topic_id, language=language).first()
        if existing_audio:
            existing_audio.file_path = audio_url
            existing_audio.file_size = audio_size
        else:
            new_audio = CourseAudioContent(
                topic_id=topic_id,
                title=f"{topic.title} - AI Sathi Overview",
                file_path=audio_url,
                duration=0,
                file_size=audio_size,
                language=language
            )
            db.session.add(new_audio)
        db.session.commit()
        return jsonify({'message': 'Audio generated successfully!', 'audio_url': audio_url}), 200
    else:
        return jsonify({'message': 'Failed to generate audio.'}), 500

@admin_bp.route('/generate-topic-notes-ocr', methods=['POST'])
@token_required
def api_generate_topic_notes_ocr(current_user, user_role, institute_id, instructor_id):
    if 'pdf_file' not in request.files:
        return jsonify({'message': 'No pdf_file provided'}), 400
    
    topic_id = request.form.get('topic_id')
    if not topic_id:
        return jsonify({'message': 'Missing topic_id'}), 400
        
    pdf_file = request.files['pdf_file']
    if pdf_file.filename == '':
        return jsonify({'message': 'Empty filename'}), 400
        
    if not pdf_file.filename.lower().endswith('.pdf'):
        return jsonify({'message': 'File must be a PDF'}), 400
        
    language = request.form.get('language', 'en')
    vision_model = request.form.get('vision_model', 'scout')
    rewrite_model = request.form.get('rewrite_model', 'kimi')
    
    import os
    import threading
    from werkzeug.utils import secure_filename
    base_dir = os.path.abspath(os.path.dirname(__file__))
    upload_folder = os.path.join(base_dir, '..', 'temp_pdfs')
    os.makedirs(upload_folder, exist_ok=True)
    
    filename = secure_filename(f"topic_{topic_id}_{pdf_file.filename}")
    filepath = os.path.join(upload_folder, filename)
    pdf_file.save(filepath)
    
    thread = threading.Thread(target=bg_process_ocr, args=(int(topic_id), filepath, language, vision_model, rewrite_model))
    thread.daemon = True
    thread.start()
    
    return jsonify({'message': 'OCR processing started in background.'}), 202

@admin_bp.route('/ocr-status', methods=['GET'])
@token_required
def api_ocr_status(current_user, user_role, institute_id, instructor_id):
    topic_id = request.args.get('topic_id')
    if not topic_id:
        return jsonify({'message': 'Missing topic_id'}), 400
        
    topic_id = int(topic_id)
    if topic_id in active_ocr_jobs:
        return jsonify(active_ocr_jobs[topic_id]), 200
    else:
        return jsonify({'status': 'idle', 'progress': 'No active job.'}), 200

@admin_bp.route('/get-course-add', methods=['POST'])
@token_required
def get_course_add_data(current_user, user_role, institute_id, instructor_id):
    """Get data needed for course add form (categories and instructors)"""
    try:
        categories = Category.query.all()
        instructors = Instructor.query.all()
        
        return jsonify({
            'categories': [cat.to_dict() for cat in categories],
            'instructor': [inst.to_dict() for inst in instructors]
        }), 200
    except Exception as e:
        return jsonify({'message': f'Error: {str(e)}'}), 500


# ==========================================
# INSTRUCTOR ANALYTICS & STUDENTS ROUTES
# ==========================================

@admin_bp.route('/analytics', methods=['POST'])
@token_required
def get_my_analytics(current_user, user_role, institute_id, instructor_id):
    """Get analytics for the current user (instructor sees their own stats)"""
    from sqlalchemy import func, extract
    from datetime import datetime, timedelta
    
    try:
        # Helper function to get monthly data
        def get_monthly_data(course_ids=None):
            months = []
            now = datetime.now()
            
            for i in range(5, -1, -1):
                month_date = now - timedelta(days=30*i)
                month_name = month_date.strftime('%b')
                month_num = month_date.month
                year = month_date.year
                
                # Count enrollments for this month
                enrollment_query = db.session.query(func.count(Enrollment.id)).filter(
                    extract('month', Enrollment.enrolled_at) == month_num,
                    extract('year', Enrollment.enrolled_at) == year
                )
                
                # Count revenue for this month
                revenue_query = db.session.query(func.sum(Enrollment.payment_amount)).filter(
                    extract('month', Enrollment.enrolled_at) == month_num,
                    extract('year', Enrollment.enrolled_at) == year
                )
                
                if course_ids:
                    enrollment_query = enrollment_query.filter(Enrollment.course_id.in_(course_ids))
                    revenue_query = revenue_query.filter(Enrollment.course_id.in_(course_ids))
                
                enrollment_count = enrollment_query.scalar() or 0
                revenue_total = revenue_query.scalar() or 0
                
                months.append({
                    'name': month_name,
                    'students': enrollment_count,
                    'revenue': float(revenue_total),
                    'enrollments': enrollment_count
                })
            
            return months
        
        # Get category distribution
        def get_category_distribution(course_ids=None):
            query = db.session.query(
                Category.name,
                func.count(Courses.id).label('count')
            ).join(Courses, Category.id == Courses.category_id)
            
            if course_ids:
                query = query.filter(Courses.id.in_(course_ids))
            
            results = query.group_by(Category.name).limit(5).all()
            
            colors = ['#8b5cf6', '#06b6d4', '#10b981', '#f59e0b', '#6b7280']
            distribution = []
            for i, (name, count) in enumerate(results):
                distribution.append({
                    'name': name or 'Uncategorized',
                    'value': count,
                    'color': colors[i % len(colors)]
                })
            
            return distribution if distribution else [{'name': 'No Data', 'value': 1, 'color': '#6b7280'}]
        
        # Weekly activity — real enrollment counts per day of the current week
        def get_weekly_activity(course_ids=None):
            days = ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun']
            now = datetime.now()
            # Find Monday of this week
            monday = now - timedelta(days=now.weekday())
            monday = monday.replace(hour=0, minute=0, second=0, microsecond=0)
            
            result = []
            for i, day in enumerate(days):
                day_start = monday + timedelta(days=i)
                day_end = day_start + timedelta(days=1)
                
                enroll_query = db.session.query(func.count(Enrollment.id)).filter(
                    Enrollment.enrolled_at >= day_start,
                    Enrollment.enrolled_at < day_end
                )
                if course_ids:
                    enroll_query = enroll_query.filter(Enrollment.course_id.in_(course_ids))
                enrollments_count = enroll_query.scalar() or 0
                
                result.append({
                    'day': day,
                    'views': enrollments_count,  # Using enrollments as proxy for activity
                    'completions': 0  # No completion tracking in current schema
                })
            
            return result
        
        # For superadmin - show platform stats
        if user_role == 'superadmin':
            total_users = User.query.count()
            total_courses = Courses.query.count()
            total_enrollments = Enrollment.query.count()
            total_videos = Video.query.count()
            total_revenue = db.session.query(func.sum(Enrollment.payment_amount)).scalar() or 0
            
            return jsonify({
                'stats': {
                    'totalUsers': total_users,
                    'totalCourses': total_courses,
                    'totalEnrollments': total_enrollments,
                    'totalVideos': total_videos,
                    'totalRevenue': float(total_revenue),
                    'role': 'superadmin'
                },
                'chartData': {
                    'monthly': get_monthly_data(),
                    'categories': get_category_distribution(),
                    'weekly': get_weekly_activity()
                }
            }), 200
        
        # For instructor - show their course stats
        if user_role in ['instructor', 'teacher'] and instructor_id:
            my_courses = Courses.query.filter_by(instructor_id=instructor_id).all()
            my_course_ids = [c.id for c in my_courses]
            
            # Count students enrolled in instructor's courses
            enrolled_students = Enrollment.query.filter(
                Enrollment.course_id.in_(my_course_ids)
            ).count() if my_course_ids else 0
            
            # Count videos in instructor's courses
            total_videos = Video.query.filter(
                Video.course_id.in_(my_course_ids)
            ).count() if my_course_ids else 0
            
            # Count topics in instructor's courses
            total_topics = Topic.query.filter(
                Topic.course_id.in_(my_course_ids)
            ).count() if my_course_ids else 0
            
            # Revenue from instructor's courses
            revenue = db.session.query(func.sum(Enrollment.payment_amount)).filter(
                Enrollment.course_id.in_(my_course_ids)
            ).scalar() or 0 if my_course_ids else 0
            
            return jsonify({
                'stats': {
                    'totalCourses': len(my_courses),
                    'totalStudents': enrolled_students,
                    'totalVideos': total_videos,
                    'totalTopics': total_topics,
                    'totalRevenue': float(revenue),
                    'role': 'instructor'
                },
                'chartData': {
                    'monthly': get_monthly_data(my_course_ids),
                    'categories': get_category_distribution(my_course_ids),
                    'weekly': get_weekly_activity(my_course_ids)
                }
            }), 200
        
        # For institute admin
        if user_role == 'institute_admin' and institute_id:
            from models.institute import Institute
            
            return jsonify({
                'stats': {
                    'totalCourses': Courses.query.count(),
                    'totalStudents': User.query.count(),
                    'totalVideos': Video.query.count(),
                    'role': 'institute_admin'
                },
                'chartData': {
                    'monthly': get_monthly_data(),
                    'categories': get_category_distribution(),
                    'weekly': get_weekly_activity()
                }
            }), 200
        
        return jsonify({'message': 'No analytics available for this role'}), 400
        
    except Exception as e:
        return jsonify({'message': f'Error: {str(e)}'}), 500


@admin_bp.route('/my-students', methods=['POST'])
@token_required
def get_my_students(current_user, user_role, institute_id, instructor_id):
    """Get students enrolled in instructor's courses"""
    try:
        data = request.get_json() or {}
        query_text = data.get('query', '')
        
        # For instructors - only show students in their courses
        if user_role in ['instructor', 'teacher'] and instructor_id:
            my_course_ids = [c.id for c in Courses.query.filter_by(instructor_id=instructor_id).all()]
            
            if not my_course_ids:
                return jsonify({'students': [], 'total': 0}), 200
            
            # Get unique user IDs enrolled in instructor's courses
            enrolled_user_ids = db.session.query(Enrollment.user_id).filter(
                Enrollment.course_id.in_(my_course_ids)
            ).distinct().all()
            enrolled_user_ids = [u[0] for u in enrolled_user_ids]
            
            # Get user details
            users_query = User.query.filter(User.id.in_(enrolled_user_ids))
            
            if query_text:
                users_query = users_query.filter(
                    or_(
                        User.fullname.ilike(f'%{query_text}%'),
                        User.email.ilike(f'%{query_text}%')
                    )
                )
            
            users = users_query.limit(100).all()
            
            output = []
            for user in users:
                # Count enrollments for this user in instructor's courses
                enrollment_count = Enrollment.query.filter(
                    Enrollment.user_id == user.id,
                    Enrollment.course_id.in_(my_course_ids)
                ).count()
                
                output.append({
                    'id': user.id,
                    'fullname': user.fullname,
                    'email': user.email,
                    'profile_img_url': user.profile_img_url,
                    'enrolled_courses': enrollment_count
                })
            
            return jsonify({'students': output, 'total': len(enrolled_user_ids)}), 200
        
        # For other roles - return all users
        users = User.query.limit(100).all()
        output = [{
            'id': u.id,
            'fullname': u.fullname,
            'email': u.email,
            'profile_img_url': u.profile_img_url
        } for u in users]
        
        return jsonify({'students': output, 'total': User.query.count()}), 200
        
    except Exception as e:
        return jsonify({'message': f'Error: {str(e)}'}), 500


@admin_bp.route('/live-classes', methods=['POST'])
@token_required
def get_my_live_classes(current_user, user_role, institute_id, instructor_id):
    """Get live classes for the current user (filtered by instructor's courses)"""
    from models.institute import LiveClass
    
    try:
        data = request.get_json() or {}
        status_filter = data.get('status')
        
        query = LiveClass.query
        
        # For instructors, filter by their courses
        if user_role in ['instructor', 'teacher'] and instructor_id:
            my_course_ids = [c.id for c in Courses.query.filter_by(instructor_id=instructor_id).all()]
            if my_course_ids:
                query = query.filter(LiveClass.course_id.in_(my_course_ids))
            else:
                return jsonify({'live_classes': []}), 200
        
        if status_filter and status_filter != 'all':
            query = query.filter_by(status=status_filter)
        
        live_classes = query.order_by(LiveClass.scheduled_start_time.desc()).limit(50).all()
        
        output = []
        for lc in live_classes:
            course_title = None
            instructor_name = None
            
            if lc.course_id:
                course = db.session.get(Courses, lc.course_id)
                if course:
                    course_title = course.title
            
            if lc.instructor_id:
                instructor = db.session.get(Instructor, lc.instructor_id)
                if instructor:
                    instructor_name = instructor.name
            
            # Calculate duration from start and end times
            duration = 60
            if lc.scheduled_start_time and lc.scheduled_end_time:
                delta = lc.scheduled_end_time - lc.scheduled_start_time
                duration = int(delta.total_seconds() / 60)
            
            output.append({
                'id': lc.id,
                'title': lc.title,
                'course_title': course_title,
                'instructor_name': instructor_name,
                'scheduled_at': lc.scheduled_start_time.isoformat() if lc.scheduled_start_time else None,
                'duration_minutes': duration,
                'status': lc.status or 'scheduled',
                'participant_count': 0,  # Not in current schema
                'max_participants': lc.max_participants,
                'meeting_url': f"https://meet.jit.si/{lc.jitsi_room_name}" if lc.jitsi_room_name else None
            })
        
        return jsonify({'live_classes': output}), 200
    except Exception as e:
        return jsonify({'message': f'Error: {str(e)}'}), 500


@admin_bp.route('/qa', methods=['POST'])
@token_required
def get_my_qa(current_user, user_role, institute_id, instructor_id):
    """Get Q&A questions for current user (filtered by instructor's courses)"""
    from models.institute import QAQuestion
    
    try:
        data = request.get_json() or {}
        search_query = data.get('query', '')
        status = data.get('status')
        
        query = QAQuestion.query
        
        # For instructors, filter by their courses
        if user_role in ['instructor', 'teacher'] and instructor_id:
            my_course_ids = [c.id for c in Courses.query.filter_by(instructor_id=instructor_id).all()]
            if my_course_ids:
                query = query.filter(QAQuestion.course_id.in_(my_course_ids))
            else:
                return jsonify({'questions': []}), 200
        
        if search_query:
            query = query.filter(QAQuestion.question_text.ilike(f'%{search_query}%'))
        
        if status and status != 'all':
            query = query.filter_by(status=status)
        
        questions = query.order_by(QAQuestion.created_at.desc()).limit(100).all()
        
        output = []
        for q in questions:
            user = db.session.get(User, q.user_id)
            user_name = user.fullname if user else 'Unknown'
            
            course_title = None
            if q.course_id:
                course = db.session.get(Courses, q.course_id)
                if course:
                    course_title = course.title
            
            output.append({
                'id': q.id,
                'user_id': q.user_id,
                'user_name': user_name,
                'course_id': q.course_id,
                'course_title': course_title,
                'question_text': q.question_text,
                'status': q.status or 'pending',
                'answers_count': q.answers_count or 0,
                'created_at': q.created_at.isoformat() if q.created_at else None
            })
        
        return jsonify({'questions': output}), 200
    except Exception as e:
        return jsonify({'message': f'Error: {str(e)}'}), 500


# ==========================================
# LIVE CLASS MANAGEMENT ROUTES
# ==========================================

@admin_bp.route('/live-classes/start-now', methods=['POST'])
@token_required
def start_class_now(current_user, user_role, institute_id, instructor_id):
    """Start an instant live class"""
    from models.institute import LiveClass
    from datetime import datetime, timedelta
    import uuid
    
    try:
        data = request.get_json() or {}
        title = data.get('title', 'Live Class')
        description = data.get('description', '')
        course_id = data.get('course_id')
        duration_minutes = data.get('duration_minutes', 60)
        
        if not course_id:
            return jsonify({'message': 'Course ID is required'}), 400
        
        # Verify instructor owns this course
        if user_role in ['instructor', 'teacher'] and instructor_id:
            course = Courses.query.filter_by(id=course_id, instructor_id=instructor_id).first()
            if not course:
                return jsonify({'message': 'You can only start classes for your own courses'}), 403
            assigned_instructor_id = instructor_id
        else:
            course = db.session.get(Courses, course_id)
            assigned_instructor_id = course.instructor_id if course else None
        
        if not course:
            return jsonify({'message': 'Course not found'}), 404
        
        # Generate unique Jitsi room name
        room_suffix = str(uuid.uuid4())[:8]
        jitsi_room_name = f"ashlya-{course_id}-{room_suffix}"
        
        now = datetime.now()
        end_time = now + timedelta(minutes=duration_minutes)
        
        new_class = LiveClass(
            title=title,
            description=description,
            course_id=course_id,
            instructor_id=assigned_instructor_id,
            scheduled_start_time=now,
            scheduled_end_time=end_time,
            jitsi_room_name=jitsi_room_name,
            status='live',
            max_participants=100,
            recording_enabled=True
        )
        
        db.session.add(new_class)
        db.session.commit()
        
        return jsonify({
            'live_class': {
                'id': new_class.id,
                'title': new_class.title,
                'jitsi_room_name': new_class.jitsi_room_name,
                'meeting_url': f"https://meet.jit.si/{jitsi_room_name}",
                'status': 'live',
                'course_title': course.title,
                'scheduled_start_time': now.isoformat(),
                'duration_minutes': duration_minutes
            }
        }), 201
        
    except Exception as e:
        db.session.rollback()
        return jsonify({'message': f'Error starting class: {str(e)}'}), 500


@admin_bp.route('/live-classes/schedule', methods=['POST'])
@token_required
def schedule_class(current_user, user_role, institute_id, instructor_id):
    """Schedule a future live class"""
    from models.institute import LiveClass
    from datetime import datetime
    import uuid
    
    try:
        data = request.get_json() or {}
        title = data.get('title')
        description = data.get('description', '')
        course_id = data.get('course_id')
        scheduled_date = data.get('scheduled_date')  # YYYY-MM-DD
        scheduled_time = data.get('scheduled_time')  # HH:MM
        duration_minutes = data.get('duration_minutes', 60)
        
        if not title or not course_id or not scheduled_date or not scheduled_time:
            return jsonify({'message': 'Title, course_id, scheduled_date, and scheduled_time are required'}), 400
        
        # Verify instructor owns this course
        if user_role in ['instructor', 'teacher'] and instructor_id:
            course = Courses.query.filter_by(id=course_id, instructor_id=instructor_id).first()
            if not course:
                return jsonify({'message': 'You can only schedule classes for your own courses'}), 403
            assigned_instructor_id = instructor_id
        else:
            course = db.session.get(Courses, course_id)
            assigned_instructor_id = course.instructor_id if course else None
        
        if not course:
            return jsonify({'message': 'Course not found'}), 404
        
        # Parse datetime
        try:
            start_time = datetime.strptime(f"{scheduled_date} {scheduled_time}", "%Y-%m-%d %H:%M")
        except ValueError:
            return jsonify({'message': 'Invalid date/time format. Use YYYY-MM-DD and HH:MM'}), 400
        
        from datetime import timedelta
        end_time = start_time + timedelta(minutes=duration_minutes)
        
        # Generate unique Jitsi room name
        room_suffix = str(uuid.uuid4())[:8]
        jitsi_room_name = f"ashlya-{course_id}-{room_suffix}"
        
        new_class = LiveClass(
            title=title,
            description=description,
            course_id=course_id,
            instructor_id=assigned_instructor_id,
            scheduled_start_time=start_time,
            scheduled_end_time=end_time,
            jitsi_room_name=jitsi_room_name,
            status='scheduled',
            max_participants=100,
            recording_enabled=True
        )
        
        db.session.add(new_class)
        db.session.commit()
        
        return jsonify({
            'live_class': {
                'id': new_class.id,
                'title': new_class.title,
                'jitsi_room_name': new_class.jitsi_room_name,
                'meeting_url': f"https://meet.jit.si/{jitsi_room_name}",
                'status': 'scheduled',
                'course_title': course.title,
                'scheduled_start_time': start_time.isoformat(),
                'scheduled_end_time': end_time.isoformat(),
                'duration_minutes': duration_minutes
            }
        }), 201
        
    except Exception as e:
        db.session.rollback()
        return jsonify({'message': f'Error scheduling class: {str(e)}'}), 500


@admin_bp.route('/live-classes/<int:class_id>/start', methods=['POST'])
@token_required
def start_scheduled_class(current_user, user_role, institute_id, instructor_id, class_id):
    """Start a scheduled class (change status to live)"""
    from models.institute import LiveClass
    from datetime import datetime
    
    try:
        live_class = db.session.get(LiveClass, class_id)
        if not live_class:
            return jsonify({'message': 'Live class not found'}), 404
        
        # Verify ownership
        if user_role in ['instructor', 'teacher'] and instructor_id:
            if live_class.instructor_id != instructor_id:
                return jsonify({'message': 'You can only start your own classes'}), 403
        
        live_class.status = 'live'
        live_class.actual_start_time = datetime.now()
        db.session.commit()
        
        return jsonify({
            'message': 'Class started successfully',
            'live_class': {
                'id': live_class.id,
                'status': 'live',
                'meeting_url': f"https://meet.jit.si/{live_class.jitsi_room_name}"
            }
        }), 200
        
    except Exception as e:
        db.session.rollback()
        return jsonify({'message': f'Error: {str(e)}'}), 500


@admin_bp.route('/live-classes/<int:class_id>/end', methods=['POST'])
@token_required
def end_class(current_user, user_role, institute_id, instructor_id, class_id):
    """End a live class"""
    from models.institute import LiveClass
    from datetime import datetime
    
    try:
        data = request.get_json() or {}
        recording_url = data.get('recording_url')
        
        live_class = db.session.get(LiveClass, class_id)
        if not live_class:
            return jsonify({'message': 'Live class not found'}), 404
        
        # Verify ownership
        if user_role in ['instructor', 'teacher'] and instructor_id:
            if live_class.instructor_id != instructor_id:
                return jsonify({'message': 'You can only end your own classes'}), 403
        
        live_class.status = 'completed'
        live_class.actual_end_time = datetime.now()
        if recording_url:
            live_class.recording_url = recording_url
        
        db.session.commit()
        
        return jsonify({
            'message': 'Class ended successfully',
            'live_class': {
                'id': live_class.id,
                'status': 'completed'
            }
        }), 200
        
    except Exception as e:
        db.session.rollback()
        return jsonify({'message': f'Error: {str(e)}'}), 500


@admin_bp.route('/live-classes/<int:class_id>/details', methods=['GET'])
@token_required
def get_class_details(current_user, user_role, institute_id, instructor_id, class_id):
    """Get details of a specific live class"""
    from models.institute import LiveClass
    
    try:
        live_class = db.session.get(LiveClass, class_id)
        if not live_class:
            return jsonify({'message': 'Live class not found'}), 404
        
        # Get course and instructor details
        course = db.session.get(Courses, live_class.course_id)
        instructor = db.session.get(Instructor, live_class.instructor_id)
        
        return jsonify({
            'id': live_class.id,
            'title': live_class.title,
            'description': live_class.description,
            'jitsi_room_name': live_class.jitsi_room_name,
            'meeting_url': f"https://meet.jit.si/{live_class.jitsi_room_name}",
            'status': live_class.status,
            'scheduled_start_time': live_class.scheduled_start_time.isoformat() if live_class.scheduled_start_time else None,
            'scheduled_end_time': live_class.scheduled_end_time.isoformat() if live_class.scheduled_end_time else None,
            'max_participants': live_class.max_participants or 100,
            'participant_count': 0,
            'recording_enabled': live_class.recording_enabled,
            'recording_url': live_class.recording_url,
            'course': {
                'title': course.title if course else 'Unknown',
                'description': course.description if course else ''
            },
            'instructor': {
                'name': instructor.name if instructor else 'Unknown',
                'email': ''
            }
        }), 200
        
    except Exception as e:
        return jsonify({'message': f'Error: {str(e)}'}), 500


@admin_bp.route('/instructor-courses', methods=['POST'])
@token_required
def get_instructor_courses(current_user, user_role, institute_id, instructor_id):
    """Get courses for the current instructor (for dropdown selection)"""
    try:
        if user_role in ['instructor', 'teacher'] and instructor_id:
            courses = Courses.query.filter_by(instructor_id=instructor_id).all()
        else:
            # Superadmin sees all courses
            courses = Courses.query.limit(100).all()
        
        output = [{
            'id': c.id,
            'title': c.title,
            'image_url': c.image_url
        } for c in courses]
        
        return jsonify({'courses': output}), 200
        
    except Exception as e:
        return jsonify({'message': f'Error: {str(e)}'}), 500


@admin_bp.route('/live-classes/<int:class_id>/jwt', methods=['GET'])
@token_required
def get_meeting_jwt(current_user, user_role, institute_id, instructor_id, class_id):
    """Generate JWT token for JaaS authenticated meeting"""
    from models.institute import LiveClass
    
    try:
        live_class = db.session.get(LiveClass, class_id)
        if not live_class:
            return jsonify({'message': 'Live class not found'}), 404
        
        # Check if user is the instructor (moderator)
        is_moderator = False
        if user_role in ['superadmin', 'admin']:
            is_moderator = True
        elif user_role in ['instructor', 'teacher'] and instructor_id:
            is_moderator = live_class.instructor_id == instructor_id
        
        # Get user info
        user_name = current_user.fullname or current_user.email or 'User'
        user_email = current_user.email or ''
        
        try:
            from utils.jaas_jwt import generate_jaas_jwt, get_jaas_meeting_url, JAAS_CONFIG
            
            jwt_token = generate_jaas_jwt(
                room_name=live_class.jitsi_room_name,
                user_name=user_name,
                user_email=user_email,
                user_id=str(current_user.id),
                is_moderator=is_moderator,
                features={
                    'recording': 'true' if is_moderator else 'false',
                    'livestreaming': 'false',
                    'transcription': 'false'
                }
            )
            
            meeting_url = get_jaas_meeting_url(live_class.jitsi_room_name, jwt_token)
            
            return jsonify({
                'jwt': jwt_token,
                'meeting_url': meeting_url,
                'room_name': live_class.jitsi_room_name,
                'is_moderator': is_moderator,
                'app_id': JAAS_CONFIG['app_id']
            }), 200
            
        except Exception as jwt_error:
            # Fallback to meet.jit.si if JaaS not configured
            return jsonify({
                'jwt': None,
                'meeting_url': f"https://meet.jit.si/{live_class.jitsi_room_name}",
                'room_name': live_class.jitsi_room_name,
                'is_moderator': is_moderator,
                'error': f'JaaS not configured: {str(jwt_error)}'
            }), 200
        
    except Exception as e:
        return jsonify({'message': f'Error: {str(e)}'}), 500

# ==========================================
# INSTITUTE STUDENTS MAP
# ==========================================

@admin_bp.route('/institute/students', methods=['POST'])
@token_required
def get_institute_students(current_user, user_role, institute_id=None, instructor_id=None):
    """Get all students enrolled in the institute with their stats"""
    try:
        from models.institute import Enrollment
        from models.user import User
        from datetime import datetime
        import urllib.parse as urlparse
        
        data = request.json or {}
        search_query = data.get('query', '')
        course_id = data.get('course_id')

        # Find distinct students who have enrolled in courses belonging to this institute
        query = db.session.query(
            User.id,
            User.fullname.label('name'),
            User.email,
            User.profile_img_url,
            db.func.count(Enrollment.id).label('enrolled_courses'),
            db.func.min(Enrollment.enrolled_at).label('enrollment_date')
        ).join(Enrollment, User.id == Enrollment.user_id)
        
        if institute_id:
            query = query.filter(Enrollment.institute_id == institute_id)
            
        if search_query:
            search_query = urlparse.unquote(search_query).lower()
            query = query.filter(db.or_(
                User.fullname.ilike(f'%{search_query}%'),
                User.email.ilike(f'%{search_query}%')
            ))
            
        if course_id:
            query = query.filter(Enrollment.course_id == course_id)
            
        results = query.group_by(User.id).all()
        
        students = []
        for r in results:
            students.append({
                'id': r.id,
                'user_id': r.id,
                'name': r.name,
                'email': r.email,
                'profile_image_url': r.profile_img_url,
                'enrolled_courses': r.enrolled_courses,
                'completed_courses': 0, # Mocking completion stats for now
                'enrollment_date': r.enrollment_date.isoformat() if r.enrollment_date else datetime.utcnow().isoformat(),
                'last_activity': None
            })
            
        return jsonify({'students': students}), 200
    except Exception as e:
        return jsonify({'error': str(e)}), 500
