"""Teacher views — control room, ops, live (Group A).

Group B/C split out 2026-11-10; re-exported here for backward
compatibility with urls.py and views.py facade.
"""

import io
import json
import logging
import uuid
from pathlib import Path as _Path
import datetime
from django.contrib import messages
from django.contrib.auth.decorators import login_required, user_passes_test
from django.core.management import call_command
from django.db import transaction
from django.http import Http404, HttpResponse, HttpResponseNotFound
from django.shortcuts import render, redirect, get_object_or_404
from django.urls import reverse
from .models import KnowledgeComponent, KCCard, Student, Exam
from .view_helpers import _is_teacher, _paper_from_book, _compute_pipeline_status, SAFEGUARD_FEATURES, PIPELINE_STAGES, _SUBJECT_CHOICES, _SUBJECT_DEFAULT_BOOK, _student_enrolled_subjects
from exams.decorators import require_teacher_or_delegation
from exams.utils.pagination import paginate
from .view_db_helpers import _gate_state, _create_pipeline_task_for_stage, _teacher_assign, _advance_pipeline, _kc_subject_matches_student, _stage_all_done, _compute_question_assignments, _get_subject_options, _compute_effective_visibility, _filter_kc_refs_for_student  

from .views_teacher_classroom import (  # noqa: F401 — re-export
    portal_teacher_peers,
    portal_teacher_recall,
    portal_teacher_workflow,
    portal_teacher_attendance,
    portal_teacher_safeguards,
    portal_teacher_support,
    portal_teacher_support_detail,
    portal_teacher_reassign,
    portal_teacher_violations,
    portal_teacher_tasks,
)
from .views_teacher_content import (  # noqa: F401 — re-export
    portal_teacher_bulk,
    portal_teacher_paste,
    portal_teacher_build_cards,
    portal_teacher_pipelines,
    portal_teacher_assign_glossary,
    portal_teacher_stage_completions,
    portal_teacher_assign_books,
    portal_teacher_content,
    portal_teacher_add_kc,
    teacher_get_student_questions,
    portal_teacher_student_questions,
    portal_teacher_daily_codes,
)


@login_required
def portal_teacher_analytics(request):
    """Class mastery heatmap: per-KC counts of mastered vs learning cards.
    Heuristic: mastered = cards with reps >= 3 (FSRS proxy; exact state enum not assumed)."""
    kcs = []
    for kc in KnowledgeComponent.objects.filter(is_active=True).order_by('code'):
        cards = KCCard.objects.filter(kc=kc)
        total = cards.count()
        mastered = cards.filter(reps__gte=3).count()
        learning = total - mastered
        pct = int(round(mastered * 100.0 / total)) if total else 0
        kcs.append({
            'code': kc.code,
            'title': kc.title,
            'mastery_pct': pct,
            'mastered': mastered,
            'total_cards': total,
            'learning': learning,
        })
    return render(request, 'exams/portal_teacher_analytics.html', {'kcs': kcs})


@login_required(login_url="portal-login")
@user_passes_test(_is_teacher, login_url="portal-login")
def portal_teacher_hub(request):
    """4-hub teacher control surface. Standards: Miller <=4, WCAG 2.2 AA, single-scroll."""
    hubs = [
        {
            "id": "daily", "title": "Rozana Kaam", "icon": "\u2600",
            "summary": "Daily operations — start here",
            "items": [
                ("Operations Center", "portal-teacher-ops", "Live status, alerts, auto-refresh"),
                ("Live Activity", "portal-teacher-live", "Kaun abhi kaam kar raha hai"),
                ("Messages", "portal-teacher-messages", "Walidain se messages"),
                ("Health Log", "portal-teacher-health", "Violation / credit record"),
            ],
            "more": [
                ("Teacher Home", "portal-teacher-home", "Aaj ka status aur shortcuts"),
                ("Support Tickets", "portal-teacher-support", "Student requests"),
                ("Mere Kaam (student view)", "portal-task-list", "Student ke nazar se"),
            ],
        },
        {
            "id": "progress", "title": "Student Progress", "icon": "\U0001F4C8",
            "summary": "Per-student tracking and evaluation",
            "items": [
                ("Pipelines", "portal-teacher-pipelines", "Task pipeline per subject"),
                ("Reflections", "portal-teacher-reflections", "Story + SOLO scoring"),
                ("Result Cards", "portal-teacher-result-cards", "Monthly result cards"),
                ("Recall / RPS", "portal-teacher-recall", "Retrieval practice schedule"),
            ],
            "more": [
                ("Peers", "portal-teacher-peers", "Peer tutoring pairs"),
                ("Lectures", "portal-teacher-lectures", "Lecture requests"),
            ],
        },
        {
            "id": "content", "title": "Content Tools", "icon": "\U0001F4DD",
            "summary": "Authoring, bulk operations, guides",
            "items": [
                ("Tasks (assign / bulk)", "portal-teacher-tasks", "Task queue, bulk assign"),
                ("Bulk Upload", "portal-teacher-bulk", "Bulk paper ingest"),
                ("Paste (grading)", "portal-teacher-paste", "Master grading prompt"),
                ("Wizard (7 gates)", "wizard:home", "G1 se G7 tak"),
            ],
            "more": [
                ("Guide", "portal-teacher-guide", "Step-by-step daily guide"),
            ],
        },
        {
            "id": "security", "title": "Security & Governance", "icon": "\U0001F512",
            "summary": "Access control, kill switches, admin",
            "items": [
                ("Sessions", "portal-teacher-sessions", "Active logins, terminate"),
                ("Safeguards", "portal-teacher-safeguards", "Kill switches"),
                ("Admin Console", "portal-admin-health-list", "Health config (2FA)"),
                ("Student View", "portal-dashboard", "Reference — student page"),
            ],
            "more": [
                ("Student Health", "portal-health", "Amazon-style health"),
                ("Student Progress", "portal-progress", "150-day progress"),
                ("Parent Health", "portal-parent-health", "Parent view (FERPA)"),
            ],
        },
    ]

    from django.urls import reverse, NoReverseMatch
    for hub in hubs:
        for key in ("items", "more"):
            rows = []
            for label, name, desc in hub[key]:
                try:
                    url = reverse(name)
                except NoReverseMatch:
                    url = "#"
                rows.append({"label": label, "url": url, "desc": desc})
            hub[key] = rows

    return render(request, "exams/portal_teacher_hub.html", {"hubs": hubs})


@login_required(login_url="portal-login")
@user_passes_test(_is_teacher, login_url="portal-login")
def portal_teacher_ops(request):
    """One-page operations center: live activity + matrix + alerts + SITREP.

    Feature gate (Rule 17): teacher_ops. When OFF, redirect to teacher
    home with a flash message pointing at the tasks page to re-enable.
    Standards: Fowler Feature Toggles 2017; ISO 27001 A.5.15; Rule 17.
    """
    from exams.models import PortalFeature
    gate = PortalFeature.objects.filter(key="teacher_ops").first()
    if gate is None or not gate.enabled:
        return redirect("portal-teacher-tasks")
    from exams.digest import digest_data, digest_text
    data = digest_data()
    data["sitrep"] = digest_text()
    return render(request, "exams/portal_teacher_ops.html", data)


@login_required(login_url="portal-login")
@user_passes_test(_is_teacher, login_url="portal-login")
def portal_teacher_lectures(request):
    """Teacher view of OPEN LectureRequests (Section 18.1).

    Lists student-flagged concept gaps, lets the teacher attach
    resource links (writes KnowledgeComponent.resource_links), and
    marks requests RESOLVED. Links only; no files hosted on the site.

    Standards: Wiggins & McTighe 2005 (backward design); Hattie &
    Timperley 2007 (feed-forward); EU AI Act Art.14 (human
    oversight); ISO 27701 7.2.8; ISO 27001 A.8.10 (no local files);
    WCAG 2.2 AA (SC 1.4.3, 2.4.1, 3.3.1); ISO 9241-210 (teacher-
    centred design); Rule 10 (single writer for resource_links).
    """
    from django.utils import timezone as _tz
    from .models import KnowledgeComponent, LectureRequest

    message = ""
    error = ""

    if request.method == "POST":
        req_id = (request.POST.get("request_id") or "").strip()
        action = (request.POST.get("action") or "").strip()
        if not req_id.isdigit():
            error = "Request id durust nahi."
        else:
            try:
                lr = LectureRequest.objects.get(pk=int(req_id))
            except LectureRequest.DoesNotExist:
                error = "Request nahi mili."
            else:
                if action == "resolve":
                    lr.status = "RESOLVED"
                    lr.resolved_at = _tz.now()
                    lr.resolved_by = request.user
                    lr.save(update_fields=["status", "resolved_at", "resolved_by"])
                    message = "Request RESOLVED."
                elif action == "attach":
                    kind = (request.POST.get("kind") or "").strip().lower()
                    label = (request.POST.get("label") or "").strip()[:120]
                    url = (request.POST.get("url") or "").strip()[:500]
                    if kind not in {"youtube", "spotify", "pdf", "image", "whatsapp", "other"}:
                        error = "Kind durust nahi."
                    elif not label or not url:
                        error = "Label aur URL dono zaroori hain."
                    elif not (url.startswith("http://") or url.startswith("https://")):
                        error = "URL http:// ya https:// se shuru hona chahiye."
                    else:
                        kc = lr.kc
                        links = list(kc.resource_links or [])
                        links.append({"kind": kind, "label": label, "url": url})
                        kc.resource_links = links
                        kc.save(update_fields=["resource_links"])
                        message = "Link add ho gaya."
                else:
                    error = "Action samajh nahi aaya."

    open_requests = LectureRequest.objects.filter(
        status="OPEN").select_related("student", "kc").order_by("-created_at")
    page_obj = paginate(request, open_requests)
    open_requests = page_obj.object_list
    resolved_requests = LectureRequest.objects.filter(
        status="RESOLVED").select_related("student", "kc").order_by("-resolved_at")[:20]

    return render(request, "exams/portal_teacher_lectures.html", {
        "open_requests": open_requests, 'page_obj': page_obj,
        "resolved_requests": resolved_requests,
        "message": message,
        "error": error,
    })


@login_required(login_url="portal-login")
@user_passes_test(_is_teacher, login_url="portal-login")
def portal_teacher_reflections(request):
    """Teacher scoring of reflections (Section 9 Phase E, SOLO taxonomy)."""
    from .models import StoryReflection, ReflectionScore
    message = ""
    error = ""

    if request.method == "POST":
        ref_id = (request.POST.get("reflection_id") or "").strip()
        solo = (request.POST.get("solo_level") or "").strip()
        comment = (request.POST.get("teacher_comment") or "").strip()
        if not ref_id.isdigit():
            error = "Reflection id durust nahi."
        elif solo not in {"0", "1", "2", "3", "4"}:
            error = "SOLO level 0 se 4 ke darmiyan hona chahiye."
        elif len(comment) > 2000:
            error = "Comment bohat lamba hai (max 2000)."
        else:
            try:
                ref = StoryReflection.objects.get(pk=int(ref_id))
            except StoryReflection.DoesNotExist:
                error = "Reflection nahi mili."
            else:
                obj, created = ReflectionScore.objects.update_or_create(
                    reflection=ref,
                    defaults={"solo_level": int(solo), "teacher_comment": comment},
                )
                message = ("Score save ho gaya." if created
                           else "Score update ho gaya.")

    unscored = list(
        StoryReflection.objects.filter(score__isnull=True)
        .select_related("student", "story")
        .order_by("story__teaching_date", "student__code")[:100]
    )
    recent = list(
        StoryReflection.objects.filter(score__isnull=False)
        .select_related("student", "story", "score")
        .order_by("-score__scored_at")[:20]
    )
    return render(request, "exams/portal_teacher_reflections.html", {
        "unscored": unscored,
        "recent": recent,
        "solo_choices": ReflectionScore.SOLO_CHOICES,
        "message": message,
        "error": error,
    })


@login_required
@user_passes_test(_is_teacher, login_url="portal-login")
def portal_teacher_live(request):
    """Live operations view (Session 6, item 7).

    Teacher-only dashboard with an optional 60-second auto-refresh.
    Auto-refresh is OFF by default and user-initiated; the user can
    pause at any time. State is stored in sessionStorage (session
    scoped). Same query shapes as portal_teacher_home (Rule 10).

    Standards: WCAG 2.2 SC 2.2.2 Pause, Stop, Hide; NNG operations
    dashboard cadence (60s); Google SRE Workbook Ch. 24 (no polling
    without user consent); OWASP ASVS 5.0 s7.2.1 (sessionStorage);
    ISO 9241-210 (user controls the state); Rule 10 (one canonical
    query shape); Rule G (Roman Urdu).
    """
    return render(request, "exams/portal_teacher_live.html", {})


@login_required(login_url="portal-login")
@user_passes_test(_is_teacher, login_url="portal-login")
def portal_teacher_guide(request):
    """Single-page teacher workflow guide (Session 6).

    One reference page for the whole flow. Every step is a clickable
    link. Every step has inline help. The teacher returns here whenever
    lost or distracted.

    Standards: GOV.UK Task List Pattern; Nielsen Norman Group (single
    reference + no tooltips for critical info); Atul Gawande, The
    Checklist Manifesto; ISO 9241-210; WCAG 2.2 AA (details/summary
    for progressive disclosure, target size, consistent help, focus
    not obscured); ISO 9001:2015 7.5.3; Rule 10 (links to canonical
    URLs, no duplication); Rule 11 (G1/G4 point at the wizard which
    prints the exact prompt).
    """
    from django.conf import settings as _settings
    from .models import (
        ModelPaper, ModelQuestion, KnowledgeComponent, Exam,
    )
    from datetime import date as _date
    terminal_url = getattr(_settings, "TERMINAL_URL", "")

    papers_count = ModelPaper.objects.count()
    total_questions = ModelQuestion.objects.count()
    pending_questions = ModelQuestion.objects.filter(kc_code="").count()
    tagged_questions = total_questions - pending_questions
    kcs_count = KnowledgeComponent.objects.filter(is_active=True).count()
    kcs_frozen = KnowledgeComponent.objects.filter(
        is_active=True, ready_for_diagnosis=True,
    ).count()
    students_count = Student.objects.filter(is_active=True).count()
    today = _date.today()
    today_graded = Exam.objects.filter(exam_date=today).count()
    today_students = (
        Exam.objects.filter(exam_date=today)
        .values("student_id").distinct().count()
    )

    # Session 8: real workflow status for each section (Nielsen NN #1).
    from . import workflow as _wf
    workflow_states = {}
    for _key in ("student_paper_check", "new_paper_ingest", "concept_build",
                 "weekly_reflection", "monthly_cards"):
        _line = _wf.state_line(request.user, _key)
        _state = _wf.get_state(request.user, _key)
        _total = _wf.WORKFLOWS[_key]["total_steps"]
        workflow_states[_key] = {
            "line": _line or "Shuru nahi kiya",
            "kind": (
                "done" if _line == "Mukammal" else
                "doing" if _line and _line != "Shuru nahi kiya" else
                "todo"
            ),
            "current_step": _state.current_step if _state else 1,
            "total_steps": _total,
        }
    return render(request, "exams/portal_teacher_guide.html", {
        "terminal_url": terminal_url,
        "papers_count": papers_count,
        "total_questions": total_questions,
        "pending_questions": pending_questions,
        "tagged_questions": tagged_questions,
        "kcs_count": kcs_count,
        "kcs_frozen": kcs_frozen,
        "students_count": students_count,
        "today_graded": today_graded,
        "today_students": today_students,
        "workflow_states": workflow_states,
    })


@login_required(login_url="portal-login")
@user_passes_test(_is_teacher, login_url="portal-login")
def portal_teacher_sessions(request):
    """Section 11.5: teacher view of active sessions + terminate button.

    Standards: OWASP ASVS 5.0 3.5.1; NIST SP 800-63B 7.1;
    ITIL 4 Incident Management; ISO 27001 A.8.15.
    """
    from .models import SessionEvent
    from django.utils import timezone

    message = ""
    error = ""

    if request.method == "POST":
        code = (request.POST.get("code") or "").strip()
        reason = (request.POST.get("reason") or "").strip()
        if not code:
            error = "Student code chunein."
        elif len(reason) < 5:
            error = "Reason likhein (kam az kam 5 harf)."
        else:
            try:
                student = Student.objects.get(code=code, is_active=True)
            except Student.DoesNotExist:
                error = "Student nahi mila: " + code
            else:
                users = [u for u in (student.student_user, student.parent_user) if u]
                n = SessionEvent.objects.filter(user__in=users, active=True).update(
                    active=False, ended_reason="teacher_kill", ended_at=timezone.now())
                message = ("Terminated " + str(n) + " session(s) for "
                           + student.code + ". Reason: " + reason[:120])

    students = list(Student.objects.filter(is_active=True).order_by("code"))
    now = timezone.now()
    rows = []
    for st in students:
        users = [u for u in (st.student_user, st.parent_user) if u]
        evs = list(SessionEvent.objects.filter(user__in=users, active=True)
                   .order_by("-last_seen_at"))
        for ev in evs:
            ago = int((now - ev.last_seen_at).total_seconds() // 60)
            rows.append({
                "student": st,
                "user": ev.user.username,
                "ip": ev.ip or "-",
                "agent": ev.user_agent[:60],
                "started": ev.started_at,
                "last_seen_min": ago,
                "session_event_id": ev.id,
            })
    return render(request, "exams/portal_teacher_sessions.html", {
        "rows": rows,
        "students": students,
        "message": message,
        "error": error,
    })


@login_required(login_url="portal-login")
@user_passes_test(_is_teacher, login_url="portal-login")
def portal_teacher_home(request):
    """Task 5 - Teacher dashboard: one screen for the daily workflow.

    Glance-level KPIs, today's submission status, pending items, and
    quick links. No writes; no new models. Reuses existing querysets.

    Standards: ISO 9241-210 (human-centred design for the teacher);
    Nielsen Norman Group (dashboard pattern - glance + drill-down);
    Guskey, On Your Mark 3rd ed. 2020 (status, not raw numbers);
    Wiggins & McTighe 2005 (assessment -> next step);
    Section 15.4 (teacher time cap - one screen reduces navigation);
    OWASP ASVS 4.3.1 (admin/teacher-gated); WCAG 2.2 AA (SC 1.4.3,
    2.4.1, 3.3.1); ISO 9001:2015 7.5.3 (dashboard is documentation
    of the daily loop); Rule 10 (one canonical path - reuses existing
    queries, no new writer).
    """
    from django.utils import timezone as _tz
    from .models import (
        KnowledgeComponent, StoryReflection, ModelPaper,
    )

    today = _tz.localdate()
    today_count = Exam.objects.filter(exam_date=today).count()
    is_owner = request.user.is_superuser
    if is_owner:
        active_students = Student.objects.filter(is_active=True).order_by("code")
    else:
        active_students = Student.objects.filter(is_active=True, assigned_by=request.user.username).order_by("code")

    # Today's per-student status (graded / not)
    if is_owner:
        todays_exam_student_ids = set(Exam.objects.filter(exam_date=today).values_list("student_id", flat=True))
    else:
        todays_exam_student_ids = set(Exam.objects.filter(exam_date=today, student__assigned_by=request.user.username).values_list("student_id", flat=True))
    today_rows = []
    for st in active_students:
        today_rows.append({
            "student": st,
            "graded_today": st.id in todays_exam_student_ids,
        })

    # Pending items
    kcs_total = KnowledgeComponent.objects.count()
    kcs_frozen = KnowledgeComponent.objects.filter(ready_for_diagnosis=True).count()
    pending_kcs = list(
        KnowledgeComponent.objects.filter(ready_for_diagnosis=False)
        .order_by("code")
    )
    pending_reflections = StoryReflection.objects.filter(score__isnull=True).count()

    # Shelf
    papers_on_shelf = ModelPaper.objects.count()

    # Recent submissions (last 10)
    if is_owner:
        recent_exams = list(Exam.objects.select_related("student").order_by("-created_at")[:10])
    else:
        recent_exams = list(Exam.objects.filter(student__assigned_by=request.user.username).select_related("student").order_by("-created_at")[:10])

    # --- Session 8: workflow cards for landing page ---
    from . import workflow as _wf
    workflow_cards = []
    for _key, _cfg in _wf.WORKFLOWS.items():
        _line = _wf.state_line(request.user, _key)
        workflow_cards.append({
            "key": _key,
            "title": _cfg["title"],
            "tagline": _cfg["tagline"],
            "total_steps": _cfg["total_steps"],
            "status_line": _line or "Shuru nahi kiya",
            "status_kind": (
                "done" if _line == "Mukammal" else
                "progress" if _line and _line != "Shuru nahi kiya" else
                "not_started"
            ),
        })
    incomplete_states = _wf.incomplete_for(request.user)

    ctx = {
        "today": today,
        "active_students_count": active_students.count(),
        "today_count": today_count,
        "today_rows": today_rows,
        "kcs_total": kcs_total,
        "kcs_frozen": kcs_frozen,
        "pending_kcs": pending_kcs[:10],
        "pending_kcs_count": len(pending_kcs),
        "pending_reflections": pending_reflections,
        "papers_on_shelf": papers_on_shelf,
        "recent_exams": recent_exams,
        "workflow_cards": workflow_cards,
        "incomplete_workflows": incomplete_states,
    }
    return render(request, "exams/portal_teacher_home.html", ctx)


@login_required(login_url="portal-login")
@user_passes_test(_is_teacher, login_url="portal-login")
def portal_teacher_messages(request):
    from exams.models import ParentMessage, Student
    from django.utils import timezone as _tz

    if request.method == "POST":
        student_code = (request.POST.get("student_code") or "").strip().upper()
        body = (request.POST.get("body") or "").strip()
        if not student_code or not body:
            return redirect("portal-teacher-messages")
        if len(body) > 500:
            body = body[:500]
        s = Student.objects.filter(code=student_code).first()
        if s is None or s.parent_user is None:
            return redirect("portal-teacher-messages")
        thread_key = s.code + ":" + str(s.parent_user.id)
        m = ParentMessage.objects.create(
            student=s, from_user=request.user, to_user=s.parent_user,
            body=body, thread_key=thread_key,
        )
        try:
            from exams.models import PortalFeatureLog
            PortalFeatureLog.objects.create(
                key="msg." + thread_key, old_enabled=True, new_enabled=True,
                changed_by=request.user,
                note="sent to parent of " + s.code + " (id=" + str(m.id) + ")",
            )
        except Exception:
            pass
        from django.urls import reverse as _rev
        return redirect(_rev("portal-teacher-messages") + "?student=" + s.code)

    # GET: threads = students with a parent account
    students_with_parent = list(
        Student.objects.exclude(parent_user__isnull=True).order_by("code")
    )
    selected = (request.GET.get("student") or "").strip().upper()
    thread_msgs = []
    selected_obj = None
    if selected:
        selected_obj = Student.objects.filter(code=selected).first()
    if selected_obj and selected_obj.parent_user:
        thread_key = selected_obj.code + ":" + str(selected_obj.parent_user.id)
        thread_msgs = list(ParentMessage.objects.filter(
            thread_key=thread_key).order_by("created_at"))

    ctx = {
        "students_with_parent": students_with_parent,
        "selected": selected_obj,
        "thread_msgs": thread_msgs,
        "body_max": 500,
    }
    if request.GET.get('fragment') == '1':
        return render(request, "exams/_teacher_messages_fragment.html", ctx)
    return render(request, "exams/portal_teacher_messages.html", ctx)


@login_required(login_url="portal-login")
@user_passes_test(_is_teacher, login_url="portal-login")
def portal_teacher_ops_sitrep(request):
    """Plain-text SITREP — copyable to any AI."""
    from exams.digest import digest_text
    from django.http import HttpResponse
    return HttpResponse(digest_text(), content_type="text/plain; charset=utf-8")


@login_required(login_url="portal-login")
@user_passes_test(_is_teacher, login_url="portal-login")
def portal_control_room(request):
    """Admin control room. Standards: Miller <=4, WCAG 2.2 AA, vertical stepper."""
    import json as _json
    from pathlib import Path as _Path
    tf = _Path(__file__).resolve().parent.parent.parent / "control_room_tasks.json"
    try:
        data = _json.loads(tf.read_text(encoding="utf-8"))
    except Exception:
        import traceback as _tb
        try:
            with open("/tmp/cc_read_error.log", "a", encoding="utf-8") as _f:
                _f.write("\n--- control_room read failed ---\n")
                _f.write("tf=" + str(tf) + "\n")
                _f.write("exists=" + str(tf.exists()) + "\n")
                _f.write(_tb.format_exc())
        except Exception:
            pass
        data = {"metadata": {}, "phases": [], "blocked": []}

    all_tasks = [t for p in data.get("phases", []) for t in p.get("tasks", [])]
    done = sum(1 for t in all_tasks if t.get("status") == "done")
    total = data.get("metadata", {}).get("total", 100) or 100
    pct = int(done / total * 100) if total else 0

    current = next((t for t in all_tasks if t.get("status") == "in_progress"), None)
    pending = [t for t in all_tasks if t.get("status") == "pending"][:3]

    return render(request, "exams/portal_control_room.html", {
        "data": data, "done": done, "total": total, "pct": pct,
        "current": current, "next_up": pending,
        "blocked": data.get("blocked", []),
    })


@login_required(login_url="portal-login")
@user_passes_test(_is_teacher, login_url="portal-login")
def portal_teacher_live_data(request):
    """JSON summary for the live view poll (Session 6, item 7).

    Returns the same four numbers shown on the live page. No cache.
    Standards: NNG freshness (fresh query each call); Rule 10 (single
    source of the numbers); Twelve-Factor App Factor III (no hidden
    state).
    """
    from django.utils import timezone as _tz
    from django.http import JsonResponse
    from .models import KnowledgeComponent, LectureRequest

    today = _tz.localdate()
    today_count = Exam.objects.filter(exam_date=today).count()
    active_students_count = Student.objects.filter(is_active=True).count()
    kcs_total = KnowledgeComponent.objects.filter(is_active=True).count()
    kcs_frozen = KnowledgeComponent.objects.filter(
        is_active=True, ready_for_diagnosis=True).count()
    open_lectures = LectureRequest.objects.filter(status="OPEN").count()

    return JsonResponse({
        "today_count": today_count,
        "active_students_count": active_students_count,
        "kcs_frozen": kcs_frozen,
        "kcs_total": kcs_total,
        "open_lectures": open_lectures,
        "ts": _tz.now().isoformat(),
    })
