from django.shortcuts import render
from django.contrib.auth.decorators import login_required
from django.db.models import Q
from exams.models_flow import FlowDefinition

@login_required(login_url="portal-login")
def portal_sharjeel_library(request):
    # Fetch all published Sharjeel flows
    flows = FlowDefinition.objects.filter(
        lesson_type='FLOW', 
        status='PUBLISHED'
    ).exclude(sharjeel_mode='').select_related('teacher').order_by('-created_at')

    # Filter: Only show flows shared with academy OR created by the current user
    user_flows = flows.filter(
        Q(is_shared_with_academy=True) | Q(teacher=request.user)
    )

    # Structure the data hierarchically (Mode -> Student Code -> Subject -> Flows)
    library_data = {
        'MEMORIZE': {},
        'UNDERSTAND': {},
        'CUSTOM': {}
    }

    for f in user_flows:
        mode = f.sharjeel_mode if f.sharjeel_mode in library_data else 'CUSTOM'
        
        # Extract student code safely
        student_code = "Teacher/Admin"
        if hasattr(f.teacher, 'student_profile'):
            student_code = f.teacher.student_profile.code
        elif hasattr(f.teacher, 'student'):
            student_code = f.teacher.student.code
            
        subject = f.subject or 'General'

        if student_code not in library_data[mode]:
            library_data[mode][student_code] = {}
        
        if subject not in library_data[mode][student_code]:
            library_data[mode][student_code][subject] = []
            
        library_data[mode][student_code][subject].append(f)

    context = {
        'library_data': library_data,
        'is_teacher': request.user.is_staff or request.user.is_superuser,
    }
    return render(request, 'exams/portal_sharjeel_library.html', context)
