"""Workshop views -- One-Way Glass (MDD Phase 2)."""
from django.contrib import messages
from django.contrib.auth.views import redirect_to_login
from django.core.exceptions import PermissionDenied
from django.db.models import Count, Exists, OuterRef, Q
from django.shortcuts import render, get_object_or_404, redirect
from django.utils import timezone
from exams.kc_firewall import _sanctioned_view


def staff_only(view):
    """Staff/superuser only. Anonymous -> /login/. Non-staff -> 403."""
    def _wrapper(request, *args, **kwargs):
        if not request.user.is_authenticated:
            return redirect_to_login(request.get_full_path(), '/login/')
        if not (request.user.is_staff or request.user.is_superuser):
            raise PermissionDenied('Workshop is staff-only.')
        return view(request, *args, **kwargs)
    _wrapper.__name__ = getattr(view, '__name__', 'wrapped')
    _wrapper.__doc__ = getattr(view, '__doc__', None)
    return _wrapper


@staff_only
def dashboard(request):
    from .models import ConceptScaffold, QuestionBlueprint, SystemImprovementTask
    from exams.models import KnowledgeComponent
    stats = {
        'pending_tasks': SystemImprovementTask.objects.filter(status='PENDING').count(),
        'approved_tasks': SystemImprovementTask.objects.filter(status='APPROVED').count(),
        'rejected_tasks': SystemImprovementTask.objects.filter(status='REJECTED').count(),
        'scaffolds_pending': ConceptScaffold.objects.filter(is_approved=False).count(),
        'scaffolds_approved': ConceptScaffold.objects.filter(is_approved=True).count(),
        'blueprints_active': QuestionBlueprint.objects.filter(is_active=True).count(),
        'blueprints_inactive': QuestionBlueprint.objects.filter(is_active=False).count(),
        'kcs_total': KnowledgeComponent.objects.count(),
    }
    return render(request, 'workshop/dashboard.html', {'stats': stats})


@staff_only
def review_queue_list(request):
    from .models import SystemImprovementTask
    status = request.GET.get('status', 'PENDING')
    if status not in ('PENDING', 'APPROVED', 'REJECTED'):
        status = 'PENDING'
    tasks = SystemImprovementTask.objects.filter(status=status).select_related(
        'student', 'kc', 'reviewed_by')[:200]
    return render(request, 'workshop/review_queue.html',
                  {'tasks': tasks, 'current_status': status})


@staff_only
def review_task_detail(request, pk):
    from .models import SystemImprovementTask
    task = get_object_or_404(SystemImprovementTask, pk=pk)
    if request.method == 'POST':
        if task.submitted_by == request.user:
            from django.contrib import messages
            messages.error(request, '4-Eyes Principle: You cannot approve your own submission. Another staff member must review this.')
            return redirect('workshop:review-detail', pk=task.pk)

        action = request.POST.get('action', '').strip()
        notes = request.POST.get('review_notes', '').strip()
        transitions = {'approve': 'APPROVED', 'reject': 'REJECTED', 'reopen': 'PENDING'}
        if action not in transitions:
            messages.error(request, 'Unknown action.')
            return redirect('workshop:review-detail', pk=pk)
        task.status = transitions[action]
        task.reviewed_by = request.user
        task.review_notes = notes
        task.reviewed_at = timezone.now() if action != 'reopen' else None
        task.save()
        messages.success(request, f'Task #{task.pk} -> {task.status}')
        return redirect('workshop:review-detail', pk=pk)
    return render(request, 'workshop/review_detail.html', {'task': task})


@staff_only
def blueprint_list(request):
    from .models import ConceptScaffold, QuestionBlueprint  # noqa: F401
    from exams.models import KnowledgeComponent
    approved_subq = ConceptScaffold.objects.filter(kc=OuterRef('pk'), is_approved=True)
    kcs = KnowledgeComponent.objects.annotate(
        scaffold_approved=Exists(approved_subq),
        bp_count=Count('blueprints', distinct=True),
        bp_active_count=Count('blueprints', filter=Q(blueprints__is_active=True), distinct=True),
    ).order_by('code')[:300]
    return render(request, 'workshop/blueprint_list.html', {'kcs': kcs})



@staff_only
def blueprint_edit(request, kc_code):
    from .models import ConceptScaffold, QuestionBlueprint
    from exams.models import KnowledgeComponent
    from .services.ai_prompt import build_prompt
    from .services.ai_parse import parse_response

    kc = get_object_or_404(KnowledgeComponent, code=kc_code)
    scaffold, _ = ConceptScaffold.objects.get_or_create(
        kc=kc, defaults={'roman_urdu_intro': '', 'is_approved': False})
    blueprints = QuestionBlueprint.objects.filter(kc=kc).order_by('stage', 'difficulty_tier')

    if request.method == 'POST':
        action = request.POST.get('action', '').strip()

        def _parse_vocab(text):
            out = {}
            for line in text.splitlines():
                line = line.strip()
                if not line or '=' not in line:
                    continue
                k, _, v = line.partition('=')
                k, v = k.strip(), v.strip()
                if k:
                    out[k] = v
            return out

        def _parse_lines(text):
            return [ln.strip() for ln in text.splitlines() if ln.strip()]

        if action in ('save_scaffold', 'save_and_approve'):
            scaffold.roman_urdu_intro = request.POST.get('roman_urdu_intro', '').strip()
            scaffold.vocabulary_bridge = _parse_vocab(request.POST.get('vocabulary_bridge', ''))
            scaffold.socratic_hints_ur = _parse_lines(request.POST.get('socratic_hints_ur', ''))
            if action == 'save_and_approve':
                scaffold.is_approved = True
            scaffold.save()
            msg = 'Scaffold saved'
            if action == 'save_and_approve':
                msg += ' and approved'
            messages.success(request, msg)
            return redirect('workshop:blueprint-edit', kc_code=kc_code)

        if action == 'toggle_approve':
            scaffold.is_approved = not scaffold.is_approved
            scaffold.save(update_fields=['is_approved', 'updated_at'])
            messages.success(request,
                f'Scaffold {"approved" if scaffold.is_approved else "unapproved"}.')
            return redirect('workshop:blueprint-edit', kc_code=kc_code)

        if action == 'toggle_blueprint':
            bp_id = request.POST.get('bp_id')
            bp = QuestionBlueprint.objects.filter(pk=bp_id, kc=kc).first()
            if bp is None:
                messages.error(request, 'Blueprint not found for this KC.')
            else:
                bp.is_active = not bp.is_active
                bp.save(update_fields=['is_active', 'updated_at'])
                messages.success(request,
                    f'Blueprint {bp.get_stage_display()}/{bp.get_question_type_display()} T{bp.difficulty_tier} is now {"active" if bp.is_active else "inactive"}.')
            return redirect('workshop:blueprint-edit', kc_code=kc_code)

        if action == 'parse_ai_response':
            raw = request.POST.get('ai_response', '').strip()
            if not raw:
                messages.error(request, 'Paste the AI response first.')
                return redirect('workshop:blueprint-edit', kc_code=kc_code)
            try:
                data = parse_response(raw)
            except Exception as exc:
                messages.error(request, f'Could not parse AI response: {exc}')
                return redirect('workshop:blueprint-edit', kc_code=kc_code)
            filled = []
            if data.get('roman_urdu_intro'):
                scaffold.roman_urdu_intro = data['roman_urdu_intro']
                filled.append('intro')
            if data.get('vocabulary_bridge'):
                scaffold.vocabulary_bridge = data['vocabulary_bridge']
                filled.append('vocab')
            if data.get('socratic_hints_ur'):
                scaffold.socratic_hints_ur = data['socratic_hints_ur']
                filled.append('hints')
            if filled:
                scaffold.is_approved = False
                scaffold.save()
                messages.success(request,
                    f'Filled from AI response: {", ".join(filled)}. Review and Save.')
            else:
                messages.warning(request, 'No usable fields found in AI response.')
            return redirect('workshop:blueprint-edit', kc_code=kc_code)

        messages.error(request, 'Unknown action.')

    # Pre-format for rendering
    vocab_lines = '\n'.join(f'{k} = {v}' for k, v in (scaffold.vocabulary_bridge or {}).items())
    hints_lines = '\n'.join(scaffold.socratic_hints_ur or [])
    return render(request, 'workshop/blueprint_edit.html', {
        'kc': kc,
        'scaffold': scaffold,
        'blueprints': blueprints,
        'vocab_lines': vocab_lines,
        'hints_lines': hints_lines,
        'ai_prompt': build_prompt(kc),
    })






@staff_only
def kc_studio_list(request):
    """KC Studio — health-aware list of all Knowledge Components (Phase 2A).

    Read-only. Filters: ?health=empty|unapproved|approved  ?subject=  ?q=
    Guarded against ConceptScaffold missing (OneToOne; 4 KCs have none).
    """
    from exams.models import KnowledgeComponent, ModelQuestion
    from .models import ConceptScaffold, QuestionBlueprint

    health  = request.GET.get('health', '').strip().lower()
    subject = request.GET.get('subject', '').strip()
    q       = request.GET.get('q', '').strip()

    kcs_qs = KnowledgeComponent.objects.filter(superseded_at__isnull=True)
    if subject:
        kcs_qs = kcs_qs.filter(subject=subject)
    if q:
        kcs_qs = kcs_qs.filter(Q(code__icontains=q) | Q(title__icontains=q))

    scaffold_by_kc = {sc.kc_id: sc for sc in ConceptScaffold.objects.filter(kc__in=kcs_qs)}
    q_counts = dict(
        ModelQuestion.objects
        .filter(superseded_at__isnull=True, kc_code__in=kcs_qs.values_list('code', flat=True))
        .values('kc_code').annotate(n=Count('id')).values_list('kc_code', 'n')
    )
    bp_counts = dict(
        QuestionBlueprint.objects.filter(kc__in=kcs_qs)
        .values('kc_id').annotate(n=Count('id')).values_list('kc_id', 'n')
    )

    rows = []
    counts = {'all': 0, 'empty': 0, 'unapproved': 0, 'approved': 0}
    for kc in kcs_qs.order_by('subject', 'code').iterator():
        sc = scaffold_by_kc.get(kc.pk)
        if sc is None:
            status = 'empty'
        elif sc.is_approved:
            status = 'approved'
        else:
            status = 'unapproved'
        counts['all'] += 1
        counts[status] += 1
        if health and health != status:
            continue
        rows.append({
            'kc': kc,
            'scaffold': sc,
            'status': status,
            'q_count': q_counts.get(kc.code, 0),
            'bp_count': bp_counts.get(kc.pk, 0),
        })

    subjects = (
        KnowledgeComponent.objects
        .filter(superseded_at__isnull=True)
        .values_list('subject', flat=True).distinct().order_by('subject')
    )

    return render(request, 'workshop/kc_studio/kc_list.html', {
        'rows': rows,
        'counts': counts,
        'subjects': subjects,
        'active_health': health,
        'active_subject': subject,
        'active_q': q,
    })



@_sanctioned_view("workshop.kc_create")
@staff_only
def kc_create(request):
    """Phase 2B — Create a new KnowledgeComponent and auto-generate its Scaffold."""
    from exams.models import KnowledgeComponent
    from .models import ConceptScaffold
    from django.contrib import messages

    if request.method == 'POST':
        code = request.POST.get('code', '').strip()
        title = request.POST.get('title', '').strip()
        subject = request.POST.get('subject', '').strip()
        chapter = request.POST.get('chapter', '').strip()
        description = request.POST.get('description', '').strip()
        cognitive = request.POST.get('cognitive_level', '').strip()

        if not code or not title or not subject:
            messages.error(request, 'Code, Title, and Subject are required.')
        elif KnowledgeComponent.objects.filter(code=code).exists():
            messages.error(request, f'KC Code "{code}" already exists.')
        else:
            kc = KnowledgeComponent.objects.create(
                code=code, title=title, subject=subject,
                chapter=chapter, description=description,
                cognitive_level=cognitive, created_by=request.user
            )
            # Auto-create empty scaffold so OneToOne doesn't crash
            ConceptScaffold.objects.create(
                kc=kc, roman_urdu_intro=f'{title} kya hai? (Draft)'
            )
            messages.success(request, f'KC "{code}" created successfully.')
            return redirect('workshop:kc-studio-list')

    return render(request, 'workshop/kc_studio/kc_form.html', {
        'cognitive_choices': KnowledgeComponent.COGNITIVE_CHOICES
    })



@_sanctioned_view("workshop.kc_edit")
@staff_only
def kc_edit(request, kc_code):
    """Phase 2C — Full 10-tab Editor for KnowledgeComponent & Scaffold."""
    from exams.models import KnowledgeComponent
    from .models import ConceptScaffold
    from django.contrib import messages
    from django.db import transaction
    import json

    kc = get_object_or_404(KnowledgeComponent, code=kc_code)
    sc = getattr(kc, 'scaffold', None)

    def _get_json(field, default):
        try:
            raw = request.POST.get(field, '').strip()
            return json.loads(raw) if raw else default
        except Exception:
            messages.error(request, f'Invalid JSON in {field}. Save failed for this tab.')
            return None

    if request.method == 'POST':
        action = request.POST.get('action')
        
        with transaction.atomic():
            if action == 'identity':
                kc.title = request.POST.get('title', kc.title)
                kc.display_code = request.POST.get('display_code', '').strip()
                kc.subject = request.POST.get('subject', kc.subject)
                kc.chapter = request.POST.get('chapter', '')
                kc.description = request.POST.get('description', '')
                kc.cognitive_level = request.POST.get('cognitive_level', '')
                kc.save()
                messages.success(request, 'Identity tab saved.')
            
            elif action == 'scaffold':
                if not sc:
                    sc = ConceptScaffold.objects.create(kc=kc)
                sc.roman_urdu_intro = request.POST.get('roman_urdu_intro', '')
                
                vb = _get_json('vocabulary_bridge', {})
                if vb is not None: sc.vocabulary_bridge = vb
                
                sh = _get_json('socratic_hints_ur', [])
                if sh is not None: sc.socratic_hints_ur = sh
                
                sc.is_approved = request.POST.get('is_approved') == 'on'
                sc.save()
                messages.success(request, 'Scaffold tab saved.')

            elif action == 'workflow':
                kc.story_status = request.POST.get('story_status', kc.story_status)
                kc.ready_for_diagnosis = request.POST.get('ready_for_diagnosis') == 'on'
                kc.is_active = request.POST.get('is_active') == 'on'
                kc.teacher_approved = request.POST.get('teacher_approved') == 'on'
                kc.save()
                messages.success(request, 'Workflow tab saved.')

            elif action.startswith('json_'):
                # Handle the 7 JSON tabs
                field_map = {
                    'json_vocab': ('key_terms', []),
                    'json_prereq': ('prerequisite_kcs', []),
                    'json_story': ('story', []),
                    'json_misc': ('misconceptions', []),
                    'json_ladder': ('socratic_ladder', []),
                    'json_resources': ('resource_links', []),
                }
                if action in field_map:
                    field, default = field_map[action]
                    parsed = _get_json(field, default)
                    if parsed is not None:
                        setattr(kc, field, parsed)
                        kc.save()
                        messages.success(request, f'{field.replace("_", " ").title()} saved.')
                
                elif action == 'json_pokemon':
                    kc.monster_name = request.POST.get('monster_name', '')
                    kc.monster_type = request.POST.get('monster_type', '')
                    lore = _get_json('monster_lore', {})
                    if lore is not None:
                        kc.monster_lore = lore
                        kc.save()
                        messages.success(request, 'Pokemon lore saved.')

        return redirect('workshop:kc-edit', kc_code=kc.code)

    # Context setup (GET)
    ctx = {
        'kc': kc,
        'sc': sc,
        'cognitive_choices': KnowledgeComponent.COGNITIVE_CHOICES,
        'story_status_choices': KnowledgeComponent._meta.get_field('story_status').choices,
        'monster_type_choices': KnowledgeComponent._meta.get_field('monster_type').choices,
    }

    def _dump(val):
        return json.dumps(val, indent=2, ensure_ascii=False)

    ctx['vb_json'] = _dump(sc.vocabulary_bridge if sc else {})
    ctx['sh_json'] = _dump(sc.socratic_hints_ur if sc else [])
    ctx['kt_json'] = _dump(kc.key_terms)
    ctx['pre_json'] = _dump(kc.prerequisite_kcs)
    ctx['story_json'] = _dump(kc.story)
    ctx['misc_json'] = _dump(kc.misconceptions)
    ctx['ladder_json'] = _dump(kc.socratic_ladder)
    ctx['res_json'] = _dump(kc.resource_links)
    ctx['lore_json'] = _dump(kc.monster_lore)

    from exams.models import ModelQuestion
    ctx['questions'] = ModelQuestion.objects.filter(kc_code=kc.code).order_by('id')
    
    return render(request, 'workshop/kc_studio/kc_edit.html', ctx)





@_sanctioned_view("workshop.question_edit")
@staff_only
def question_edit(request, q_id=None, kc_code=None):
    """Phase 3B — Create or edit a ModelQuestion."""
    from exams.models import ModelQuestion, KnowledgeComponent
    from django.contrib import messages
    from django.db import transaction

    q = None
    if q_id:
        q = get_object_or_404(ModelQuestion, id=q_id)
        kc_code = q.kc_code
    
    current_kc = get_object_or_404(KnowledgeComponent, code=kc_code)

    if request.method == 'POST':
        text = request.POST.get('question_text', '').strip()
        ans = request.POST.get('model_answer', '').strip()
        marks = request.POST.get('marks', 1)
        new_kc_code = request.POST.get('kc_code', '').strip()
        is_superseded = request.POST.get('is_superseded') == 'on'

        if not text or not new_kc_code:
            messages.error(request, 'Question text and KC Code are required.')
        else:
            with transaction.atomic():
                if not q:
                    q = ModelQuestion()
                
                q.question_text = text
                q.model_answer = ans
                q.marks = marks
                q.kc_code = new_kc_code
                q.superseded_at = timezone.now() if is_superseded else None
                
                # Link to the KC object if it exists
                target_kc = KnowledgeComponent.objects.filter(code=new_kc_code).first()
                if target_kc:
                    q.kc = target_kc
                    
                q.save()
                messages.success(request, 'Question saved successfully.')
                
                # Redirect back to the KC that now owns this question
                return redirect('workshop:kc-edit', kc_code=new_kc_code)

    all_kcs = KnowledgeComponent.objects.filter(superseded_at__isnull=True).order_by('code')
    
    return render(request, 'workshop/kc_studio/question_form.html', {
        'q': q,
        'kc': current_kc,
        'all_kcs': all_kcs,
        'is_superseded': q.superseded_at is not None if q else False
    })



@_sanctioned_view("workshop.question_toggle")
@staff_only
def question_toggle(request, q_id):
    """Quick-toggle a question's archived status."""
    from exams.models import ModelQuestion
    from django.utils import timezone
    from django.contrib import messages
    
    q = get_object_or_404(ModelQuestion, id=q_id)
    
    if request.method == 'POST':
        if q.superseded_at:
            q.superseded_at = None
            messages.success(request, f'Question #{q.id} restored.')
        else:
            q.superseded_at = timezone.now()
            messages.success(request, f'Question #{q.id} archived.')
        q.save()
        
    return redirect('workshop:kc-edit', kc_code=q.kc_code)



@staff_only
def student_map_list(request):
    """Phase 4A — List all students to select for the Pipeline Map."""
    from exams.models import Student
    students = Student.objects.filter(is_active=True).order_by('code')
    return render(request, 'workshop/student_map/list.html', {'students': students})

@staff_only
def student_map_detail(request, student_code):
    """Phase 4A — Show the pipeline (Locks & Attempts) for a specific student."""
    from exams.models import Student, StudentQuestionLock, AttemptLog
    student = get_object_or_404(Student, code=student_code)
    
    # Get active locks
    locks = StudentQuestionLock.objects.filter(student=student, is_active=True).select_related('question')
    
    # Get attempts (ordered newest first)
    attempts = AttemptLog.objects.filter(student=student).select_related('question').order_by('-created_at')

    return render(request, 'workshop/student_map/detail.html', {
        'student': student,
        'locks': locks,
        'attempts': attempts,
    })



@_sanctioned_view("workshop.content_audit")
@staff_only
def content_audit(request):
    """Phase 6 — Publish Readiness Dashboard."""
    from exams.models import KnowledgeComponent, ModelQuestion
    from workshop.models import ConceptScaffold
    from django.db.models import Count

    kcs = KnowledgeComponent.objects.filter(superseded_at__isnull=True)
    
    # Prefetch relations for speed
    scaffold_by_kc = {sc.kc_id: sc for sc in ConceptScaffold.objects.filter(kc__in=kcs)}
    q_counts = dict(
        ModelQuestion.objects.filter(superseded_at__isnull=True, kc_code__in=kcs.values_list('code', flat=True))
        .values('kc_code').annotate(n=Count('id')).values_list('kc_code', 'n')
    )

    stats = {
        'total': kcs.count(),
        'ready': 0,
        'no_scaffold': 0,
        'unapproved_scaffold': 0,
        'no_story': 0,
        'no_questions': 0,
    }

    rows = []
    for kc in kcs.order_by('subject', 'code').iterator():
        sc = scaffold_by_kc.get(kc.pk)
        q_count = q_counts.get(kc.code, 0)
        has_story = bool(kc.story and len(kc.story) > 0)
        
        issues = []
        if not sc:
            issues.append('No Scaffold')
            stats['no_scaffold'] += 1
        elif not sc.is_approved:
            issues.append('Scaffold Unapproved')
            stats['unapproved_scaffold'] += 1
            
        if not has_story:
            issues.append('No Story')
            stats['no_story'] += 1
            
        if q_count == 0:
            issues.append('No Questions')
            stats['no_questions'] += 1

        is_ready = len(issues) == 0
        if is_ready:
            stats['ready'] += 1
        else:
            rows.append({
                'kc': kc,
                'issues': issues,
                'q_count': q_count,
                'subject': kc.subject
            })

    return render(request, 'workshop/content_audit.html', {
        'stats': stats,
        'unready_rows': rows,
    })


@staff_only
def subject_mastery_analytics(request):
    """Phase 7 — Subject Mastery & Struggle Heatmap."""
    from exams.models import AttemptLog, Student
    from django.db.models import Count, Avg, Q, F

    # 1. Subject Overall Stats
    subjects = AttemptLog.objects.filter(
        question__kc__isnull=False
    ).values(
        'question__kc__subject'
    ).annotate(
        total_attempts=Count('id'),
        avg_score=Avg('score'),
        avg_max=Avg('max_score'),
        pass_count=Count('id', filter=Q(outcome__icontains='PASS') or Q(score__gte=F('max_score') * 0.6))
    ).order_by('question__kc__subject')

    # Calculate percentages for subjects
    for s in subjects:
        if s['avg_max'] and s['avg_max'] > 0:
            s['avg_pct'] = round((float(s['avg_score'] or 0) / float(s['avg_max'] or 1)) * 100, 1)
        else:
            s['avg_pct'] = 0
        if s['total_attempts'] > 0:
            s['pass_pct'] = round((s['pass_count'] / s['total_attempts']) * 100, 1)
        else:
            s['pass_pct'] = 0

    # 2. Struggle KCs (Heatmap)
    # Find KCs with the most failed attempts
    struggle_kcs = AttemptLog.objects.filter(
        question__kc__isnull=False
    ).values(
        'question__kc__subject',
        'question__kc_code',
        'question__kc__title'
    ).annotate(
        total_attempts=Count('id'),
        fails=Count('id', filter=Q(outcome__icontains='FAIL') | Q(score__lt=F('max_score') * 0.6))
    ).filter(fails__gt=0).order_by('-fails')[:50]

    # Calculate failure rate for struggle KCs
    for kc in struggle_kcs:
        if kc['total_attempts'] > 0:
            kc['fail_pct'] = round((kc['fails'] / kc['total_attempts']) * 100, 1)
        else:
            kc['fail_pct'] = 0

    return render(request, 'workshop/analytics.html', {
        'subjects': subjects,
        'struggle_kcs': struggle_kcs,
        'total_attempts': AttemptLog.objects.count(),
    })


@staff_only
def pokemon_workshop(request):
    """Phase 8 — Monster Dex (Pokemon Workshop)."""
    from exams.models import KnowledgeComponent
    
    # Filter for KCs that have a monster assigned vs not
    filter_type = request.GET.get('filter', 'all')
    
    kcs = KnowledgeComponent.objects.filter(superseded_at__isnull=True)
    
    if filter_type == 'assigned':
        kcs = kcs.exclude(monster_name='').exclude(monster_name__isnull=True)
    elif filter_type == 'empty':
        kcs = kcs.filter(monster_name='')
        
    kcs = kcs.order_by('subject', 'code')
    
    # Counts for the header
    total = KnowledgeComponent.objects.filter(superseded_at__isnull=True).count()
    assigned = KnowledgeComponent.objects.filter(superseded_at__isnull=True).exclude(monster_name='').exclude(monster_name__isnull=True).count()
    empty = total - assigned
    
    return render(request, 'workshop/pokemon_workshop.html', {
        'kcs': kcs,
        'filter_type': filter_type,
        'total': total,
        'assigned': assigned,
        'empty': empty,
    })



@staff_only
def teacher_upload_hub(request):
    """Landing — list all active students for physical test uploads."""
    from exams.models import Student
    from django.db.models import Count, Q
    students = Student.objects.filter(is_active=True).annotate(
        lock_count=Count('question_locks', filter=Q(question_locks__is_active=True))
    ).order_by('code')
    return render(request, 'workshop/teacher_upload_hub.html', {'students': students})


@staff_only
def teacher_upload_student(request, student_id):
    """Per-student upload page — single + bulk options."""
    from exams.models import Student, StudentQuestionLock
    student = get_object_or_404(Student, id=student_id)
    locks = StudentQuestionLock.objects.filter(
        student=student, is_active=True
    ).select_related('question', 'question__paper', 'question__kc').order_by('-locked_at')
    return render(request, 'workshop/teacher_upload_student.html', {
        'student': student, 'locks': locks,
    })



@staff_only
def upload_keys_hub(request):
    """List students + their active upload keys."""
    from exams.models import Student
    from exams.models_delegation import TaskDelegation
    from django.utils import timezone as tz

    students = Student.objects.filter(is_active=True).order_by('code')
    active_keys = TaskDelegation.objects.filter(
        task_type__in=['QUESTION_UPLOAD', 'PAPER_UPLOAD'],
        expires_at__gt=tz.now(),
    ).select_related('assignee')

    key_map = {}
    for k in active_keys:
        key_map.setdefault(k.assignee_id, []).append(k)

    rows = []
    for s in students:
        user = s.student_user
        keys = key_map.get(user.id, []) if user else []
        rows.append({'student': s, 'user': user, 'keys': keys})

    return render(request, 'workshop/upload_keys_hub.html', {'rows': rows})


@staff_only
def upload_keys_grant(request, student_id):
    """Grant a QUESTION_UPLOAD and/or PAPER_UPLOAD key to a student."""
    from exams.models import Student
    from exams.models_delegation import TaskDelegation
    from django.contrib import messages
    from django.utils import timezone as tz
    from datetime import timedelta

    if request.method != 'POST':
        return redirect('workshop:upload-keys-hub')

    student = get_object_or_404(Student, id=student_id)
    if not student.student_user:
        messages.error(request, f'{student.code} has no linked user account.')
        return redirect('workshop:upload-keys-hub')

    scope = request.POST.get('scope', 'single')
    hours = float(request.POST.get('hours', 2))
    delegation_mode = request.POST.get('delegation_mode', 'INDIVIDUAL').strip().upper()
    if delegation_mode not in ('INDIVIDUAL', 'CHOICE'):
        delegation_mode = 'INDIVIDUAL'

    types = []
    if scope == 'single': types = ['QUESTION_UPLOAD']
    elif scope == 'bulk': types = ['PAPER_UPLOAD']
    elif scope == 'both': types = ['QUESTION_UPLOAD', 'PAPER_UPLOAD']

    # Optional use-count override (default 1 = one upload per grant)
    try:
        _uses_count = int(request.POST.get('uses', '1'))
        if _uses_count < 1: _uses_count = 1
        if _uses_count > 20: _uses_count = 20
    except (ValueError, TypeError):
        _uses_count = 1

    expires = tz.now() + timedelta(hours=hours)

    for t in types:
        TaskDelegation.objects.create(
            assignee=student.student_user,
            task_type=t,
            expires_at=expires,
            created_by=request.user,
            notes=f'Granted via Workshop for {hours}h · {delegation_mode}',
            delegation_mode=delegation_mode,
            target_class=student.student_class or 'ALL',
            uses_remaining=_uses_count,
        )

    messages.success(request, f'✅ {scope.upper()} upload key granted to {student.code} for {hours}h.')
    return redirect('workshop:upload-keys-hub')


@staff_only
def upload_keys_revoke(request, delegation_id):
    """Revoke a single delegation key."""
    from exams.models_delegation import TaskDelegation
    from django.contrib import messages

    if request.method != 'POST':
        return redirect('workshop:upload-keys-hub')

    try:
        d = TaskDelegation.objects.get(id=delegation_id)
        assignee = d.assignee.username
        d.delete()
        messages.success(request, f'✅ Revoked key for {assignee}.')
    except TaskDelegation.DoesNotExist:
        messages.warning(request, 'This key was already revoked or does not exist.')
    return redirect('workshop:upload-keys-hub')


@staff_only
def physical_pipeline_hub(request):
    """Unified Command Center for the Physical Test Pipeline."""
    from exams.models_delegation import TaskDelegation
    from exams.services import exam_queue
    from django.utils import timezone as tz

    active_keys = TaskDelegation.objects.filter(
        task_type__in=['QUESTION_UPLOAD', 'PAPER_UPLOAD'],
        expires_at__gt=tz.now(),
    ).count()

    try:
        snapshot = exam_queue.get_queue_snapshot()
        pending = snapshot['pending']
        pending_tokens = pending.count() if hasattr(pending, 'count') else len(pending)
    except Exception:
        pending_tokens = 0

    # PHASE 2e: Code publication status
    from exams.models import Student, StudentDailyCode
    from exams.models_day_mission import DailyCodeVisibility as _DCV3
    from django.utils import timezone as _tz3
    
    _today_e = _tz3.localdate()
    _vis_e = _DCV3.objects.filter(date=_today_e).first()
    _is_published = _vis_e.is_visible if _vis_e else False
    _published_at = _vis_e.published_at if _vis_e else None
    _published_by = _vis_e.published_by.username if (_vis_e and _vis_e.published_by) else None
    
    # Count students with codes set for today
    _active_9th = Student.objects.filter(is_active=True, student_class__startswith='9').count()
    _codes_today = StudentDailyCode.objects.filter(date=_today_e)
    _students_with_morning = sum(1 for c in _codes_today if (c.per_book_codes or {}).get('morning'))
    _students_with_evening = sum(1 for c in _codes_today if (c.per_book_codes or {}).get('evening'))
    
    return render(request, 'workshop/physical_pipeline_hub.html', {
        'active_keys': active_keys,
        'pending_tokens': pending_tokens,
        'pub_status': {
            'date': _today_e,
            'is_published': _is_published,
            'published_at': _published_at,
            'published_by': _published_by,
            'students_with_morning': _students_with_morning,
            'students_with_evening': _students_with_evening,
            'total_9th': _active_9th,
        },
    })


@staff_only
def pipeline_guide(request):
    from pathlib import Path
    from django.utils.safestring import mark_safe
    md_path = Path('/home/orkoworo/idealogy/api/PIPELINE_PHYSICAL_TEST.md')
    if not md_path.exists():
        return render(request, 'workshop/pipeline_guide.html', {'error': 'PIPELINE_PHYSICAL_TEST.md not found.', 'html_content': None, 'raw_content': ''})
    raw = md_path.read_text(encoding='utf-8')
    html_content = None
    error = None
    try:
        import markdown
        html_content = markdown.markdown(raw, extensions=['tables', 'fenced_code', 'nl2br'])
    except ImportError:
        error = 'markdown package not installed. Run: pip install markdown'
    return render(request, 'workshop/pipeline_guide.html', {'html_content': mark_safe(html_content) if html_content else None, 'raw_content': raw, 'error': error})


@staff_only
def workshop_pro_learning_hub(request):
    from exams.models_day_mission import QuestionReasoning
    from exams.models import ModelQuestion, ModelPaper
    from django.contrib import messages
    from django.shortcuts import redirect
    
    subjects = ModelPaper.objects.values_list('subject', flat=True).distinct().order_by('subject')
    selected_subject = request.GET.get('subject', '').strip()
    
    papers = []
    selected_paper_id = request.GET.get('paper_id', '').strip()
    
    if selected_subject:
        papers = ModelPaper.objects.filter(subject__iexact=selected_subject).order_by('title')
        
    questions = []
    qid = request.GET.get('qid', '').strip()
    
    if selected_paper_id:
        questions = ModelQuestion.objects.filter(paper_id=selected_paper_id).order_by('question_index')
        
    question = None
    steps = []
    if qid:
        question = ModelQuestion.objects.filter(id=qid).first()
        if question:
            steps = QuestionReasoning.objects.filter(question=question)

    # Handle POST to add/edit a step
    if request.method == 'POST' and question:
        action = request.POST.get('action')
        
        if action == 'bulk_manual':
            import json as _json
            step_numbers = request.POST.getlist('step_number[]')
            step_types = request.POST.getlist('step_type[]')
            stages_list = request.POST.getlist('stage[]')
            titles = request.POST.getlist('title[]')
            prompts = request.POST.getlist('prompt[]')
            options_list = request.POST.getlist('options[]')
            correct_answers = request.POST.getlist('correct_answer[]')
            explanations = request.POST.getlist('explanation[]')
            hints = request.POST.getlist('hint[]')
            
            count = 0
            for i in range(len(step_numbers)):
                if not step_numbers[i].strip():
                    continue
                
                opts = []
                opt_raw = options_list[i] if i < len(options_list) else ''
                if opt_raw.strip():
                    opt_raw_clean = opt_raw.strip().replace("'", '"')
                    try:
                        parsed = _json.loads(opt_raw_clean)
                        if isinstance(parsed, list):
                            opts = parsed
                    except Exception:
                        opts = [o.strip() for o in opt_raw.split(',') if o.strip()]
                
                QuestionReasoning.objects.update_or_create(
                    question=question, step_number=int(step_numbers[i]),
                    defaults={
                        'step_type': step_types[i] if i < len(step_types) else 'SHORT_TEXT',
                        'stage': stages_list[i] if i < len(stages_list) else 'ENGAGE',
                        'title': titles[i] if i < len(titles) else '',
                        'prompt': prompts[i] if i < len(prompts) else '',
                        'options': opts,
                        'correct_answer': correct_answers[i] if i < len(correct_answers) else '',
                        'explanation': explanations[i] if i < len(explanations) else '',
                        'hint': hints[i] if i < len(hints) else ''
                    }
                )
                count += 1
            messages.success(request, f"Successfully saved {count} steps.")
            
        elif action == 'ai_json':
            raw_json = request.POST.get('ai_json', '').strip()
            try:
                raw_json = re.sub(r'^```(?:json)?\s*', '', raw_json)
                raw_json = re.sub(r'\s*```$', '', raw_json)
                data = json.loads(raw_json)
                steps_data = data.get('steps', [])
                
                count = 0
                for s in steps_data:
                    QuestionReasoning.objects.update_or_create(
                        question=question, step_number=s.get('step_number'),
                        defaults={
                            'step_type': s.get('step_type', 'SHORT_TEXT'),
                            'stage': s.get('stage', 'ENGAGE'),
                            'title': s.get('title', ''),
                            'prompt': s.get('prompt', ''),
                            'options': s.get('options', []),
                            'correct_answer': s.get('correct_answer', ''),
                            'explanation': s.get('explanation', ''),
                            'hint': s.get('hint', '')
                        }
                    )
                    count += 1
                messages.success(request, f"Imported {count} steps from AI.")
            except Exception as e:
                messages.error(request, f"AI JSON Error: {str(e)}")

        return redirect(f"{request.path}?subject={selected_subject}&paper_id={selected_paper_id}&qid={qid}")

    return render(request, 'workshop/pro_learning_hub.html', {
        'subjects': subjects,
        'selected_subject': selected_subject,
        'papers': papers,
        'selected_paper_id': selected_paper_id,
        'questions': questions,
        'question': question, 
        'steps': steps
    })


@staff_only
def upload_keys_bulk_grant(request):
    if request.POST.get('task_type') == 'CHOICE':
        request.POST = request.POST.copy()
        request.POST['task_type'] = 'QUESTION_UPLOAD'
        request.POST['delegation_mode'] = 'CHOICE'
    """Bulk grant upload keys to a scope: Class / Class+Shift / Shift / ALL.

    Skips students who already have an active key of the same type.
    """
    from exams.models import Student
    from exams.models_delegation import TaskDelegation
    from django.contrib import messages
    from django.utils import timezone as tz
    from datetime import timedelta

    if request.method != 'POST':
        return redirect('workshop:upload-keys-hub')

    scope = (request.POST.get('scope') or 'CLASS').strip().upper()
    target_class = (request.POST.get('target_class') or '').strip()
    target_shift = (request.POST.get('target_shift') or '').strip().lower()
    task_type = (request.POST.get('task_type') or 'QUESTION_UPLOAD').strip()

    if task_type not in ('QUESTION_UPLOAD', 'PAPER_UPLOAD'):
        messages.error(request, 'Invalid task type.')
        return redirect('workshop:upload-keys-hub')

    # FIX: read delegation_mode from POST (set to CHOICE by block above when user picks "Choice")
    delegation_mode = (request.POST.get('delegation_mode') or 'INDIVIDUAL').strip().upper()
    if delegation_mode not in ('INDIVIDUAL', 'CHOICE'):
        delegation_mode = 'INDIVIDUAL'

    try:
        hours = float(request.POST.get('hours', '2'))
    except (ValueError, TypeError):
        hours = 2.0
    try:
        uses_count = int(request.POST.get('uses', '1'))
        if uses_count < 1: uses_count = 1
        if uses_count > 20: uses_count = 20
    except (ValueError, TypeError):
        uses_count = 1

    students = Student.objects.filter(is_active=True)
    if scope == 'CLASS':
        if not target_class:
            messages.error(request, 'Class required.')
            return redirect('workshop:upload-keys-hub')
        students = students.filter(student_class=target_class)
    elif scope == 'CLASS_SHIFT':
        if not target_class or target_shift not in ('morning', 'evening'):
            messages.error(request, 'Class + shift required.')
            return redirect('workshop:upload-keys-hub')
        students = students.filter(student_class=target_class, shift=target_shift)
    elif scope == 'SHIFT':
        if target_shift not in ('morning', 'evening'):
            messages.error(request, 'Shift required.')
            return redirect('workshop:upload-keys-hub')
        students = students.filter(shift=target_shift)
    elif scope == 'ALL':
        pass  # no filter
    else:
        messages.error(request, f'Invalid scope: {scope}')
        return redirect('workshop:upload-keys-hub')

    expires = tz.now() + timedelta(hours=hours)
    created = 0
    skipped_no_user = 0
    skipped_has_key = 0

    for s in students:
        if not s.student_user:
            skipped_no_user += 1
            continue
        # Skip if already has active key of same type
        if TaskDelegation.objects.filter(
            assignee=s.student_user,
            task_type=task_type,
            expires_at__gt=tz.now(),
        ).exists():
            skipped_has_key += 1
            continue
        TaskDelegation.objects.create(
            assignee=s.student_user,
            task_type=task_type,
            expires_at=expires,
            created_by=request.user,
            notes=f'Bulk grant ({scope}) by {request.user.username} for {hours}h · {delegation_mode}',
            delegation_mode=delegation_mode,
            target_class=s.student_class or 'ALL',
            uses_remaining=uses_count,
        )
        created += 1

    messages.success(
        request,
        f'✅ Bulk {task_type}: created {created} · skipped {skipped_has_key} (already had key) · '
        f'skipped {skipped_no_user} (no user account) · scope={scope}'
    )
    return redirect('workshop:upload-keys-hub')


@staff_only
def upload_keys_bulk_revoke(request):
    """Bulk revoke upload keys matching a scope: Class / Class+Shift / Shift / ALL."""
    from exams.models import Student
    from exams.models_delegation import TaskDelegation
    from django.contrib import messages
    from django.utils import timezone as tz

    if request.method != 'POST':
        return redirect('workshop:upload-keys-hub')

    scope = (request.POST.get('scope') or 'ALL').strip().upper()
    target_class = (request.POST.get('target_class') or '').strip()
    target_shift = (request.POST.get('target_shift') or '').strip().lower()
    task_type = (request.POST.get('task_type') or 'ANY').strip()
    delegation_mode = None
    if task_type == 'CHOICE':
        task_type = 'QUESTION_UPLOAD'
        delegation_mode = 'CHOICE'

    # Find matching students
    students = Student.objects.filter(is_active=True)
    if scope == 'CLASS':
        if not target_class:
            messages.error(request, 'Class required.')
            return redirect('workshop:upload-keys-hub')
        students = students.filter(student_class=target_class)
    elif scope == 'CLASS_SHIFT':
        if not target_class or target_shift not in ('morning', 'evening'):
            messages.error(request, 'Class + shift required.')
            return redirect('workshop:upload-keys-hub')
        students = students.filter(student_class=target_class, shift=target_shift)
    elif scope == 'SHIFT':
        if target_shift not in ('morning', 'evening'):
            messages.error(request, 'Shift required.')
            return redirect('workshop:upload-keys-hub')
        students = students.filter(shift=target_shift)
    elif scope == 'ALL':
        pass
    else:
        messages.error(request, f'Invalid scope: {scope}')
        return redirect('workshop:upload-keys-hub')

    user_ids = [s.student_user_id for s in students if s.student_user_id]
    if not user_ids:
        messages.info(request, 'No students matched the scope.')
        return redirect('workshop:upload-keys-hub')

    qs = TaskDelegation.objects.filter(
        assignee_id__in=user_ids,
        expires_at__gt=tz.now(),
    )
    if task_type in ('QUESTION_UPLOAD', 'PAPER_UPLOAD'):
        qs = qs.filter(task_type=task_type)
    if delegation_mode:
        qs = qs.filter(delegation_mode=delegation_mode)
    else:
        qs = qs.filter(task_type__in=['QUESTION_UPLOAD', 'PAPER_UPLOAD'])

    count = qs.count()
    qs.delete()

    messages.success(
        request,
        f'✅ Bulk revoked: {count} active key(s) cleared · '
        f'scope={scope} · type={task_type}'
    )
    return redirect('workshop:upload-keys-hub')
