from django.views.decorators.csrf import csrf_exempt
"""Student portal views for exams app.

Extracted from views.py 2026-11-09 (Handover V2 Phase 2, student portal
Wave 1).
"""
import datetime, io, json, logging, uuid
from pathlib import Path as _Path
from collections import Counter
from urllib.parse import quote

from django.contrib import messages
from django.contrib.auth.decorators import login_required, user_passes_test
from django.db import transaction
from django.db.models import Q
from django.http import Http404, HttpResponse, JsonResponse
from django.shortcuts import render, redirect, get_object_or_404
from django.urls import reverse
from django.utils import timezone
from django.views.decorators.http import require_POST
from django.core.paginator import Paginator

from .models import (
    Student, ModelQuestion, StudentQuestionLock, Submission, StudentNote,
    ModelPaper, KCCard, Exam, StudentContribution, EngineState,
    DailyQuestionCount, BadgeAward, StudentStreak, Attendance, DailyTask,
    ParentReport, WhatsAppLog, StudentTask, ReasoningStep, PortalFeature,
    PortalFeatureLog, FeatureAccess,
)
from .view_helpers import (
    _is_teacher, _paper_from_book, _compute_pipeline_status,
    STAGE_TO_TASK_TYPE, SAFEGUARD_FEATURES, PIPELINE_STAGES,
    _SUBJECT_CHOICES, _SUBJECT_DEFAULT_BOOK, _SUBJECT_TO_PREFIX,
    _student_enrolled_subjects, _no_student_redirect,
    _board_prediction,
    _band,
)
from .view_db_helpers import (
    _current_student, _gate_state, _create_pipeline_task_for_stage,
    _teacher_assign, _advance_pipeline, _kc_subject_matches_student,
    _stage_all_done, _compute_effective_visibility,
    _compute_question_assignments, _get_subject_options,
    _is_student_user, _user_has_feature, _filter_kc_refs_for_student,
    _progress_for,
    _reflection_stats,
)
from exams.utils.pagination import paginate



class _TeacherPreviewStudent:
    """Lightweight stub so teachers can preview student flows without a student profile.
    The stub is NEVER saved to the database — it only provides defaults for tier/medium."""
    def __init__(self, teacher_id):
        self.id = f"T{teacher_id}"          # Prefixed to avoid ID collision
        self.code = 'TEACHER-PREVIEW'
        self.name = 'Teacher Preview'
        self.tier = 1                        # Default tier
        self.medium = 'EN'                   # Default medium

@login_required
def portal_my_todo(request):
    """Standalone Personal Todo page for all users."""
    from exams.models import PersonalTodo
    todos = PersonalTodo.objects.filter(user=request.user)
    page_obj = paginate(request, todos)
    todos = page_obj.object_list
    return render(request, 'exams/portal_my_todo.html', {
        'all_subjects': locals().get('all_subjects', []),'todos': todos, 'page_obj': page_obj})


@login_required(login_url="portal-login")
def portal_task_funnel(request, task_id):
    """Student funnel: one StudentTask laid out as a multi-step quest.

    For prompt-driven task types (KC_*, GLOSSARY, STORY) the funnel
    redirects to the detail page — that page already renders the exact
    prompt from get_prompt(). This avoids duplicating the prompt UI.
    Standards: GOV.UK (one page, one job); Nielsen NN #8; Rule 23.
    """
    from exams.models import StudentTask
    from exams.quests import (
        get_or_create_quest, advance_step, abandon_quest,
    )

    user = request.user
    student = _current_student(user)
    if student is None:
        return redirect("portal-login")

    try:
        task = StudentTask.objects.get(id=task_id, student=student)
    except StudentTask.DoesNotExist:
        raise Http404("task not found")

    # KC-family tasks need the printer's prompt. The detail page has it.
    PROMPT_TASK_TYPES = {
        "KC_TAG", "KC_DISCOVERY", "KC_MISCONCEPTION",
        "KC_SOCRATIC_LADDER", "GLOSSARY", "STORY",
    }
    if task.task_type in PROMPT_TASK_TYPES:
        return redirect("portal-task-detail", task_id=task.id)

    quest = get_or_create_quest(task)

    # Step navigation via GET ?step=N or POST
    if request.method == "POST":
        action = (request.POST.get("action") or "").strip()
        if action == "advance":
            n = int(request.POST.get("step") or "0")
            try:
                advance_step(quest, n, actor=request.user)
            except ValueError as e:
                return redirect(
                    reverse("portal-task-funnel", args=[task.id])
                    + "?err=" + str(e)[:120])
            return redirect(reverse("portal-task-funnel",
                                    args=[task.id]) + "?ok=1")
        if action == "abandon":
            abandon_quest(quest, actor=request.user,
                          reason="student exited")
            return redirect("portal-task-list")
        if action == "help":
            # Rule 13 HITL: student requests teacher reset
            from exams.models import PortalFeatureLog
            PortalFeatureLog.objects.create(
                key="funnel_help." + student.code,
                old_enabled=True, new_enabled=True,
                changed_by=request.user,
                note="task " + str(task.id) + " help requested",
            )
            return redirect(
                reverse("portal-task-funnel", args=[task.id])
                + "?help=1")

    steps = list(quest.steps.order_by("step_index"))
    total = len(steps)
    done = sum(1 for s in steps if s.completed)
    pct = int(round((done / total) * 100)) if total else 0

    # Current step: first not-completed, else the last
    current = None
    for s in steps:
        if not s.completed:
            current = s
            break
    if current is None and steps:
        current = steps[-1]

    return render(request, "exams/portal_task_funnel.html", {
        'all_subjects': locals().get('all_subjects', []),
        "task": task,
        "quest": quest,
        "steps": steps,
        "current": current,
        "total": total,
        "done": done,
        "pct": pct,
        "ok": request.GET.get("ok") == "1",
        "err": request.GET.get("err") or "",
        "help": request.GET.get("help") == "1",
    })


@login_required(login_url="portal-login")
def portal_system_k_kaam_safar_detail(request, paper_code):
    from exams.models import TaskPipeline, StudentTask
    user = request.user
    student = _current_student(user)
    if student is None:
        return redirect("portal-login")

    code = (paper_code or "").strip().upper()
    try:
        pipe = TaskPipeline.objects.get(paper_code=code)
    except TaskPipeline.DoesNotExist:
        raise Http404("pipeline not found: " + code)

    completed = set(pipe.stages_completed or [])

    rows = []
    for n, label, who, has_ai in PIPELINE_STAGES:
        if n in completed:
            status = "done"
        elif n == pipe.current_stage:
            status = "current"
        else:
            status = "waiting"

        # student's task at this stage, if any
        task = StudentTask.objects.filter(
            pipeline=pipe, pipeline_stage=n,
            student=student, unassigned_at__isnull=True,
        ).first()

        rows.append({
            "n": n,
            "label": label,
            "who": who,
            "has_ai": has_ai,
            "status": status,
            "task": task,
            "linkable": (status == "current" and who == "student" and task is not None),
        })

    return render(request, "exams/portal_pipeline_detail.html", {
        'all_subjects': locals().get('all_subjects', []),
        "pipe": pipe,
        "rows": rows,
        "student": student,
        "total_stages": len(PIPELINE_STAGES),
    })


@login_required(login_url="portal-login")
def portal_system_k_kaam_safar(request):
    """Student pipeline map (landing page).

    Standards: GOV.UK Task List; W3C WAI-ARIA progressbar (role+aria-valuenow);
    WCAG 2.2 SC 1.4.1, 2.4.8, 2.5.5, 4.1.3; Nielsen NN #1, #2;
    ISO 9241-110, 112; Sweller CLT; Rule 10 (one canonical map);
    Rule G (ur-Latn); IN-22 (visible exit).
    """
    from exams.models import TaskPipeline, StudentTask
    from django.db.models import Count
    student = _current_student(request.user)
    if student is None:
        return redirect("portal-login")

    total_stages = len(PIPELINE_STAGES)
    stage_nums = set(n for n, _, _, _ in PIPELINE_STAGES)

    # DEF-041 fix (2026-10-09): show every pipeline the student has OPEN TASKS in,
    # not only the ones they own. Nielsen NN #1 (status visible); WCAG 2.2 SC 3.2.4
    # (consistent identification); AERA Std 1.0 (a value must name its construct).
    # DEF-042: derive the student's safar from their own StudentTask rows,
    # not only the pipeline FK (fan-out rows have pipeline=NULL).
    # Standards: Rule 4 (verified), Rule 10 (one source), AERA Std 1.0,
    # Nielsen NN #1, WCAG 2.2 SC 3.2.4.
    # Map task_type -> pipeline_stage (DEF-042 fallback). Hoisted above the loop
    # so both the stage-count block and the next-task lookup see it.
    STAGE_TO_TT = {1: "BOOK_INGEST", 3: "KC_DISCOVERY", 5: "KC_TAG",
                   6: "KC_MISCONCEPTION", 7: "KC_SOCRATIC_LADDER",
                   10: "GLOSSARY", 11: "STORY"}
    TT_TO_STAGE = {v_: k_ for k_, v_ in STAGE_TO_TT.items()}
    from exams.models import StudentTask
    _prefixes = set()
    for _ref in (StudentTask.objects
                 .filter(student=student, unassigned_at__isnull=True)
                 .values_list("task_ref", flat=True)):
        if _ref and "#" in _ref:
            _prefixes.add(_ref.split("#")[0])
    _owned = TaskPipeline.objects.filter(owner_student=student)
    _matched = TaskPipeline.objects.filter(paper_code__in=_prefixes)
    pipes_qs = (_owned | _matched).distinct().order_by("-updated_at")

    rows = []
    totals = {"pipelines": 0, "pipelines_done": 0, "pipelines_blocked": 0,
              "stages_total": 0, "stages_done": 0, "stages_remaining": 0}

    for p in pipes_qs:
        done_set = set(p.stages_completed or []) & stage_nums
        done_count = len(done_set)
        pct = int(round(done_count / total_stages * 100)) if total_stages else 0
        is_done = (p.status == "DONE") or (done_count >= total_stages)
        is_blocked = (p.status == "BLOCKED_ON_TEACHER")

        next_stage = None
        if not is_done:
            for n, label, who, has_ai in PIPELINE_STAGES:
                if n == p.current_stage and n not in done_set:
                    next_stage = {"n": n, "label": label, "who": who, "has_ai": has_ai}
                    break

        task = None
        if next_stage and next_stage["who"] == "student":
            task = StudentTask.objects.filter(
                pipeline=p, pipeline_stage=next_stage["n"],
                student=student, unassigned_at__isnull=True,
                status__in=["ASSIGNED", "IN_PROGRESS"],
            ).first()
            if task is None:
                _tt = STAGE_TO_TT.get(next_stage["n"])
                if _tt:
                    task = StudentTask.objects.filter(
                        student=student, task_type=_tt,
                        task_ref__startswith=p.paper_code,
                        unassigned_at__isnull=True,
                        status__in=["ASSIGNED", "IN_PROGRESS"],
                    ).order_by("task_ref").first()

        # per-stage task counts. Primary: pipeline FK. Fallback: task_ref prefix
        # mapped by task_type -> stage (DEF-042; Rule 4; Rule 10; AERA Std 1.0).
        counts = {}
        for c in (StudentTask.objects
                  .filter(pipeline=p, student=student)
                  .values("pipeline_stage", "status")
                  .annotate(n=Count("id"))):
            s = c["pipeline_stage"]
            counts.setdefault(s, {})
            counts[s][c["status"]] = c["n"]
        # DEF-051: for KC stages the task_ref uses the subject prefix ("C9-MT02-..."),
        # not the book code ("MT-9-BOOK"). Match either. Rule 10: one canonical
        # prefix rule per pipeline subject. AERA Std 1.0 (a value names its construct).
        from django.db.models import Q as _Q2
        _subject_prefix = "C9-" + p.paper_code.split("-")[0].upper()
        _fallback_q = _Q2(task_ref__startswith=p.paper_code) | _Q2(task_ref__startswith=_subject_prefix)
        for c in (StudentTask.objects
                  .filter(student=student, unassigned_at__isnull=True)
                  .filter(_fallback_q)
                  .values("task_type", "status")
                  .annotate(n=Count("id"))):
            s = TT_TO_STAGE.get(c["task_type"])
            if s is None:
                continue
            counts.setdefault(s, {})
            counts[s][c["status"]] = counts[s].get(c["status"], 0) + c["n"]

        stage_rows = []
        for sn, slab, swho, sai in PIPELINE_STAGES:
            cs = counts.get(sn, {})
            d  = cs.get("DONE", 0)
            ip = cs.get("IN_PROGRESS", 0)
            aa = cs.get("ASSIGNED", 0)
            sk = cs.get("SKIPPED", 0)
            live = d + ip + aa
            retired = sk
            tot = live + retired
            stage_rows.append({
                "n": sn, "label": slab, "who": swho, "has_ai": sai,
                "is_done": sn in done_set, "is_current": sn == p.current_stage,
                "done": d, "in_progress": ip, "assigned": aa, "skipped": sk,
                "total": tot, "live": live, "retired": retired,
                "pct": int(round(d / live * 100)) if live else 0,
            })

        # DEF-044 (2026-10-09): the card's N/11 = the BOOK's safar, from
        # pipeline.stages_completed. Stages 2 (system) and 4 (teacher) count
        # even though no student task exists in them. Per-stage chips still
        # use the student's own task counts (Rule 14; AERA Std 1.0).
        # The card's top number is the pipeline's record, not any individual
        # student's; every student who can see this pipeline sees the same
        # book-level number. Standards: AERA Std 1.0; Nielsen NN #1;
        # ISO 9001:2015 7.5.3.
        for _s in stage_rows:
            _s["is_current"] = (_s["n"] == p.current_stage)

        # DEF-046 (2026-10-09): the card names BOTH constructs.
        #   ttl     = book safar (pipeline.stages_completed)
        #   herline = THIS student's task completions in this book
        # AERA/APA/NCME 2014 Std 1.0 (a value names its construct);
        # Nielsen NN #1; WCAG 2.2 SC 3.2.4; ISO 9001:2015 7.5.3.
        _her_qs = (StudentTask.objects
                   .filter(student=student,
                           task_ref__startswith=p.paper_code,
                           unassigned_at__isnull=True)
                   .exclude(status="SKIPPED"))
        her_done = _her_qs.filter(status="DONE").count()
        her_total = _her_qs.count()

        rows.append({"pipe": p, "done_count": done_count, "pct": pct,
                     "her_done": her_done, "her_total": her_total,
                     "stage_rows": stage_rows,
                     "is_done": is_done, "is_blocked": is_blocked,
                     "next_stage": next_stage, "task": task})
        totals["pipelines"] += 1
        totals["stages_total"] += total_stages
        totals["stages_done"] += done_count
        if is_done: totals["pipelines_done"] += 1
        if is_blocked: totals["pipelines_blocked"] += 1

    totals["stages_remaining"] = totals["stages_total"] - totals["stages_done"]
    overall_pct = (int(round(totals["stages_done"] / totals["stages_total"] * 100))
                   if totals["stages_total"] else 0)

    return render(request, "exams/portal_pipeline_index.html", {
        'all_subjects': locals().get('all_subjects', []),
        "rows": rows, "totals": totals, "overall_pct": overall_pct,
        "total_stages": total_stages, "student": student,
    })


@login_required(login_url="portal-login")
@require_POST
def portal_task_submit(request, task_id):
    import json as _json
    from django.db import transaction as _tx
    from django.utils import timezone as _tz
    from exams.models import StudentTask, PortalFeatureLog
    user = request.user
    student = _current_student(user)
    if student is None:
        return redirect("portal-login")

    from django.urls import reverse as _rev
    from urllib.parse import quote as _q

    raw = (request.POST.get("json_payload") or "").strip()
    if not raw:
        # WCAG 2.2 SC 3.3.1 / 3.3.3; GOV.UK Error Summary; Nielsen NN #9
        return redirect(
            _rev("portal-task-detail", kwargs={"task_id": task_id})
            + "?err=" + _q("JSON khaali tha. Dobara try karein.")
        )

    # Rule 10: use the canonical parser (exams.parsing.extract_json),
    # not a local re-implementation. Handles bare / fenced / embedded.
    # Standards: Rule 10; ISO 9001:2015 8.5.1; AERA Std 1.0.
    from exams.parsing import extract_json as _extract
    try:
        payload = _extract(raw)
    except ValueError as _e:
        return redirect(
            _rev("portal-task-detail", kwargs={"task_id": task_id})
            + "?err=" + _q("JSON theek nahi tha: " + str(_e)[:120])
        )

    # Empty-payload guard (P21-7b, 2026-10-12). Empty dict/list parses
    # successfully but starves downstream writers (e.g. generate_kc_content
    # rejects "Found keys: []"). Refuse here so the student keeps a clean
    # task row and can retry. Standards: ISO/IEC/IEEE 29119-3 5.4;
    # ISO 9001:2015 8.7 (control of nonconforming outputs); Rule 10.
    if not payload or (isinstance(payload, (dict, list)) and len(payload) == 0):
        return redirect(
            _rev("portal-task-detail", kwargs={"task_id": task_id})
            + "?err=" + _q("JSON khaali tha. Asli jawab paste karein.")
        )

    with _tx.atomic():
        try:
            task = StudentTask.objects.select_for_update().get(
                id=task_id, student=student
            )
        except StudentTask.DoesNotExist:
            raise Http404("task not found")

        # shared-group: if a sibling already DONE, mark self SKIPPED and bail
        if task.shared_group:
            sibs = (StudentTask.objects
                    .select_for_update()
                    .filter(shared_group=task.shared_group)
                    .exclude(id=task.id))
            if sibs.filter(status="DONE").exists():
                task.status = "SKIPPED"
                task.ingest_status = "PENDING"
                task.ingest_error = "Completed by a sibling"
                task.save(update_fields=["status", "ingest_status", "ingest_error"])
                return redirect("portal-task-detail", task_id=task.id)

        if task.status == "DONE":
            return redirect("portal-task-detail", task_id=task.id)

        key = _task_idempotency_key(task.id, raw)
        if task.idempotency_key and task.idempotency_key == key:
            return redirect("portal-task-detail", task_id=task.id)

        task.json_payload = payload
        task.idempotency_key = key
        task.status = "IN_PROGRESS"
        task.last_heartbeat_at = _tz.now()
        # Turn 3c: student reached step 3 (paste JSON).
        task.current_step = max(int(task.current_step or 1), 3)
        task.save(update_fields=[
            "json_payload", "idempotency_key", "status", "last_heartbeat_at",
            "current_step",
        ])

        # ALG-007 Mizan gate (Phase 7.5b, 2026-10-08).
        # Standards: IEEE 7009-2024 (fail-safe autonomy); Nygard 2018
        # (half-open circuit); EU AI Act Art. 14 (meaningful oversight);
        # Rule 12 (Mizan decides); Rule 13 (HITL preserved).
        # Feature toggle pattern: Fowler Feature Toggles 2017; SRE Ch. 17.
        # Default OFF — current behaviour unchanged when toggle is off.
        from exams.models import PortalFeature as _PF
        _mizan_on = _PF.objects.filter(
            key="mizan_auto_decide", enabled=True).exists()
        if _mizan_on:
            try:
                from exams.mizan import (decide as _mizan_decide,
                                         decide_correction as _mizan_corr,
                                         log_decision as _mizan_log)
                if task.task_type == "DATA_CORRECTION":
                    _md = _mizan_corr(payload or {}, {})
                else:
                    _md = _mizan_decide(
                        task.task_type, payload or {},
                        context={"has_override_path": 1,
                                 "audit_writeable": 1})
                _mizan_log(_md, task_id=task.id, actor="AUTO")
                if _md.band == "REFUSE_WITH_ROUTE":
                    # Leave task IN_PROGRESS; do not fire the writer.
                    task.ingest_status = "PENDING"
                    task.ingest_error = (
                        "Mizan: " + ", ".join(_md.failed_criteria)
                        + " | " + _md.teacher_question)[:2000]
                    task.save(update_fields=["ingest_status", "ingest_error"])
                    PortalFeatureLog.objects.create(
                        key="mizan_refuse." + task.student.code,
                        old_enabled=False, new_enabled=False,
                        changed_by=request.user,
                        note=("task " + str(task.id) + " refused; cs="
                              + str(_md.cs)
                              + " failed=" + ",".join(_md.failed_criteria)))
                    from django.urls import reverse as _rev_al
                    import urllib.parse as _uq
                    return redirect(
                        _rev_al("portal-task-detail",
                                kwargs={"task_id": task.id})
                        + "?err=" + _uq.quote(_md.action_text[:80]))
                # APPROVE / AUTO_APPROVE_WITH_NOTE / HITL all proceed.
                # The distinction is recorded in the audit log; the writer
                # runs in all three cases so the student is never blocked.
            except Exception as _e:
                PortalFeatureLog.objects.create(
                    key="mizan_error." + task.student.code,
                    old_enabled=False, new_enabled=False,
                    changed_by=request.user,
                    note="mizan decide failed: " + str(_e)[:200])

        # ---- AI Expert Panel gate (replaces teacher loop) ----
        # Standards: MACS 4-of-5 consensus; Polit/Beck CVI; AERA/APA/NCME.
        # Toggle: portal feature 'expert_panel' — enable to activate.
        from exams.models import PortalFeature as _PFp
        _panel_on = _PFp.objects.filter(key='expert_panel', enabled=True).exists()
        if _panel_on:
            from exams.services.expert_panel import evaluate_panel
            _book_prefix = (task.task_ref or '').split('#')[0].strip().upper()
            _panel = evaluate_panel(task, payload or {}, {'book_prefix': _book_prefix})
            from exams.models import PortalFeatureLog as _PFLp
            _PFLp.objects.create(
                key='expert_panel.' + task.student.code,
                old_enabled=False, new_enabled=_panel.passed,
                changed_by=request.user,
                note=('task ' + str(task.id) + ' panel='
                      + ('PASS' if _panel.passed else 'FAIL')
                      + ' cs=' + str(_panel.consensus_count)
                      + ' drr=' + format(_panel.drr, '.2f')
                      + ' ' + '; '.join(_panel.blockers[:2]))[:900],
            )
            if not _panel.passed:
                task.ingest_status = 'PENDING'
                task.ingest_error = _panel.action_text[:2000]
                task.save(update_fields=['ingest_status', 'ingest_error'])
                from django.urls import reverse as _rp
                return redirect(_rp('portal-task-detail', kwargs={'task_id': task.id}))

        from exams.student_task_dispatch import dispatch
        result = dispatch(task)

        # ---- Reroute by payload code (AERA Std 1.0; ISO 9001 8.5.1; Womack & Jones) ----
        # Compare SUBJECTS (XX-9), not raw codes, so MT-9 == MT-9-BOOK.
        # If subject differs, move the task to the payload's pipeline.
        # Auto-chain is skipped when a reroute occurred.
        _rerouted = False
        _reroute_from = ""
        _reroute_to = ""
        if result.ok and task.task_type == "BOOK_INGEST":
            try:
                def _subj(_c):
                    _c = (_c or "").strip().upper()
                    if _c.endswith("-BOOK"):
                        _c = _c[:-5]
                    _p = _c.split("-")
                    return (_p[0] + "-" + _p[1]) if len(_p) >= 2 else _c
                submitted_code = (payload.get("code") or "").strip().upper()
                task_book_code = (task.task_ref or "").split("#")[0].strip().upper()
                _sub_subj = _subj(submitted_code)
                _task_subj = _subj(task_book_code)
                if _sub_subj and _task_subj and _sub_subj != _task_subj:
                    from exams.models import TaskPipeline as _TP
                    _new_book_code = _sub_subj + "-BOOK"
                    new_pipe, _ = _TP.objects.get_or_create(
                        paper_code=_new_book_code,
                        defaults={
                            "current_stage": 1, "stages_completed": [],
                            "status": "ACTIVE", "owner_student": task.student,
                        },
                    )
                    old_pipe_id = task.pipeline_id
                    suffix = ""
                    if "#" in task.task_ref:
                        suffix = task.task_ref.split("#", 1)[1]
                    task.task_ref = _new_book_code + (("#" + suffix) if suffix else "")
                    task.pipeline = new_pipe
                    task.pipeline_stage = 1
                    task.save(update_fields=["task_ref", "pipeline", "pipeline_stage"])
                    PortalFeatureLog.objects.create(
                        key="task_reroute." + task.student.code,
                        old_enabled=True, new_enabled=True,
                        changed_by=request.user,
                        note=("task " + str(task.id) + " rerouted "
                              + _task_subj + " -> " + _sub_subj),
                    )
                    _rerouted = True
                    _reroute_from = _task_subj
                    _reroute_to = _sub_subj
            except Exception as _e:
                PortalFeatureLog.objects.create(
                    key="task_reroute_error." + task.student.code,
                    old_enabled=True, new_enabled=False,
                    changed_by=request.user,
                    note="reroute check failed: " + str(_e)[:200],
                )

        task.ingest_status = "OK" if result.ok else "FAILED"
        task.ingest_error = (result.error or "")[:2000]
        if result.ok:
            task.status = "DONE"
            task.completed_at = _tz.now()
        else:
            task.status = "IN_PROGRESS"
        # Turn 3c: on FAIL, keep cursor at 3 (monotonic)
        task.current_step = max(int(task.current_step or 1), 3)
        task.save(update_fields=[
            "ingest_status", "ingest_error", "status", "completed_at",
            "current_step",
        ])

        # shared-group: on success mark all siblings SKIPPED
        if result.ok and task.shared_group:
            (StudentTask.objects
             .filter(shared_group=task.shared_group)
             .exclude(id=task.id)
             .exclude(status="DONE")
             .update(status="SKIPPED",
                     ingest_error="Completed by " + task.student.code))

        # pipeline auto-chain (Cooper Stage-Gate; fires only when whole stage done)
        if (result.ok and not _rerouted
                and task.pipeline_id is not None and task.pipeline_stage):
            from exams.models import TaskPipeline
            try:
                pipe = TaskPipeline.objects.select_for_update().get(id=task.pipeline_id)
                _advance_pipeline(pipe, task.pipeline_stage,
                                  actor=request.user, closer=task.student)
            except TaskPipeline.DoesNotExist:
                pass

    from django.urls import reverse as _rev
    _url = _rev("portal-task-detail", kwargs={"task_id": task.id})
    try:
        if _rerouted:
            _url += "?rerouted_from=" + _reroute_from + "&rerouted_to=" + _reroute_to
    except NameError:
        pass
    return redirect(_url)


@login_required(login_url="portal-login")
def portal_task_detail(request, task_id):
    from exams.models import StudentTask
    user = request.user
    student = _current_student(user)
    if student is None:
        return redirect("portal-login")
    try:
        task = StudentTask.objects.get(id=task_id, student=student)
    except StudentTask.DoesNotExist:
        raise Http404("task not found")

    # shared-group semantics (Pessimistic Offline Lock)
    sibling_in_progress = None
    sibling_done = None
    if task.shared_group:
        sibs = (StudentTask.objects
                .filter(shared_group=task.shared_group)
                .exclude(id=task.id)
                .select_related("student"))
        sibling_in_progress = sibs.filter(status="IN_PROGRESS").first()
        sibling_done = sibs.filter(status="DONE").first()

    enabled, feature = _task_feature_enabled(task)
    if not enabled:
        msg = feature.message if feature else "Yeh safha abhi band hai."
        return render(request, "exams/portal_task_disabled.html", {
        'all_subjects': locals().get('all_subjects', []),
            "task": task, "message": msg,
        })

    try:
        from exams.student_task_dispatch import get_prompt
        prompt_text = get_prompt(task)
        prompt_error = ""
    except Exception as e:
        prompt_text = ""
        prompt_error = type(e).__name__ + ": " + str(e)[:200]

    # KC Discovery: route to the 6-step funnel (2026-10-10)
    # Standards: Tatsuoka 1983 (Q-matrix); Rule 27 (stepper); Rule H;
    #   GOV.UK Step-by-Step; Rule 23 (one job per view).
    if task.task_type == "KC_DISCOVERY":
        from exams.models import ModelQuestion
        q_count = ModelQuestion.objects.filter(
            paper__code=task.task_ref
        ).count()
        blocked = q_count < 400
        if blocked and task.status != "SKIPPED":
            # Auto-rollback: bank too small, send pipeline back to Stage 1.
            # Standards: Bloom 1968 (prerequisites); MTSS/NCII (tiered support);
            #   ALCOA+ (attributable, append-only); Rule 9 (mark, never delete).
            from django.db import transaction as _tx
            from django.utils import timezone as _tz
            from exams.models import PortalFeatureLog as _PFL, TaskPipeline as _TP
            with _tx.atomic():
                _pipe = task.pipeline
                _old_stage = _pipe.current_stage if _pipe else None
                if _pipe and _pipe.current_stage != 1:
                    _pipe.current_stage = 1
                    _pipe.save(update_fields=["current_stage"])
                task.status = "SKIPPED"
                task.ingest_error = (
                    f"Bank {task.task_ref} has {q_count} questions (<400 required). "
                    f"Rolled back to Stage 1 (BOOK_INGEST) at {_tz.now().isoformat()}."
                )
                task.save(update_fields=["status", "ingest_error"])
                # Un-skip BOOK_INGEST tasks for the same pipeline
                _ingests = StudentTask.objects.filter(
                    student=student,
                    task_type="BOOK_INGEST",
                    pipeline_id=task.pipeline_id,
                )
                _restored = _ingests.update(status="ASSIGNED", completed_at=None)
                _PFL.objects.create(
                    key="kc_discovery_rollback." + student.code,
                    old_enabled=True, new_enabled=False,
                    changed_by=request.user,
                    note=(f"KC_DISCOVERY {task.id} blocked ({q_count}<400); "
                          f"pipeline stage {_old_stage}->1; "
                          f"{_restored} BOOK_INGEST tasks restored"),
                )
            return redirect("portal-task-list-academic")
        return render(request, "exams/portal_task_detail_kc_discovery.html", {
        'all_subjects': locals().get('all_subjects', []),
            "task": task,
            "student": student,
            "prompt_text": prompt_text,
            "prompt_error": prompt_error,
            "q_count": q_count,
            "blocked": blocked,
        })

    # compute progress numbers from task_ref if it looks like BOOK_INGEST
    page_index = None
    page_total = 20
    if task.task_type == "BOOK_INGEST" and "#p=" in task.task_ref:
        try:
            rng = task.task_ref.split("#p=")[1]
            a, b = rng.split("-")
            page_index = int(a)
            page_total = max(int(b), page_index)
        except Exception:
            pass

    # v4 checkout stepper: MONOTONIC CURSOR (Turn 3c 2026-10-11).
    # task.current_step is the SOURCE OF TRUTH. Computed step is fallback.
    # Once a student reaches a step, the field stores it, never regresses.
    # Standards: Kleppmann DDIA Ch.5; ALCOA+ Original; Rule 10; Rule 25.
    TOTAL_STEPS = 3
    done_steps = list(task.steps_completed or [])
    _stored = int(task.current_step or 1)
    if task.status == "DONE":
        _computed = TOTAL_STEPS
        completed_set = {"copy_prompt", "ai_chat", "paste_json"}
    elif task.status == "IN_PROGRESS" and task.ingest_status in ("FAILED", "PENDING"):
        _computed = 3
        completed_set = {"copy_prompt", "ai_chat"}
    elif done_steps:
        _computed = min(max(len(done_steps) + 1, 1), TOTAL_STEPS)
        completed_set = set(done_steps)
    else:
        _computed = 1
        completed_set = set()
    current_step = max(_stored, _computed)
    if current_step > _stored:
        task.current_step = current_step
        task.save(update_fields=["current_step"])
    # start progress bar at 20% for a fresh task (progressive-disclosure)
    if task.status == "DONE":
        progress_pct = 100
    elif current_step == 1:
        progress_pct = 20
    elif current_step == 2:
        progress_pct = 66
    else:
        progress_pct = 90

    return render(request, "exams/portal_task_detail.html", {
        'all_subjects': locals().get('all_subjects', []),
        "task": task,
        "student": student,
        "prompt_text": prompt_text,
        "prompt_error": prompt_error,
        "page_index": page_index,
        "page_total": page_total,
        "submitted_ok": request.GET.get("ok") == "1",
        "submitted_err": request.GET.get("err") or "",
        "current_step": current_step,
        "total_steps": TOTAL_STEPS,
        "completed_set": completed_set,
        "progress_pct": progress_pct,
        "sibling_in_progress": sibling_in_progress,
        "sibling_done": sibling_done,
        "rerouted_from": request.GET.get("rerouted_from") or "",
        "rerouted_to": request.GET.get("rerouted_to") or "",
    })


@login_required(login_url="portal-login")
@require_POST
def portal_task_pause(request, task_id):
    """Keller 1968 PSI self-pacing; Rule 9 (append-only timestamp); Rule 10 (sole writer)."""
    from exams.models import StudentTask
    from django.utils import timezone
    student = _current_student(request.user)
    if student is None:
        return redirect("portal-login")
    task = StudentTask.objects.filter(id=task_id, student=student).first()
    if task is None:
        raise Http404("task not found")
    if task.status == "DONE":
        return redirect("portal-task-list-management")
    task.paused_at = timezone.now()
    if task.status == "IN_PROGRESS":
        task.status = "ASSIGNED"
    task.save(update_fields=["paused_at", "status"])
    return redirect("portal-task-list-management")


@login_required(login_url="portal-login")
def portal_task_list(request, category=None):
    from exams.models import StudentTask, PortalFeature, StudentTaskGate
    from django.urls import reverse as _rev
    # Rule 23 / GOV.UK: default to Academic when no category passed
    if category not in ("ACADEMIC", "MANAGEMENT", "SUPPORT"):
        return redirect(_rev("portal-task-list-academic"))
    user = request.user
    student = _current_student(user)
    if student is None:
        return redirect("portal-login")

    # v4 per-student gate override (Fowler per-user override; Rule 10 view-layer only)
    # GLOBAL portal gate (Fowler release toggle; Rule 13 view-layer control)
    _portal_gate = PortalFeature.objects.filter(key="task_portal").first()
    if _portal_gate is None or _portal_gate.enabled is False:
        raise Http404("no such page")

    # RULE 17 per-user feature control (NIST AC-6; OWASP A01:2021)
    if not _user_has_feature(request.user, "feature.task_portal"):
        raise Http404("no such page")

    gate = StudentTaskGate.objects.filter(student=student).first()
    # HIDDEN: link removed + page shows a neutral 404-style banner (no data leak)
    if gate is not None and gate.hidden is True:
        raise Http404("no such page")
    if gate is not None and gate.enabled is False:
        # LOCKED: still visible but inert, teacher message shown
        return render(request, "exams/portal_task_disabled.html", {
        'all_subjects': locals().get('all_subjects', []),
            "task": None,
            "message": gate.message or "Mere Kaam abhi band hai.",
        })

    enabled_keys = set(
        PortalFeature.objects.filter(enabled=True).values_list("key", flat=True)
    )
    from django.db.models import Q as _Q
    # Rule 14: category filter (None = all; "ACADEMIC" or "MANAGEMENT")
    # Rule 23: hide SKIPPED from student view.
    tasks = (StudentTask.objects
             .filter(student=student)
             .filter(_Q(unassigned_at__isnull=True))
             .exclude(status="SKIPPED"))
    if category in ("ACADEMIC", "MANAGEMENT", "SUPPORT"):
        tasks = tasks.filter(category=category)
    tasks = tasks.order_by("status", "task_type", "task_ref")
    # MTSS enrichment (2026-10-22)
    weak_subject = None
    try:
        from exams.models import Exam as _Exam_MTSS
        _subject_scores = {}
        _recent_exams = _Exam_MTSS.objects.filter(student=student).order_by("-exam_date")[:40]
        for _e in _recent_exams:
            _sub = _e.submissions.order_by("-created_at").first()
            if _sub and _sub.ai_score is not None and _e.max_marks and _e.subject:
                _pct = (float(_sub.ai_score) / float(_e.max_marks)) * 100.0
                _subject_scores.setdefault(_e.subject, []).append(_pct)
        if _subject_scores:
            _avgs = {k: sum(v) / len(v) for k, v in _subject_scores.items()}
            _lowest = min(_avgs, key=_avgs.get)
            if _avgs[_lowest] < 60.0:
                weak_subject = _lowest
    except Exception:
        weak_subject = None

    _TASK_META_MTSS = {
        'HANDWRITING_EN': (5, True), 'HANDWRITING_UR': (5, True), 'GLOSSARY': (5, True),
        'READING_EN': (10, False), 'READING_UR': (10, False),
        'KC_DISCOVERY': (10, False), 'KC_MISCONCEPTION': (15, False),
        'KC_SOCRATIC_LADDER': (20, False), 'BOOK_INGEST': (30, False),
    }
    _SUBJ_NAMES_MTSS = {'MT': 'Mathematics', 'PH': 'Physics', 'CH': 'Chemistry', 'BI': 'Biology',
                        'EN': 'English', 'UR': 'Urdu', 'IS': 'Islamiyat', 'CS': 'Computer Science',
                        'TQ': 'Tarjumatul Quran'}
    def _task_subject_mtss(t):
        ref = (t.task_ref or '').upper()
        for _p in ['MT', 'PH', 'CH', 'BI', 'EN', 'UR', 'IS', 'CS', 'TQ']:
            if ref.startswith(_p + '-') or ('-' + _p + '-') in ref:
                return _SUBJ_NAMES_MTSS.get(_p)
        return None

    rows = []
    for t in tasks:
        k = _task_feature_key(t)
        _mins, _quick = _TASK_META_MTSS.get(t.task_type, (10, False))
        _is_priority = bool(weak_subject and _task_subject_mtss(t) == weak_subject)
        rows.append({
            "task": t, "key": k, "enabled": k in enabled_keys,
            "estimated_mins": _mins, "is_quick_win": _quick, "is_priority": _is_priority,
        })
    # Pipeline-stage gating (Rule 14; GOV.UK Task List; ISO 9241-110;
    # Sweller CLT one-stage-at-a-time; Rule 23). MANAGEMENT tasks whose
    # pipeline_stage is ahead of the pipeline's current_stage are hidden
    # from the student view. DONE tasks stay visible (historical record);
    # non-pipeline tasks are never gated.
    from exams.models import TaskPipeline as _TPipeline
    # Pipelines this student owns. MANAGEMENT work is per-pipeline (Rule 14);
    # cross-pipeline and orphan rows belong on their own student's view.
    _student_pipeline_ids = set(
        _TPipeline.objects.filter(owner_student=student)
        .values_list("id", flat=True)
    )
    # Only load stages for this student's own pipelines — no full-table scan.
    _pipe_stages = {p.id: p.current_stage
                    for p in _TPipeline.objects.filter(id__in=_student_pipeline_ids)}
    _before = len(rows)
    def _hidden_mgmt(r):
        t = r["task"]
        if t.category != "MANAGEMENT":
            return False
        # Only show MANAGEMENT tasks tied to a pipeline this student owns.
        # Orphan rows (pipeline_id=None) and rows tied to another student's
        # pipeline are hidden. DONE rows on the student's own pipeline stay
        # for historical record.
        # Standards: Rule 14 (categories do not inflate a pipeline view);
        # Nielsen NN #1 (accurate status); ISO 9241-110 7.1 (task fit);
        # GOV.UK Task List (group by meaning).
        if t.pipeline_id is None:
            return True
        if t.pipeline_id not in _student_pipeline_ids:
            return True
        if t.status == "DONE":
            return False
        if t.pipeline_stage is None:
            return False
        return _pipe_stages.get(t.pipeline_id, 0) < t.pipeline_stage
    rows = [_r for _r in rows if not _hidden_mgmt(_r)]
    _hidden = _before - len(rows)

    counts = {
        "assigned": sum(1 for r in rows if r["task"].status == "ASSIGNED"),
        "in_progress": sum(1 for r in rows if r["task"].status == "IN_PROGRESS"),
        "done": sum(1 for r in rows if r["task"].status == "DONE"),
        "total": len(rows),
        "hidden_gated": _hidden,
    }
    # Sequential unlock (GOV.UK Task List; Bloom 1968 Mastery; Keller 1968 PSI;
    # MTSS/NCII sequencing; Sweller CLT chunking; Nielsen NN #1, #6).
    # Book-page refs like "CH-9-BOOK#p=1-2" gate by page number: only the
    # lowest incomplete in each book is a link. Non-book refs are always open.
    # Computed on render; no DB status change (Rule 9).
    import re as _re
    from collections import defaultdict as _dd
    _pref_buckets = _dd(list)
    for _r in rows:
        _t = _r["task"]
        _m = _re.match(r"^(.+?)#p=(\d+)-", _t.task_ref or "")
        if _m:
            _pref_buckets[_m.group(1)].append((int(_m.group(2)), _t.task_ref, _t.status))
    _first_incomplete = {}
    for _pref, _items in _pref_buckets.items():
        _items.sort(key=lambda x: x[0])
        for _p, _ref, _st in _items:
            if _st in ("ASSIGNED", "IN_PROGRESS"):
                _first_incomplete[_pref] = _ref
                break
    for _r in rows:
        _t = _r["task"]
        _m = _re.match(r"^(.+?)#p=(\d+)-", _t.task_ref or "")
        if not _m:
            _r["unlock"] = "open"; _r["locked_by_ref"] = None
            continue
        _first = _first_incomplete.get(_m.group(1))
        if _first is None or _first == _t.task_ref:
            _r["unlock"] = "open"; _r["locked_by_ref"] = None
        else:
            _r["unlock"] = "locked"; _r["locked_by_ref"] = _first
    # KC group gating (Bloom 1968 mastery; Keller 1968 PSI; MTSS/NCII sequencing;
    # Sweller CLT; Hick 1952; Nielsen NN #1; GOV.UK Task List).
    # Within each KC task_type group, only the first ASSIGNED/IN_PROGRESS row is a
    # link. The rest are locked with 'Pehle <ref> karein'. Nothing hidden (Rule 9).
    KC_GATED = {"KC_MISCONCEPTION", "KC_SOCRATIC_LADDER", "KC_TAG", "KC_DISCOVERY"}
    _kc_buckets = _dd(list)
    for _r in rows:
        _t = _r["task"]
        if _t.task_type in KC_GATED and _r.get("unlock") != "locked":
            _kc_buckets[_t.task_type].append((_t.task_ref or "", _t.status))
    _kc_first = {}
    for _tt, _items in _kc_buckets.items():
        _items.sort(key=lambda x: x[0])
        for _ref, _st in _items:
            if _st in ("ASSIGNED", "IN_PROGRESS"):
                _kc_first[_tt] = _ref
                break
    for _r in rows:
        _t = _r["task"]
        if _t.task_type not in KC_GATED or _r.get("unlock") == "locked":
            continue
        _first = _kc_first.get(_t.task_type)
        if _first is None or _first == _t.task_ref:
            continue
        _r["unlock"] = "locked"; _r["locked_by_ref"] = _first
    from exams.models import TaskPipeline
    pipelines = list(TaskPipeline.objects.filter(
        stage_tasks__student=student
    ).distinct().order_by("paper_code"))

    # Rule 14: separate ACADEMIC from MANAGEMENT/SUPPORT.
    # Standards: AERA Std 1.0 (distinct constructs); MTSS/NCII
    # (only on-construct work rolls into student progress);
    # COBIT 2019; ISO 21001:2018.
    cat_order = [("ACADEMIC", "Skills"),
                 ("MANAGEMENT", "System Kaam"),
                 ("SUPPORT", "Madad")]
    cat_buckets = {"ACADEMIC": {}, "MANAGEMENT": {}, "SUPPORT": {}}
    for r in rows:
        cat = r["task"].category or "ACADEMIC"
        if cat not in cat_buckets:
            cat = "ACADEMIC"
        tt = r["task"].task_type
        g = cat_buckets[cat].setdefault(tt, {
            "type": tt, "rows": [], "done": 0, "open": 0,
            "enabled": True,
            "label": r["task"].get_task_type_display()})
        g["rows"].append(r)
        if r["task"].status == "DONE":
            g["done"] += 1
        elif r["task"].status in ("ASSIGNED", "IN_PROGRESS"):
            g["open"] += 1
        g["enabled"] = g["enabled"] and r["enabled"]

    groups_by_category = []
    for cat_key, cat_label in cat_order:
        bucket = cat_buckets[cat_key]
        ordered = sorted(bucket.values(),
                         key=lambda x: (x["open"] == 0, x["type"]))
        if ordered:
            groups_by_category.append((cat_key, cat_label, ordered))

    # counts split per Rule 14: ACADEMIC vs MANAGEMENT totals
    acad_rows = [r for r in rows
                 if (r["task"].category or "ACADEMIC") == "ACADEMIC"]
    mgmt_rows = [r for r in rows
                 if (r["task"].category or "ACADEMIC") == "MANAGEMENT"]
    counts_academic = {
        "assigned": sum(1 for r in acad_rows if r["task"].status == "ASSIGNED"),
        "in_progress": sum(1 for r in acad_rows
                           if r["task"].status == "IN_PROGRESS"),
        "done": sum(1 for r in acad_rows if r["task"].status == "DONE"),
        "total": len(acad_rows),
    }
    counts_management = {
        "assigned": sum(1 for r in mgmt_rows if r["task"].status == "ASSIGNED"),
        "in_progress": sum(1 for r in mgmt_rows
                           if r["task"].status == "IN_PROGRESS"),
        "done": sum(1 for r in mgmt_rows if r["task"].status == "DONE"),
        "total": len(mgmt_rows),
    }

    # Rule 14 tab URLs (GOV.UK tabs pattern)
    from django.urls import reverse as _rev
    tabs = [
        {"key": "ACADEMIC",   "label": "Skills",
         "url": _rev("portal-task-list-academic"),
         "active": category == "ACADEMIC"},
        {"key": "MANAGEMENT", "label": "System Kaam",
         "url": _rev("portal-task-list-management"),
         "active": category == "MANAGEMENT"},
    ]

    # Mark the first open task in each group as "next" (Hick 1952; Nielsen NN #1;
    # GOV.UK One Thing Per Page; Bloom 1968). Nothing hidden (Rule 9).
    for _ck, _cl, _cgs in groups_by_category:
        for _g in _cgs:
            _marked = False
            _nref = None
            for _r in _g["rows"]:
                if not _marked and _r["task"].status in ("ASSIGNED","IN_PROGRESS"):
                    _r["next"] = True; _marked = True
                    _nref = _r["task"].task_ref
                else:
                    _r["next"] = False
            _g["next_ref"] = _nref

    # GLOBAL single-task unlock (Mastery Learning Bloom 1968; Keller PSI 1968;
    # GOV.UK One Thing Per Page; Sweller CLT; user directive 2026-10-10).
    # Only ONE open task is clickable. All others locked until it is DONE.
    _PRIO = {
        'KC_DISCOVERY': 1,
        'KC_TAG': 2,
        'KC_MISCONCEPTION': 3,
        'KC_SOCRATIC_LADDER': 4,
        'GLOSSARY': 5,
        'READING_EN': 90,
        'READING_UR': 91,
    }
    _open = [r for r in rows
             if r["task"].status in ("ASSIGNED", "IN_PROGRESS")]
    _open.sort(key=lambda r: (
        _PRIO.get(r["task"].task_type, 99),
        r["task"].task_ref or "",
        r["task"].id,
    ))
    _first = _open[0] if _open else None
    for _r in rows:
        _st = _r["task"].status
        if _st in ("ASSIGNED", "IN_PROGRESS"):
            if _r is _first:
                _r["next"] = True
                _r["unlock"] = "open"
                _r["locked_by_ref"] = None
            else:
                _r["next"] = False
                _r["unlock"] = "locked"
                _r["locked_by_ref"] = (
                    _first["task"].task_ref or _first["task"].task_type
                ) if _first else None
        else:
            _r["next"] = False

    # MTSS aggregate stats (2026-10-22)
    _open_rows = [r for r in rows if r["task"].status not in ("DONE", "SKIPPED")]
    _done_rows = [r for r in rows if r["task"].status == "DONE"]
    _mtss_total = len(_open_rows) + len(_done_rows)
    _est_mins_total = sum(r.get("estimated_mins", 10) for r in _open_rows)
    mtss_stats = {
        "completion_pct": round(len(_done_rows) / _mtss_total * 100) if _mtss_total else 0,
        "done_count": len(_done_rows),
        "open_count": len(_open_rows),
        "total_count": _mtss_total,
        "total_estimated_mins": _est_mins_total,
        "time_display": (f"{_est_mins_total // 60}h {_est_mins_total % 60}m" if _est_mins_total >= 60 else f"{_est_mins_total}m"),
        "quick_win_count": sum(1 for r in _open_rows if r.get("is_quick_win", False)),
    }
    return render(request, "exams/portal_task_list.html", {
        'all_subjects': locals().get('all_subjects', []),
        "mtss_stats": mtss_stats,
        "weak_subject": weak_subject,
        "rows": rows, "counts": counts,
        "tabs": tabs, "active_category": category,
        "counts_academic": counts_academic,
        "counts_management": counts_management,
        "student": student,
        "pipelines": pipelines,
        "groups_by_category": groups_by_category,
    })


def _task_feature_enabled(task):
    from exams.models import PortalFeature
    f = PortalFeature.objects.filter(key=_task_feature_key(task)).first()
    return bool(f and f.enabled), f


def _task_feature_key(task):
    return "student_tasks." + task.task_type


def _task_idempotency_key(task_id, payload_text):
    import hashlib as _h
    h = _h.sha256()
    h.update(str(task_id).encode("utf-8"))
    h.update(b"|")
    h.update(payload_text.encode("utf-8"))
    return h.hexdigest()[:32]


@login_required(login_url="portal-login")
def portal_glossary(request):
    """Search over the Layer-0 key_terms for any KC.

    Students type a word; system matches across term, roman_urdu and
    definition (case-insensitive substring). Returns matching term
    cards with definition + example + non_example so the student can
    understand a Tier-3 word in seconds, without leaving the server.

    Standards:
      Beck/McKeown/Kucan three-tier vocabulary (retrievable on demand);
      Marzano Six-Step Process (definition + example + non-example);
      Frayer Model (the non_example teaches discrimination);
      Hayden et al. 2019 (three probes displayed);
      AERA/APA/NCME 2014 Std 13.7 (each value names its construct);
      COPPA / FERPA / Constitution of Pakistan Art. 14 / PECA 2016
        (no external search engine; query never leaves the server);
      ISO 27001 A.8.10 (data stays within the perimeter);
      WCAG 2.2 AA; OWASP ASVS 4.3.1 (login required);
      Rule G (Roman Urdu, lang=ur-Latn); Rule 10 (single canonical writer).
    """
    user = request.user
    student = _current_student(user)
    if student is None:
        return _no_student_redirect(request)

    is_student = _is_student_user(user)
    query = (request.GET.get("q") or "").strip()[:80]

    from .models import KnowledgeComponent
    kcs = list(KnowledgeComponent.objects.filter(
        subject="Chemistry", is_active=True).order_by("chapter", "code"))

    scored = []
    q_lower = query.lower()
    total_terms = 0

    for kc in kcs:
        for t in (kc.key_terms or []):
            total_terms += 1
            term = (t.get("term") or "")
            ru = (t.get("roman_urdu") or "")
            definition = (t.get("definition") or "")
            if not query:
                continue
            rank = _rank_term_match(q_lower, term, ru, definition)
            if rank < 9:
                scored.append((rank, kc, t))

    scored.sort(key=lambda x: x[0])
    results = []
    for _rank, kc, t in scored:
        term = (t.get("term") or "")
        ru = (t.get("roman_urdu") or "")
        definition = (t.get("definition") or "")
        if True:
                results.append({
                    "term": term,
                    "roman_urdu": ru,
                    "definition": definition,
                    "example": t.get("example") or "",
                    "non_example": t.get("non_example") or "",
                    "confidence": t.get("confidence"),
                    "kc_code": kc.code,
                    "kc_title": kc.title,
                    "chapter": kc.chapter,
                })

    # Cap results to 40 to keep the page light
    capped = results[:40]
    truncated = len(results) > 40

    return render(request, "exams/portal_glossary.html", {
        'all_subjects': locals().get('all_subjects', []),
        "student": student,
        "is_student": is_student,
        "query": query,
        "results": capped,
        "result_count": len(results),
        "truncated": truncated,
        "total_terms": total_terms,
    })


def _rank_term_match(query_lower, term, ru, definition):
    """Score a term for a query. Lower is better.
       0 = exact term match
       1 = term starts with query
       2 = term contains query
       3 = roman_urdu contains query
       4 = definition contains query
       9 = no match
    """
    t = (term or "").lower()
    r = (ru or "").lower()
    d = (definition or "").lower()
    if t == query_lower:
        return 0
    if t.startswith(query_lower):
        return 1
    if query_lower in t:
        return 2
    if query_lower in r:
        return 3
    if query_lower in d:
        return 4
    return 9


def portal_terms(request):
    """Layer 0 — student-facing list of Tier-3 key terms per KC.

    Read-only MVP. Students see every KC that has key_terms, grouped by
    chapter. Each term shows definition, example, non-example, and the
    three Hayden probes as visible questions (answer capture deferred).

    Standards: Beck/McKeown/Kucan (three-tier vocabulary);
    Marzano Six-Step Process; Frayer Model; Hayden et al. 2019;
    AERA/APA/NCME 2014 Std 13.7; Rule G (Roman Urdu, lang=ur-Latn);
    WCAG 2.2 AA; OWASP ASVS 4.3.1 (login required).
    """
    user = request.user
    student = _current_student(user)
    if student is None:
        return _no_student_redirect(request)

    is_student = _is_student_user(user)

    from .models import KnowledgeComponent
    kcs = list(KnowledgeComponent.objects.filter(
        subject="Chemistry", is_active=True).order_by("chapter", "code"))

    by_chapter = {}
    total_terms = 0
    for kc in kcs:
        terms = kc.key_terms or []
        if not terms:
            continue
        by_chapter.setdefault(kc.chapter or "Chapter", []).append({
            "kc": kc,
            "terms": terms,
            "term_count": len(terms),
        })
        total_terms += len(terms)

    return render(request, "exams/portal_terms.html", {
        'all_subjects': locals().get('all_subjects', []),
        "student": student,
        "is_student": is_student,
        "by_chapter": by_chapter,
        "total_kcs": sum(len(v) for v in by_chapter.values()),
        "total_terms": total_terms,
    })


@login_required(login_url="portal-login")
def portal_progress(request):
    """MTSS Progress Monitoring Dashboard: Trend, Tier, & Interventions."""
    from collections import OrderedDict
    from datetime import timedelta

    user = request.user
    student = None
    try:
        student = Student.objects.get(student_user=user, is_active=True)
    except Student.DoesNotExist:
        try:
            student = Student.objects.get(parent_user=user, is_active=True)
        except Student.DoesNotExist:
            student = None
    if student is None:
        return _no_student_redirect(request)

    exams = (Exam.objects.filter(student=student)
             .select_related()
             .order_by("exam_date"))

    exam_dates = list(Exam.objects.filter(student=student, submissions__isnull=False).values_list("exam_date", flat=True).distinct().order_by("-exam_date")[:12])  # industry standard: cap timeline widget

    from exams.models import AttemptLog

    # ── One chronological event stream: bulk submissions + single attempts ──
    events = []

    for e in exams:
        sub = e.submissions.order_by("-created_at").first()
        if sub and sub.ai_score is not None and e.max_marks:
            events.append({
                "date": e.exam_date,
                "score": float(sub.ai_score),
                "max": float(e.max_marks),
                "mistakes": len(sub.ai_mistakes or []),
                "subject": e.subject or "",
            })

    for sa in (AttemptLog.objects.filter(student=student)
               .select_related("question")
               .order_by("created_at")):
        if sa.score is None or not sa.max_score:
            continue
        mistakes = 0
        rj = sa.result_json or {}
        if isinstance(rj, dict) and "mistakes" in rj:
            try: mistakes = len(rj["mistakes"])
            except Exception: mistakes = 0
        elif getattr(sa, "outcome", None) and sa.outcome != "CORRECT":
            mistakes = 1

        events.append({
            "date": sa.created_at.date(),
            "score": float(sa.score),
            "max": float(sa.max_score),
            "mistakes": mistakes,
            "subject": sa.question.paper.subject if getattr(sa.question, "paper", None) else "",
        })

    events.sort(key=lambda ev: ev["date"])

    total_exams = len(events)
    total_score = sum(ev["score"] for ev in events)
    total_max = sum(ev["max"] for ev in events)
    total_mistakes = sum(ev["mistakes"] for ev in events)
    recent_scores = [ev["score"] / ev["max"] * 100.0 for ev in events if ev["max"]]
    exam_dates = [ev["date"] for ev in events]

    overall_pct = round((total_score / total_max * 100.0), 1) if total_max > 0 else 0.0

    # ---- 2. Calculate Trend (Last 3 vs Previous 3) ----
    trend_delta = 0.0
    if len(recent_scores) >= 4:
        last_3 = recent_scores[-3:]
        prev_3 = recent_scores[-6:-3] if len(recent_scores) >= 6 else recent_scores[:-3]
        if prev_3:
            trend_delta = (sum(last_3)/len(last_3)) - (sum(prev_3)/len(prev_3))

    # ---- 3. MTSS Decision Rules ----
    # Tier 3: Below safe line (40%) OR sharply declining trend (<-5%)
    # Tier 2: Below excellent line (60%) OR flat trend (-5% to +5%)
    # Tier 1: Above 60% AND positive trend
    if overall_pct < 40.0 or trend_delta < -5.0:
        tier = 3
        tier_label = "Tier 3: Intensive Support"
        tier_class = "status-box--error"
        tier_icon = "🚨"
    elif overall_pct < 60.0 or (-5.0 <= trend_delta <= 5.0):
        tier = 2
        tier_label = "Tier 2: Strategic Support"
        tier_class = "status-box--info" # Using info (blue) for warning as we don't have yellow box
        tier_icon = "⚠️"
    else:
        tier = 1
        tier_label = "Tier 1: On Track"
        tier_class = "status-box--success"
        tier_icon = "🌟"

    # ---- 4. Generate Interventions ----
    recommendations = []
    if tier == 3:
        recommendations.append("Fauran tawajjo dein: Aap ka score safe line (40%) se neeche hai.")
        recommendations.append("Aaj se pace kam karein (ya 1-2 sawal rozana karein) taake buniyad mazboot ho.")
        recommendations.append("Teacher se baat karein aur 'Samajhne ka Safar' mein concepts dobara parhein.")
    elif tier == 2:
        recommendations.append("Aap safe line ke qareeb hain. Thori mehnat aur chahiye.")
        recommendations.append("Apne kamzor subjects par focus karein (neeche table dekhein).")
        recommendations.append("Rozana ki handwriting aur homework check karwayein.")
    else:
        recommendations.append("Bohat khoob! Aap track par hain.")
        recommendations.append("Apna pace barhayein (e.g., 4 sawal rozana) taake 800+ marks ka target mile.")
        recommendations.append("Consistency barkarar rakhein.")

    # ---- 5. Weekly Trend for Chart ----
    by_week = OrderedDict()
    for ev in events:
        pct = ev["score"] / ev["max"] * 100.0
        wk = ev["date"].isocalendar()
        key = f"{wk[0]}-W{wk[1]:02d}"
        by_week.setdefault(key, []).append(pct)
    
    weekly = []
    for k in sorted(by_week.keys()):
        vals = by_week[k]
        weekly.append({
            "week": k,
            "pct": round(sum(vals) / len(vals), 1),
            "count": len(vals),
        })

    weekly = weekly[-20:] # Max 20 points for chart
    spark = []
    if len(weekly) >= 2:
        w = 600
        h = 120
        step = w / (len(weekly) - 1)
        for i, r in enumerate(weekly):
            x = i * step
            y = h - (r["pct"] / 100.0) * h
            spark.append(f"{x:.1f},{y:.1f}")
    spark_points = " ".join(spark)

    # ---- 6. Subject-wise ----
    subs = {}
    for ev in events:
        pct = ev["score"] / ev["max"] * 100.0
        subs.setdefault(ev["subject"], []).append((ev["date"], pct))
    
    subject_rows = []
    for sname, rows in sorted(subs.items()):
        rows.sort()
        first3 = [p for _, p in rows[:3]]
        last3 = [p for _, p in rows[-3:]]
        f = round(sum(first3) / len(first3), 1) if first3 else None
        l = round(sum(last3) / len(last3), 1) if last3 else None
        delta = round(l - f, 1) if (f is not None and l is not None) else None
        
        # Add specific warning if subject is very weak
        if l is not None and l < 40:
            recommendations.append(f"⚠️ {sname}: Failing (under 40%). Zaroori hai ke isay dobara parhein.")

        subject_rows.append({
            "name": sname,
            "count": len(rows),
            "first_avg": f,
            "last_avg": l,
            "delta": delta,
        })

    # --- FETCH WEAK KCS FOR REMEDIATION DRILLS ---
    from exams.models import Submission, KnowledgeComponent
    from django.db.models import F
    
    # Find recent submissions where the student scored below 60%
    weak_subs = Submission.objects.filter(
        exam__student=student,
        ai_score__lt=F('exam__max_marks') * 0.6
    ).select_related('exam').order_by('-created_at')[:10]
    
    weak_kcs = []
    seen_codes = set()
    for sub in weak_subs:
        kc_code = sub.exam.kc_code
        if kc_code and kc_code not in seen_codes:
            kc = KnowledgeComponent.objects.filter(code=kc_code).first()
            # Fallback: If DB is empty, use AI-generated ladder from the submission
            ladder_data = kc.socratic_ladder if (kc and kc.socratic_ladder) else sub.ai_raw.get('socratic_ladder', [])
            if kc and ladder_data:
                # Create a mock object to pass to the template
                kc.socratic_ladder = ladder_data
                if not kc.story:
                    kc.story = sub.ai_raw.get('concept_story', '')
                weak_kcs.append(kc)
                seen_codes.add(kc_code)
    # ----------------------------------------------

    # ── AI DIAGNOSIS BRIDGE (MySQL-safe) ──
    from exams.models import AttemptLog
    latest_diagnoses = {}
    _ai_logs = AttemptLog.objects.filter(student=student).order_by('-created_at')
    for _log in _ai_logs:
        _rj = _log.result_json or {}
        if isinstance(_rj, dict) and 'panel_diagnosis' in _rj:
            _subj = _log.question.paper.subject
            if _subj not in latest_diagnoses:
                latest_diagnoses[_subj] = _rj.get('chief_examiner', {})
        if len(latest_diagnoses) >= 8:  # cap for performance
            break

    context = {
        'student': student,
        'exam_dates': exam_dates,
        'weekly': weekly,
        'weak_kcs': weak_kcs,
        'spark_points': spark_points,
        'subject_rows': subject_rows,
        'total_exams': total_exams,
        'overall_pct': overall_pct,
        'total_mistakes': total_mistakes,
        'total_score': int(total_score),
        'total_max': int(total_max),
        'first_day': exams.first().exam_date if exams.exists() else None,
        'last_day': exams.last().exam_date if exams.exists() else None,
        'board_line': 33,
        'safe_line': 40,
        # MTSS Context
        'tier': tier,
        'tier_label': tier_label,
        'tier_class': tier_class,
        'tier_icon': tier_icon,
        'recommendations': recommendations,
        'trend_delta': round(trend_delta, 1),
        'latest_diagnoses': latest_diagnoses,
    }

    # --- EXPERT PANEL DASHBOARD DATA ---
    from exams.services.master_plan_panel import (
        build_master_plan, get_expert_panel_status, get_accuracy_trend, get_mizan_trend,
    )
    from exams.services.points_ledger import get_balance
    context['point_balance'] = get_balance(student)
    context['master_plan'] = build_master_plan(student)
    context['experts'] = get_expert_panel_status(student)
    context['chart_accuracy'] = get_accuracy_trend(student)
    context['chart_mizan'] = get_mizan_trend(student)
    # -----------------------------------

    return render(request, "exams/portal_progress.html", context)


@login_required(login_url="portal-login")
def portal_detail_step(request, exam_id, step_number):
    """Handle one POST from the 4-step reasoning widget.

    Steps: 1 (read model), 2 (faded answers), 3 (rewrite), 4 (submit).
    Gated: a step cannot start until its predecessor is complete.

    Standards: Sweller et al. (2011) completion strategy;
    Hattie & Timperley (2007) where-to-next; OWASP ASVS 4.3.1 (auth);
    5.1.3 (input validation); Rule 10 (one canonical state row per
    student-exam pair).
    """
    from django.http import JsonResponse, HttpResponseNotAllowed, HttpResponseNotFound
    from django.utils import timezone as _tz

    if request.method != "POST":
        return HttpResponseNotAllowed(["POST"])

    student = None
    try:
        student = Student.objects.get(student_user=request.user, is_active=True)
    except Student.DoesNotExist:
        try:
            student = Student.objects.get(parent_user=request.user, is_active=True)
        except Student.DoesNotExist:
            return HttpResponseNotFound("No student linked.")

    try:
        exam = Exam.objects.get(id=exam_id, student=student)
    except Exam.DoesNotExist:
        return HttpResponseNotFound("Exam not found.")

    if step_number not in (1, 2, 3, 4):
        return HttpResponseNotFound("Invalid step.")

    state, _ = ReasoningStep.objects.get_or_create(
        student=student, exam=exam,
        defaults={"current_step": 1, "completed_steps": []},
    )
    completed = list(state.completed_steps or [])

    if step_number > 1 and (step_number - 1) not in completed:
        return JsonResponse(
            {"ok": False, "error": "Pehle pichla qadam mukammal karein."},
            status=400,
        )
    if step_number in completed:
        return JsonResponse({"ok": True, "already": True,
                             "next": state.current_step})

    if step_number == 2:
        faded = {}
        for k, v in request.POST.items():
            if k.startswith("blank_"):
                faded[k[len("blank_"):]] = (v or "").strip()
        state.faded_answers = faded
    elif step_number == 3:
        text = (request.POST.get("rewrite") or "").strip()
        if len(text) < 10:
            return JsonResponse(
                {"ok": False, "error": "Thora aur likhein (10+ characters)."},
                status=400,
            )
        state.rewritten_answer = text
    elif step_number == 4:
        state.submitted_at = _tz.now()

    if step_number not in completed:
        completed.append(step_number)
    state.completed_steps = sorted(completed)
    state.current_step = min(step_number + 1, 4)
    state.save()
    return JsonResponse({"ok": True, "progress": state.progress_line(),
                         "next": state.current_step})


@login_required(login_url="portal-login")
def portal_profile(request):
    """Profile page. Teachers/owners can view any student via ?student_code=."""
    user = request.user
    from exams.models import Student, DailyQuestionCount, HealthScore, BadgeAward, StudentStreak
    from django.shortcuts import redirect
    from django.utils import timezone

    is_teacher = user.is_staff or user.is_superuser
    # Accept both ?student_code= (new) and ?code= (legacy cache)
    student_code = (request.GET.get('student_code') or request.GET.get('code') or '').strip()

    # === STUDENT SELECTION ===
    if is_teacher:
        if student_code:
            student = Student.objects.filter(code=student_code, is_active=True).first()
        else:
            # FALLBACK: teacher/owner sees first active student by default
            student = Student.objects.filter(is_active=True).order_by('code').first()
    else:
        student = Student.objects.filter(student_user=user, is_active=True).first()
        if not student:
            student = Student.objects.filter(parent_user=user, is_active=True).first()

    if not student:
        return redirect('portal-dashboard')

    # Dropdown options for teacher
    students = Student.objects.filter(is_active=True).order_by('code') if is_teacher else []

    # === CONTEXT (restore all expected variables) ===
    today = timezone.localdate()
    dqc, _ = DailyQuestionCount.objects.get_or_create(student=student, date=today)
    today_completed_count = dqc.completed_count
    target_total = (student.daily_question_count or 1) * 8  # 8 books
    total_badges = BadgeAward.objects.filter(student=student).count()

    # Pacing edit permission
    if is_teacher:
        can_edit = True
    else:
        can_edit = not (student.pacing_locked_until and student.pacing_locked_until > today)

    # Health score (for potential Mizan display in profile)
    hs, _ = HealthScore.objects.get_or_create(student=student)

    # Streak
    streak, _ = StudentStreak.objects.get_or_create(student=student)

    # ── AI DIAGNOSIS BRIDGE ──
    from exams.models import AttemptLog

    context = {
        'student': student,
        'students': students,
        'audience': 'teacher' if is_teacher else 'student',
        'daily_question_count': student.daily_question_count,
        'can_edit_pacing': can_edit,
        # Restoration of original context variables:
        'today_completed_count': today_completed_count,
        'target_total': target_total,
        'total_badges': total_badges,
        'kzm_score': hs.score if hs else 500,
        'kzm_band': hs.band if hs else 'NEUTRAL',
        'streak': streak.current_streak if streak else 0,
    }
    return render(request, "exams/portal_profile.html", context)


def _profile_audience(user):
    """Return (audience, student). Audience in {teacher,parent,student}."""
    if user.is_staff:
        return "teacher", None
    s = _current_student(user)
    if s is None:
        return None, None
    if _is_student_user(user):
        return "student", s
    return "parent", s


@login_required(login_url="portal-login")
def portal_study(request):
    """Understanding Path (Section 9). GET shows stories; POST saves a reflection."""
    user = request.user
    student = _current_student(user)
    if student is None:
        return _no_student_redirect(request)

    is_student = _is_student_user(user)
    message = ""
    error = ""

    if request.method == "POST":
        if not is_student:
            error = "Sirf student apni reflection likh sakta hai."
        else:
            story_id = request.POST.get("story_id", "").strip()
            text = (request.POST.get("reflection_text") or "").strip()
            if not story_id.isdigit():
                error = "Story nahi mili."
            elif len(text.split()) < 5:
                error = "Kam az kam 5 lafz likhein."
            elif len(text) > 2000:
                error = "Bohat lamba jawab hai. 3 lines mein likhein."
            else:
                from .models import StoryLecture, StoryReflection
                try:
                    story = StoryLecture.objects.get(pk=int(story_id))
                except StoryLecture.DoesNotExist:
                    error = "Story nahi mili."
                else:
                    existing = StoryReflection.objects.filter(
                        student=student, story=story).first()
                    if existing:
                        error = "Aap ne is story par pehle hi likh diya hai."
                    else:
                        StoryReflection.objects.create(
                            student=student, story=story, reflection_text=text)
                        message = "Shukriya. Aap ki reflection mehfooz ho gayi."

    from .models import StoryLecture, StoryReflection
    _cls = (student.student_class or '').strip().lower()
    from exams.utils_class import allowed_classes_for
    _allowed_classes = allowed_classes_for(_cls) or ([_cls] if _cls else [])
    qs = StoryLecture.objects.filter(
        student_class__in=_allowed_classes
    ).order_by("teaching_date", "subject", "question_index")
    latest_date = qs.order_by("-teaching_date").values_list("teaching_date", flat=True).first()
    stories = list(qs.filter(teaching_date=latest_date)) if latest_date else []

    reflections = {
        r.story_id: r for r in StoryReflection.objects.filter(
            student=student, story__in=stories)
    }
    for s in stories:
        s.current_reflection = reflections.get(s.id)
        if s.current_reflection:
            words = len(s.current_reflection.reflection_text.split())
            if words < 10:
                s.current_reflection.quality_label = "Needs Detail"
                s.current_reflection.quality_class = "tag--negative"
            elif words < 30:
                s.current_reflection.quality_label = "Good"
                s.current_reflection.quality_class = "tag--neutral"
            else:
                s.current_reflection.quality_label = "Excellent"
                s.current_reflection.quality_class = "tag--positive"

    # MTSS Focus: find weak subject from recent exam scores (only flag if < 60%)
    weak_subject = None
    try:
        from exams.models import Exam
        subject_scores = {}
        recent_exams = Exam.objects.filter(student=student).order_by("-exam_date")[:40]
        for e in recent_exams:
            sub = e.submissions.order_by("-created_at").first()
            if sub and sub.ai_score is not None and e.max_marks and e.subject:
                pct = (float(sub.ai_score) / float(e.max_marks)) * 100.0
                subject_scores.setdefault(e.subject, []).append(pct)
        if subject_scores:
            avg_by_subject = {k: sum(v) / len(v) for k, v in subject_scores.items()}
            lowest_subject = min(avg_by_subject, key=avg_by_subject.get)
            if avg_by_subject[lowest_subject] < 60.0:
                weak_subject = lowest_subject
    except Exception:
        weak_subject = None

    # Reorder: weak subject stories appear first
    if weak_subject:
        stories.sort(key=lambda s: (0 if s.subject == weak_subject else 1, s.subject, s.question_index))

    from collections import OrderedDict
    by_subject = OrderedDict()
    for s in stories:
        by_subject.setdefault(s.subject, []).append(s)

    return render(request, "exams/portal_study.html", {
        'all_subjects': locals().get('all_subjects', []),
        "student": student,
        "is_student": is_student,
        "teaching_date": latest_date,
        "by_subject": by_subject,
        "weak_subject": weak_subject,
        "message": message,
        "error": error,
    })


@login_required(login_url="portal-login")
def portal_lecture_request(request):
    """Student flags a KC they still do not understand (Section 18.1).

    Creates one LectureRequest (OPEN). Idempotent: if an OPEN request
    already exists for this student+KC, no duplicate is created.
    Standards: Wiggins and McTighe 2005 (backward design); Hattie and
    Timperley 2007 (feed-forward); EU AI Act Art.14 (human oversight);
    ISO 27701 7.2.8; Rule 10 (one canonical writer).
    """
    from django.shortcuts import redirect
    from .models import KnowledgeComponent, LectureRequest

    if request.method != "POST":
        return redirect("portal-detail")

    student = _current_student(request.user)
    if student is None or not _is_student_user(request.user):
        return redirect("portal-detail")

    kc_code = (request.POST.get("kc_code") or "").strip().upper()
    note = (request.POST.get("note") or "").strip()[:2000]

    if not kc_code:
        return redirect("portal-detail")

    kc = KnowledgeComponent.objects.filter(
        code=kc_code, is_active=True).first()
    if kc is None:
        return redirect("portal-detail")

    existing = LectureRequest.objects.filter(
        student=student, kc=kc, status="OPEN").exists()
    if not existing:
        LectureRequest.objects.create(
            student=student, kc=kc, note=note, status="OPEN")

    return redirect("portal-detail")


@login_required
def portal_upload_center(request):
    """Show locked questions grouped by session (Morning/Evening) and filtered by the daily mission ledger."""
    from exams.models import Student, StudentQuestionLock, EngineState
    from exams.models_delegation import TaskDelegation
    from exams.models_day_mission import StudentDayMission
    from django.utils import timezone
    from django.contrib import messages
    from exams.services.daily_code import get_or_create_row, BOOK_ABBR

    student = Student.objects.filter(student_user=request.user, is_active=True).first()
    if not student:
        return redirect('portal-dashboard')

    has_key = TaskDelegation.objects.filter(
        assignee=request.user,
        task_type__in=['QUESTION_UPLOAD', 'PAPER_UPLOAD'],
        expires_at__gt=timezone.now(),
    ).exists()

    if not has_key and not (request.user.is_staff or request.user.is_superuser):
        messages.error(request, 'Upload key required. It may have expired.')
        return redirect('portal-exam-token-status')

    is_choice_test = TaskDelegation.objects.filter(
        assignee=request.user,
        task_type__in=['QUESTION_UPLOAD', 'PAPER_UPLOAD'],
        expires_at__gt=timezone.now(),
        delegation_mode='CHOICE'
    ).exists()

    from exams.models import StudentDailyCode
    from datetime import timedelta

    engine = EngineState.objects.filter(id=1).first()
    current_day = engine.get_current_day() if (engine and engine.has_started) else 1

    # ── ALLOW MANUAL DAY SELECTION (GET param) ──
    requested_day = request.GET.get('day', '').strip()
    if requested_day.isdigit():
        day_num = max(1, min(120, int(requested_day)))
        request.session['mission_override'] = day_num - current_day
    else:
        # ── RESPECT CALENDAR OVERRIDE (Day 2 click) ──
        override = request.session.get('mission_override', 0)
        day_num = max(1, min(120, current_day + override))
    target_date = engine.start_date + timedelta(days=day_num - 1)

    # Fetch codes specifically for the TARGET date
    code_row = StudentDailyCode.objects.filter(student=student, date=target_date).first()
    codes = code_row.per_book_codes if code_row else {}

    # Allow explicit shift selection via GET parameter. Default to student's assigned shift.
    requested_shift = request.GET.get('shift', '').strip().lower()
    if requested_shift in ('morning', 'evening'):
        session = requested_shift
    else:
        session = (student.shift or 'morning').strip().lower()
        if session not in ('morning', 'evening'):
            session = 'morning'
            
    session_codes = codes.get(session, {}) if isinstance(codes, dict) else {}

    # PHASE 10: Visibility gate
    from exams.models_day_mission import DailyCodeVisibility as _DCV_uc
    from exams.services.daily_code import SUBJECT_SESSION, BOOK_ABBR
    from exams.models_day_mission import DayAttemptPolicy
    from django.db.models import Q

    # Check for active retake
    _sc = (student.student_class or '').strip()
    _sh = (student.shift or '').strip().lower()
    _retake_policy = DayAttemptPolicy.objects.filter(
        status='PAST_REATTEMPT', date=target_date
    ).filter(
        Q(target_student=student) |
        Q(target_student__isnull=True, target_class=_sc, target_shift=_sh) |
        Q(target_student__isnull=True, target_class=_sc, target_shift='') |
        Q(target_student__isnull=True, target_class='', target_shift=_sh) |
        Q(target_student__isnull=True, target_class='', target_shift='')
    ).first()

    def _resolve_vis_uc(d, stu):
        sc = (stu.student_class or '').strip()
        sh = (stu.shift or '').strip().lower()
        v = _DCV_uc.objects.filter(date=d, target_student=stu).first()
        if v: return v
        if sc and sh:
            v = _DCV_uc.objects.filter(date=d, target_student__isnull=True, target_class=sc, target_shift=sh).first()
            if v: return v
        if sc:
            v = _DCV_uc.objects.filter(date=d, target_student__isnull=True, target_class=sc, target_shift='').first()
            if v: return v
        if sh:
            v = _DCV_uc.objects.filter(date=d, target_student__isnull=True, target_class='', target_shift=sh).first()
            if v: return v
        return _DCV_uc.objects.filter(date=d, target_student__isnull=True, target_class='', target_shift='').first()

    _vis_uc = _resolve_vis_uc(target_date, student)
    
    is_session_published = False
    if _vis_uc:
        if session == 'morning' and getattr(_vis_uc, 'morning_visible', _vis_uc.is_visible):
            is_session_published = True
        elif session == 'evening' and getattr(_vis_uc, 'evening_visible', _vis_uc.is_visible):
            is_session_published = True
    
    has_active_retake = (_retake_policy is not None)

    required_subjects = []
    
    if is_session_published or has_active_retake or has_key:
        # INDUSTRY STANDARD FIX: Filter subjects strictly by the active session (Morning/Evening)
        allowed_subjects = [subj for subj, sess in SUBJECT_SESSION.items() if sess == session]
        
        # Get all SDM rows for the day
        from datetime import timedelta
        from django.utils import timezone
        from exams.models import EngineState
        from exams.models_day_mission import DailyCodeVisibility
        from exams.services.daily_code import SUBJECT_SESSION
        
        _eng_shift = EngineState.objects.filter(id=1).first()
        _target_date = (_eng_shift.start_date + timedelta(days=day_num - 1)) if (_eng_shift and _eng_shift.start_date) else timezone.localdate()
        _vis_dc = DailyCodeVisibility.objects.filter(date=_target_date).first()
        _morning_vis = getattr(_vis_dc, 'morning_visible', False) if _vis_dc else False
        _evening_vis = getattr(_vis_dc, 'evening_visible', False) if _vis_dc else False
        
        missions = StudentDayMission.objects.filter(
            student=student,
            day_number=day_num,
            question__paper__superseded_at__isnull=True,
        )
        
        _hidden_subs = []
        for subj, sess in SUBJECT_SESSION.items():
            _vis = DailyCodeVisibility.objects.filter(date=_target_date, target_student=student).first()
            if not _vis:
                _s_class = (student.student_class or '').strip()
                _vis = DailyCodeVisibility.objects.filter(date=_target_date, target_class=_s_class).first()
            if not _vis:
                _vis = DailyCodeVisibility.objects.filter(date=_target_date, target_student__isnull=True, target_class='').first()
                
            if not _vis:
                _hidden_subs.append(subj)
                continue
                
            if sess == 'morning':
                is_vis = _vis.morning_visible
            else:
                is_vis = _vis.evening_visible
                
            if not is_vis:
                _hidden_subs.append(subj)
                
        if _hidden_subs:
            missions = missions.exclude(subject__in=_hidden_subs)
            
        missions = missions.select_related('question', 'question__paper').order_by('subject', 'position')
        
        # Group missions by subject
        grouped_missions = {}
        for m in missions:
            subj = m.subject or (m.question.paper.subject if m.question.paper else 'Unknown')
            if subj not in allowed_subjects:
                continue
            if subj not in grouped_missions:
                grouped_missions[subj] = []
            grouped_missions[subj].append(m)

        from exams.models import RetakeRequest, AttemptLog as _AL
        for subj, m_list in grouped_missions.items():
            abbr = BOOK_ABBR.get(subj, subj[:2].upper())
            expected_code = session_codes.get(abbr)
            is_past_day = (day_num < current_day)

            if not m_list:
                continue

            _qids = [m.question_id for m in m_list]
            _num_questions = max(len(_qids), 1)

            # Latest APPROVED and any PENDING for this (day, subject)
            _approved = RetakeRequest.objects.filter(
                student=student, day_number=day_num, subject=subj, status='APPROVED'
            ).order_by('-processed_at').first()
            _pending = RetakeRequest.objects.filter(
                student=student, day_number=day_num, subject=subj, status='PENDING'
            ).first()

            _retake_status = None
            _attempts_granted = 0
            _attempts_used = 0
            _can_upload = False
            _needs_request = False

            def _count_attempts(since_dt=None):
                qs = _AL.objects.filter(
                    student=student, question_id__in=_qids, is_physical=True,
                    target_day_number=day_num
                )
                if since_dt:
                    qs = qs.filter(created_at__gte=since_dt)
                raw = qs.count()
                if is_choice_test and raw > 0:
                    raw = raw // _num_questions
                return raw

            if _pending and not _approved:
                # Fresh PENDING — waiting for teacher
                _retake_status = 'PENDING'
                _can_upload = False
            elif _approved:
                # Count ONLY attempts after this approval was granted
                _attempts_granted = _approved.attempts_granted
                _attempts_used = _count_attempts(since_dt=_approved.processed_at)
                _retake_status = 'APPROVED'
                if _attempts_used < _attempts_granted:
                    _can_upload = True
                else:
                    _can_upload = False
                    _needs_request = True
            else:
                # No approval, no pending
                _attempts_used = _count_attempts()
                if is_past_day:
                    # Past day = always needs approval
                    _can_upload = False
                    _needs_request = True
                else:
                    # Current day: 1 free first attempt
                    if _attempts_used < 1:
                        _can_upload = True
                    else:
                        _can_upload = False
                        _needs_request = True

            target_m = m_list[0]
            if expected_code is not None:
                for m in m_list:
                    if m.position == expected_code:
                        target_m = m
                        break

            required_subjects.append({
                'subject': subj,
                'required_q_num': target_m.position,
                'question': target_m.question,
                'day_number': day_num,
                'is_past_day': is_past_day,
                'retake_status': _retake_status,
                'attempts_used': _attempts_used,
                'attempts_granted': _attempts_granted,
                'can_upload': _can_upload,
                'needs_request': _needs_request,
                'lock': None,
                'has_assigned': True,
                'has_active_code': expected_code is not None,
            })

    return render(request, 'exams/portal_upload_center.html', {
        'all_subjects': locals().get('all_subjects', []),
        'student': student,
        'required_subjects': required_subjects,
        'is_choice_test': is_choice_test,
        'session': session,
        'target_day': day_num,
        'day_options': list(range(1, max(current_day, day_num) + 1)),
    })


@login_required
def portal_test_upload_guide(request):
    """Roman Urdu guide for the anti-cheat test upload process."""
    return render(request, 'exams/portal_test_upload_guide.html')


@login_required
def personal_todo_action(request):
    """Secure API for managing PersonalTodo items. Enforces strict IDOR protection."""
    import json
    from django.http import JsonResponse
    from django.shortcuts import get_object_or_404
    from exams.models import PersonalTodo

    if request.method != 'POST':
        return JsonResponse({'error': 'POST required'}, status=405)

    try:
        data = json.loads(request.body)
    except json.JSONDecodeError:
        return JsonResponse({'error': 'Invalid JSON'}, status=400)

    action = data.get('action')
    
    if action == 'add':
        title = (data.get('title') or '').strip()
        if not title:
            return JsonResponse({'error': 'Title required'}, status=400)
        todo = PersonalTodo.objects.create(user=request.user, title=title[:255])
        return JsonResponse({'status': 'ok', 'id': todo.id, 'title': todo.title})

    elif action == 'toggle':
        todo_id = data.get('id')
        # IDOR PROTECTION: Scoped strictly to request.user
        todo = get_object_or_404(PersonalTodo, id=todo_id, user=request.user)
        todo.is_completed = not todo.is_completed
        todo.save(update_fields=['is_completed', 'updated_at'])
        return JsonResponse({'status': 'ok', 'is_completed': todo.is_completed})

    elif action == 'delete':
        todo_id = data.get('id')
        # IDOR PROTECTION: Scoped strictly to request.user
        todo = get_object_or_404(PersonalTodo, id=todo_id, user=request.user)
        todo.delete()
        return JsonResponse({'status': 'ok'})

    return JsonResponse({'error': 'Invalid action'}, status=400)


@login_required(login_url="portal-login")
def portal_full_leaderboard(request):
    """Full leaderboard — students see own class, teachers can switch."""
    from exams.services.leaderboard import get_leaderboard
    from exams.models import Student
    from django.utils import timezone
    from django.contrib.auth import get_user_model

    user = request.user
    is_teacher = user.is_staff or user.is_superuser

    # Get student linked to current user
    student = _current_student(user)

    all_classes = list(
        Student.objects.filter(is_active=True)
        .values_list('student_class', flat=True)
        .distinct()
        .order_by('student_class')
    )
    # Filter out empty/None
    all_classes = sorted([c for c in all_classes if c and c.strip()])

    current_class = None
    if is_teacher:
        # TEACHER: use ?class= parameter, default to first class
        current_class = request.GET.get('class', '').strip()
        if current_class not in all_classes:
            current_class = all_classes[0] if all_classes else '9'

        student = Student.objects.filter(
            is_active=True, student_class=current_class
        ).first()

        if student is None:
            return render(request, "exams/portal_full_leaderboard.html", {
        'all_subjects': locals().get('all_subjects', []),
                "student": None,
                "leaderboard": {"leaders": [], "viewer_rank": None, "total_students": 0, "scope_label": "", "viewer_started": False},
                "now": timezone.now(),
                "is_teacher": True,
                "all_classes": all_classes,
                "current_class": current_class,
                "class_subject_trophies": "{}",
            })
    else:
        # STUDENT: always use their own class
        if student is None:
            from django.http import HttpResponse
            return HttpResponse("No active student linked to this account.", status=404)
        current_class = student.student_class

    data = get_leaderboard(student, window=10000)

    from exams.models_trophy import TrophyEvent
    from exams.models import ModelQuestion
    import json as _json
    _tqs = list(TrophyEvent.objects.filter(student__student_class=current_class, count__gt=0, date__gte=datetime.date(2026, 11, 1), cancelled_at__isnull=True).values('event_key', 'subject', 'count'))
    _qids = [int(t['event_key'].split(':')[-1]) for t in _tqs if not t['subject'] and t['event_key'].startswith('Q_COMPLETE:') and t['event_key'].split(':')[-1].isdigit()]
    _qsubs = {q.id: q.paper.subject for q in ModelQuestion.objects.filter(id__in=_qids).select_related('paper')} if _qids else {}
    _class_subs = {}
    for t in _tqs:
        _subj = t['subject']
        if not _subj:
            _k = t['event_key']
            if _k.startswith('PAPER_COMPLETE:') and _k.count(':') >= 3: _subj = _k.split(':')[3]
            elif _k.startswith('DIARY_COMPLETE:') and _k.count(':') >= 3: _subj = _k.split(':')[3]
            elif _k.startswith('BACKFILL_CHOICE:'): _subj = _k.split(':')[-1]
            elif _k.startswith('Q_COMPLETE:'):
                try: _subj = _qsubs.get(int(_k.split(':')[-1]))
                except ValueError: pass
        _subj = _subj or 'General'
        _class_subs[_subj] = _class_subs.get(_subj, 0) + t['count']

    return render(request, "exams/portal_full_leaderboard.html", {
        'all_subjects': locals().get('all_subjects', []),
        "student": student,
        "leaderboard": data,
        "now": timezone.now(),
        "is_teacher": is_teacher,
        "all_classes": all_classes,
        "current_class": current_class,
        "class_subject_trophies": _json.dumps({k: v for k, v in _class_subs.items() if k != 'General'}),
    })


@login_required
def portal_my_duties(request):
    """Dedicated page for students to view and execute their assigned duties."""
    from exams.models_delegation import TaskDelegation
    from django.utils import timezone

    user = request.user
    # Fetch active duties using the unified TaskDelegation model
    delegated_tasks = TaskDelegation.objects.filter(
        assignee=user,
        expires_at__gt=timezone.now()
    ).order_by('expires_at')
    page_obj = paginate(request, delegated_tasks)
    delegated_tasks = page_obj.object_list

    return render(request, 'exams/portal_my_duties.html', {
        'all_subjects': locals().get('all_subjects', []),
        'delegated_tasks': delegated_tasks, 'page_obj': page_obj
    })


@login_required
@user_passes_test(_is_teacher, login_url="portal-login")
@csrf_exempt
def engine_toggle(request):
    if request.method == 'POST':
        try:
            data = json.loads(request.body)
            action = data.get('action')
            with transaction.atomic():
                state = EngineState.objects.select_for_update().get(id=1)
                if action == 'start':
                    state.is_running = True
                    state.has_started = True
                    state.remaining_seconds = EngineState.TOTAL_DURATION
                    state.last_updated = timezone.now()
                    state.save()
                elif action == 'pause':
                    state.is_running = False
                    state.save()
                elif action == 'resume':
                    state.is_running = True
                    state.save()
                elif action == 'stop':
                    EngineState.objects.filter(id=1).update(
                        is_running=False,
                        has_started=False,
                        remaining_seconds=EngineState.TOTAL_DURATION,
                        last_updated=None,
                    )
            return JsonResponse({'status': 'success'})
        except Exception as e:
            return JsonResponse({'status': 'error', 'message': str(e)}, status=400)
    return JsonResponse({'status': 'error'}, status=405)


@login_required
@csrf_exempt
def engine_status(request):
    state, _ = EngineState.objects.get_or_create(id=1)
    remaining = state.get_live_remaining()
    days = int(remaining // 86400)
    hours = int((remaining % 86400) // 3600)
    minutes = int((remaining % 3600) // 60)
    seconds = int(remaining % 60)
    try:
        current_day = state.get_current_day()
    except Exception:
        current_day = 1
    
    return JsonResponse({
        'running': state.is_running,
        'is_running': state.is_running,
        'current_day': current_day,
        'remaining_seconds': remaining,
        'time_up': remaining <= 0,
        'start_day': state.start_day,
        'has_started': state.has_started,
    })


@login_required
def update_pacing(request):
    if request.method == 'POST':
        pace = request.POST.get('daily_question_count')
        if pace in ['1', '2', '3', '4', '5', '6', '7', '8', '9', '10']:
            from django.utils import timezone
            from django.contrib import messages
            from datetime import timedelta
            
            student_code = request.POST.get('student_code')
            if student_code and request.user.is_staff:
                student = Student.objects.filter(code=student_code, is_active=True).first()
            else:
                student = Student.objects.filter(student_user=request.user, is_active=True).first()
                if not student:
                    student = Student.objects.filter(parent_user=request.user, is_active=True).first()
                
            if student:
                today = timezone.now().date()
                is_teacher = request.user.is_staff
                is_parent = hasattr(request.user, 'student_as_parent')
                is_student = hasattr(request.user, 'student_self')
                
                locked = False
                is_owner = request.user.is_superuser
                if not is_teacher and not is_owner:
                    if is_student and student.pacing_locked_until and student.pacing_locked_until > today:
                        locked = True
                        messages.error(request, f"Aap pacing {student.pacing_locked_until.strftime('%d %b %Y')} tak change nahi kar sakte.")
                    elif is_parent and student.parent_pacing_locked_until and student.parent_pacing_locked_until > today:
                        locked = True
                        messages.error(request, f"Aap parent ke taur par pacing {student.parent_pacing_locked_until.strftime('%d %b %Y')} tak change nahi kar sakte.")
                
                if not locked:
                    student.daily_question_count = int(pace)
                    update_fields = ['daily_question_count']
                    if is_student:
                        student.pacing_locked_until = today + timedelta(days=30)
                        update_fields.append('pacing_locked_until')
                    elif is_parent:
                        student.parent_pacing_locked_until = today + timedelta(days=30)
                        update_fields.append('parent_pacing_locked_until')
                    student.save(update_fields=update_fields)
                    messages.success(request, f"Pacing successfully saved to {pace} for {student.name}.")
            else:
                messages.error(request, "Student record not found.")
                
    # Redirect with student_code to preserve selection + cache buster
    redirect_url = "/api/portal/profile/?v=3"
    if request.user.is_staff and request.POST.get('student_code'):
        redirect_url += f"&student_code={request.POST.get('student_code')}"
    return redirect(redirect_url)


# Fix anonymous user crash
from django.contrib.auth.decorators import login_required
@login_required(login_url='/login/')
def portal_dashboard(request):
    if not request.user.is_authenticated:
        return redirect('portal-login')
    from exams.models import PortalFeature, StudentTaskGate, HealthScore, BadgeAward, DailyQuestionCount, StudentStreak
    from django.utils import timezone
    from django.db.models import Q as _Q
    from .models import ParentReport, PeerPair

    user = request.user
    student = None
    try:
        student = Student.objects.get(student_user=user, is_active=True)
    except Student.DoesNotExist:
        try:
            student = Student.objects.get(parent_user=user, is_active=True)
        except Student.DoesNotExist:
            student = None
            
    if student is None:
        return _no_student_redirect(request)

    from exams.services.leaderboard import get_leaderboard

    from exams.models_delegation import TaskDelegation
    _del_target = student.student_user if student.student_user else user
    delegated_tasks = TaskDelegation.objects.filter(
        assignee=_del_target.student_user if hasattr(_del_target, 'student_user') else _del_target,
        expires_at__gt=timezone.now()
    ).order_by('expires_at')

    # Build friendly delegated links (industry standard: recognition over recall)
    TASK_LABELS = {
        'ATTENDANCE': ('📋 Mark Attendance', '/api/portal/teacher/control/?tab=hazri'),
        'LATE_MINUTES': ('⏱️ Late Minutes Entry', '/api/portal/teacher/control/?tab=hazri'),
        'EXAM_SUPERVISION': ('📝 Exam Supervision', '/discipline/sessions/'),
        'UNIFORM_CHECK': ('👔 Uniform Check', '/discipline/daily/'),
        'BEHAVIOR_LOGGING': ('⚠️ Behavior Logging', '/discipline/violations/'),
        'DAILY_TASKS_CHECK': ('✅ Daily Tasks Check', '/discipline/daily/'),
        'PAPER_GRADING': ('📄 Paper Grading', '/api/portal/teacher/paste/'),
        'GLOSSARY_ASSIGN': ('📚 Assign Glossary', '/api/portal/teacher/assign-glossary/'),
        'PEER_REVIEW': ('👥 Peer Review', '/api/portal/teacher/peers/'),
        'FEE_VERIFICATION': ('💵 Fee Verification', '/academy/?tab=fees'),
        'DEVICE_APPROVAL': ('📱 Device Approval', '/integrity/my-devices/'),
        'DOCUMENT_VAULT': ('🗄️ Document Vault', '/vault/'),
        'SUPPORT_TICKETS': ('🎫 Support Tickets', '/api/portal/teacher/support/'),
        'LECTURE_REQUESTS': ('🎓 Lecture Requests', '/api/portal/teacher/lectures/'),
        'PAPER_UPLOAD': ('📤 Paper Upload', '/api/portal/teacher/bulk/'),
        'CUSTOM_PAGE': ('🔗 Custom Page Access', ''),
        'BULK_DIARY': ('📝 Bulk Diary', '/discipline/class-homework/bulk-diary/'),
    }

    delegated_links = []
    for d in delegated_tasks:
        label, default_url = TASK_LABELS.get(d.task_type, (f'🔑 {d.task_type}', ''))
        url = (d.custom_url or '').strip() or default_url
        if not url:
            continue

        # Special case: Class & Homework → also surface the Bulk Diary page
        extra_links = []
        if 'class-homework' in url and 'bulk-diary' not in url:
            label = '📋 Class & Homework'
            extra_links.append({
                'label': '📝 Bulk Diary',
                'url': '/discipline/class-homework/bulk-diary/',
            })

        delegated_links.append({
            'label': label,
            'url': url,
            'expires_at': d.expires_at,
            'time_left': d.expires_at - timezone.now(),
        })
        for extra in extra_links:
            delegated_links.append({
                'label': extra['label'],
                'url': extra['url'],
                'expires_at': d.expires_at,
                'time_left': d.expires_at - timezone.now(),
            })

    # Shared Data
    _streak, _ = StudentStreak.objects.get_or_create(student=student)
    _badges = BadgeAward.objects.filter(student=student).order_by('-awarded_at')
    _total_badges = _badges.count()
    _recent_badges = list(_badges[:3])
    from exams.services.trophy_service import total_trophies
    _total_trophies = total_trophies(student)
    _today = timezone.localdate()

    # Unified dashboard: All students route to portal.html


    # ==========================================
    # 9TH GRADE BRANCH (Mizan)
    # ==========================================
    _kzm, _ = HealthScore.objects.get_or_create(student=student)

    # Layer 2: Lazy recompute — ensure dashboard is always accurate.
    # Only triggers for 9th-class (algorithm short-circuits for others).
    try:
        from exams.mizan_algorithm import recompute as _mizan_recompute, compute as _mizan_compute
        _r = _mizan_compute(student)
        # Only write if score changed (avoids needless DB writes on every load)
        if _r.get("score") != _kzm.score:
            _mizan_recompute(student)
            _kzm.refresh_from_db()
    except Exception:
        pass  # Never block the dashboard

    _today_count, _ = DailyQuestionCount.objects.get_or_create(student=student, date=_today)
    _today_completed = _today_count.completed_count
    
    # FIX: Use AttemptLog to count ALL uploads today (even failures), not just TrophyEvents (passes)
    try:
        from exams.models import AttemptLog
        _today_attempts = AttemptLog.objects.filter(student=student, created_at__date=_today, cancelled_at__isnull=True).count()
        if _today_attempts > _today_completed:
            _today_completed = _today_attempts
    except Exception:
        pass
    _target_total = student.daily_question_count * 8

    # Industry Standard: Attempted vs Passed are separate metrics
    from exams.models_trophy import TrophyEvent
    from django.db.models import Sum as _Sum_Check
    _today_passed = TrophyEvent.objects.filter(
        student=student, date=_today, count__gt=0, cancelled_at__isnull=True
    ).aggregate(t=_Sum_Check('count'))['t'] or 0


    # Daily Averages Calculation
    _eng = EngineState.objects.filter(id=1).first()
    _current_day = _eng.get_current_day() if (_eng and _eng.has_started) else 1
    _current_day = max(1, _current_day)
    
    _mizan_gain = max(0, _kzm.score - 500)
    
    # --- >1000 Appreciation Logic ---
    is_above_1000 = _kzm.score > 1000
    actual_score = _kzm.score

    try:
        from exams.mizan_algorithm import compute as _m_compute
        _m_data = _m_compute(student)
        _max_possible_m = _m_data.get("max_possible", 5760)
        _gain_per_trophy_m = _m_data.get("gain_per_trophy", 500.0 / 5760)
    except Exception:
        _max_possible_m = 5760
        _gain_per_trophy_m = 500.0 / 5760
    _mizan_per_day = round((_total_trophies * _gain_per_trophy_m) / max(_current_day, 1), 2)
    _trophies_per_day = round(_total_trophies / _current_day, 2)
    _badges_per_day = round(_total_badges / _current_day, 2)

    # Fix Pace Projections (Roman Urdu)

    # Daily Averages Calculation
    _eng = EngineState.objects.filter(id=1).first()
    _current_day = _eng.get_current_day() if (_eng and _eng.has_started) else 1
    _current_day = max(1, _current_day)
    
    _mizan_gain = max(0, _kzm.score - 500)
    
    # --- >1000 Appreciation Logic ---
    is_above_1000 = _kzm.score > 1000
    actual_score = _kzm.score

    try:
        from exams.mizan_algorithm import compute as _m_compute
        _m_data = _m_compute(student)
        _max_possible_m = _m_data.get("max_possible", 5760)
        _gain_per_trophy_m = _m_data.get("gain_per_trophy", 500.0 / 5760)
    except Exception:
        _max_possible_m = 5760
        _gain_per_trophy_m = 500.0 / 5760
    _mizan_per_day = round((_total_trophies * _gain_per_trophy_m) / max(_current_day, 1), 2)
    _trophies_per_day = round(_total_trophies / _current_day, 2)
    _badges_per_day = round(_total_badges / _current_day, 2)

    # Fix Pace Projections (Roman Urdu)

    pace = student.daily_question_count or 1
    if pace == 6: proj = "Agar aap rozana 48 trophies (Pace 6) kamate rahein, toh maximum marks ke chance hain."
    elif pace == 5: proj = "Agar aap rozana 40 trophies (Pace 5) kamate rahein, toh 800+ marks ke chance hain."
    elif pace == 4: proj = "Agar aap rozana 32 trophies (Pace 4) kamate rahein, toh achi tarah pass hone ke chance hain."
    elif pace == 3: proj = "Agar aap rozana 24 trophies (Pace 3) kamate rahein, toh 6 kitabon mein pass hone ke chance hain."
    elif pace == 2: proj = "Agar aap rozana 12 trophies (Pace 2) kamate rahein, toh 4 kitabon mein pass hone ke chance hain."
    else: proj = "Aap ka pace set nahi hai. Baraye meharbani profile mein pace set karein."


    if _kzm.score >= 800: status = "Aap ki halat bohat achi hai (Excellent)."
    elif _kzm.score >= 500: status = "Aap ki halat theek hai (Neutral)."
    else: status = "Aap ki halat theek nahi hai, aap ko mehnat ki zaroorat hai."

    _coach_summary = f"{status} {proj}"


    subjects, days, overall_pct = _progress_for(student)
    headline_band = _band(overall_pct)
    if subjects:
        top = [s for s in subjects if s["band_key"] == "good"]
        low = [s for s in subjects if s["band_key"] == "low"]
        parts = []
        if top:
            parts.append("ne " + ", ".join(s["name"] for s in top[:3]) + " mein acha kaam kiya")
        if low:
            parts.append("aur " + ", ".join(s["name"] for s in low[:3]) + " mein thora kaam baqi hai")
        headline_text = student.name.split()[0] + " " + (" ".join(parts) if parts else "ne aaj tests diye.") + "."
    else:
        headline_text = "Abhi koi test nahi hua."

    att_total = Attendance.objects.filter(student=student).count()
    att_present = Attendance.objects.filter(student=student, present=True).count()
    attendance_pct = round(att_present / att_total * 100, 1) if att_total else 0
    
    reflection = _reflection_stats(student)
    
    latest_report = ParentReport.objects.filter(student=student).order_by("-date_to").first()
    
    peer_rows = []
    qs_peers = PeerPair.objects.filter(active=True).filter(
        _Q(tutor=student) | _Q(tutee=student)
    ).select_related("tutor", "tutee", "kc").order_by("kc__code")
    for pp in qs_peers:
        if pp.tutor_id == student.id:
            peer_rows.append({
                "role": "tutor",
                "partner": pp.tutee.name + " (" + pp.tutee.code + ")",
                "kc": pp.kc.code,
                "kc_title": pp.kc.title,
            })
        else:
            peer_rows.append({
                "role": "tutee",
                "partner": pp.tutor.name + " (" + pp.tutor.code + ")",
                "kc": pp.kc.code,
                "kc_title": pp.kc.title,
            })

    from exams.services.trophy_service import total_trophies, trophy_target
    _total_trophies = total_trophies(student)
    _trophy_target = trophy_target(student)
    _trophy_progress_pct = int(min(100, round(_total_trophies / _trophy_target * 100, 1))) if _trophy_target else 0
    # --- Board exam prediction ---
    try:
        from exams.models import EngineState as _EngState
        _eng = _EngState.objects.filter(id=1).first()
        _current_day = _eng.get_current_day() if (_eng and _eng.has_started) else 0
    except Exception:
        _current_day = 0
    _prediction = _board_prediction(student, _total_trophies, _current_day)

    # Phase EEE: Calculate handwriting points from ClassHomeworkRecord
    from discipline.models import ClassHomeworkRecord
    _recent_hw = list(ClassHomeworkRecord.objects.filter(student__linked_code=student.code, subject="", date__gte=timezone.localdate() - timezone.timedelta(days=13)).order_by("-date")[:14])
    _pts_per_hw = getattr(ClassHomeworkRecord, "PTS_HANDWRITING", 5)
    _hw_points = sum(_pts_per_hw for r in _recent_hw if r.handwriting_done)

    ctx = {
        "student": student, 
        "hw_points": _hw_points,
        "daily_question_count": student.daily_question_count, 
        "prediction": _prediction,
        "target_total": _target_total,
        "total_trophies": _total_trophies,
        "trophy_target": _trophy_target,
        "today_passed": _today_passed,
        "today_attempted": _today_completed,
        "is_above_1000": is_above_1000,
        "actual_score": actual_score,
        "trophy_progress_pct": _trophy_progress_pct,
        "today_completed_count": _today_completed, 
        "total_badges": _total_badges, 
        "recent_badges": _recent_badges,
        "streak": _streak.current_streak,
        "coach_summary": _coach_summary,
        "subjects": subjects, 
        "days": days,
        "kzm_score": _kzm.score, 
        "kzm_band": _kzm.band, 
        "kzm": _kzm,
        "overall_pct": overall_pct, 
        "attendance_pct": attendance_pct,
        "headline_band": headline_band, 
        "headline_text": headline_text,
        "reflection": reflection, 
        "peer_rows": peer_rows, 
        "latest_report": latest_report, 
        "delegated_tasks": delegated_tasks,
        "leaderboard": get_leaderboard(student, window=3),
        "mizan_per_day": _mizan_per_day,
        "trophies_per_day": _trophies_per_day,
        "badges_per_day": _badges_per_day,
    }
    ctx["task_portal_visible"] = bool(PortalFeature.objects.filter(
        key="task_portal", enabled=True).exists()) and not (
        StudentTaskGate.objects.filter(student=student, hidden=True).exists()
    )
    # [Phase W leftover removed — Phase CC cleanup]
    ctx["guide"] = {
        "title": "Dashboard Kaise Dekhein",
        "purpose": "Yeh aap ka main page hai jahan aap ki tamam performance dikhti hai.",
        "value": "Yahan aap Mizan Score (0-1000), aap ki Streak (kitne din lagatar kaam kiya), aur Aaj ka Mission dekh sakte hain.",
        "how_to": "Rozana ka mission mukammal karein taake trophies barhein. Har din kaam karein taake streak barhe.",
        "controls": "Top menu se 'Mere Kaam' par ja kar upload karein, ya 'Report Hub' se detail report dekhein.",
    }
    return render(request, "exams/portal.html", ctx)


# ══════════════════════════════════════════════════════════════════
# DAILY TROPHY CHART (Teacher Only)
# ══════════════════════════════════════════════════════════════════
from django.contrib.auth.decorators import login_required
from django.shortcuts import render, redirect
from django.utils import timezone
from django.db.models import Sum

@login_required
def portal_daily_trophy_chart(request):
    """Shows today's trophies per student per subject for a specific class."""
    if not (request.user.is_staff or request.user.is_superuser):
        return redirect('portal-dashboard')
        
    from exams.models import Student
    from exams.models_trophy import TrophyEvent
    
    today = timezone.localdate()
    
    # Class Selection (using Python set to avoid Django's default-ordering distinct bug)
    _raw_classes = Student.objects.filter(is_active=True).values_list('student_class', flat=True)
    all_classes = sorted(set(c for c in _raw_classes if c and c.strip()))
    current_class = request.GET.get('class', '10').strip()
    if current_class not in all_classes:
        current_class = all_classes[0] if all_classes else '10'

    # Fetch Students in class
    students = Student.objects.filter(is_active=True, student_class=current_class).order_by('code')
    
    # Fetch today's trophies (evening resolved below)
    trophies = list(TrophyEvent.objects.filter(
        date=today, student__student_class=current_class, count__gt=0, date__gte=datetime.date(2026, 11, 1), cancelled_at__isnull=True
    ).values('student_id', 'subject', 'event_key', 'count'))
    from exams.models import ModelQuestion
    import json as _json
    q_ids = [int(t['event_key'].split(':')[-1]) for t in trophies
        if not t['subject'] and t['event_key'].startswith('Q_COMPLETE:')]
    q_subjects = {q.id: q.paper.subject for q in ModelQuestion.objects.filter(id__in=q_ids).select_related('paper')}
    trophy_map = {}
    class_subject_trophies = {}
    for t in trophies:
        sid = t['student_id']; subj = t['subject']; key = t['event_key']
        if not subj:
            if key.startswith('PAPER_COMPLETE:') and key.count(':') >= 3: subj = key.split(':')[3]
            elif key.startswith('DIARY_COMPLETE:') and key.count(':') >= 3: subj = key.split(':')[3]
            elif key.startswith('BACKFILL_CHOICE:'): subj = key.split(':')[-1]
            elif key.startswith('Q_COMPLETE:'):
                try: subj = q_subjects.get(int(key.split(':')[-1]))
                except ValueError: pass
        subj = subj or 'General'
        trophy_map.setdefault(sid, {})
        trophy_map[sid][subj] = trophy_map[sid].get(subj, 0) + t['count']
        class_subject_trophies[subj] = class_subject_trophies.get(subj, 0) + t['count']

    # Define the fixed 9 columns based on the class
    if str(current_class).startswith('10'):
        active_subjects = ['Urdu', 'English', 'Pak Study', 'Mathematics', 'Chemistry', 'Physics', 'Tarjumatul Quran', 'Computer Science', 'Biology']
    else:
        active_subjects = ['Urdu', 'English', 'Islamiyat', 'Mathematics', 'Chemistry', 'Physics', 'Tarjumatul Quran', 'Computer Science', 'Biology']

    # Append any extra valid subjects found in the data (but not '')
    for t in trophies:
        subj = t['subject']
        if subj and subj not in active_subjects:
            active_subjects.append(subj)
    
    # Build rows for ALL students
    rows = []
    for s in students:
        s_trophies = trophy_map.get(s.id, {})
        total = sum(s_trophies.values())
        rows.append({
            'student': s,
            'subjects': s_trophies,
            'total': total
        })
            
    # Sort rows by total descending (highest trophies first)
    rows.sort(key=lambda x: x['total'], reverse=True)

    # Format Date with Day Name
    today_formatted = today.strftime('%d %b %Y (%A)')

    all_trophies = list(TrophyEvent.objects.filter(student__student_class=current_class, count__gt=0, date__gte=datetime.date(2026, 11, 1), cancelled_at__isnull=True).values('student_id', 'subject', 'event_key', 'count'))
    _qids2 = [int(t['event_key'].split(':')[-1]) for t in all_trophies if not t['subject'] and t['event_key'].startswith('Q_COMPLETE:')]
    _qsubs2 = {q.id: q.paper.subject for q in ModelQuestion.objects.filter(id__in=_qids2).select_related('paper')}
    all_time_trophy_map = {}
    for t in all_trophies:
        _sid, _subj, _key = t['student_id'], t['subject'], t['event_key']
        if not _subj:
            if _key.startswith('PAPER_COMPLETE:') and _key.count(':') >= 3: _subj = _key.split(':')[3]
            elif _key.startswith('DIARY_COMPLETE:') and _key.count(':') >= 3: _subj = _key.split(':')[3]
            elif _key.startswith('BACKFILL_CHOICE:'): _subj = _key.split(':')[-1]
            elif _key.startswith('Q_COMPLETE:'):
                try: _subj = _qsubs2.get(int(_key.split(':')[-1]))
                except ValueError: pass
        if _subj and _subj != 'General':
            all_time_trophy_map.setdefault(_sid, {})
            all_time_trophy_map[_sid][_subj] = all_time_trophy_map[_sid].get(_subj, 0) + t['count']

    return render(request, 'exams/portal_daily_chart.html', {
        'all_subjects': locals().get('all_subjects', []),
        'today': today,
        'today_formatted': today_formatted,
        'all_classes': all_classes,
        'current_class': current_class,
        'rows': rows,
        'active_subjects': active_subjects,
        'class_subject_trophies': _json.dumps({k: v for k, v in class_subject_trophies.items() if k != 'General'}),
        'trophy_map_json': _json.dumps({k: {sk: sv for sk, sv in v.items() if sk != 'General'} for k, v in trophy_map.items()}),
        'all_time_trophy_map_json': _json.dumps(all_time_trophy_map),
    })


@login_required
def portal_request_retake(request):
    """POST: Student requests a retake for a past-day or already-attempted book."""
    from exams.models import RetakeRequest, Student, EngineState, AttemptLog
    from exams.models_day_mission import StudentDayMission
    import uuid
    from datetime import datetime

    if request.method != 'POST':
        return redirect('portal-upload-center')

    student = Student.objects.filter(student_user=request.user, is_active=True).first()
    if not student:
        return redirect('portal-dashboard')

    eng = EngineState.objects.first()
    cur_day = eng.get_current_day() if (eng and eng.has_started) else 1

    day_number = request.POST.get('day_number', '').strip()
    subject = request.POST.get('subject', '').strip()

    if not day_number.isdigit() or not subject:
        messages.error(request, 'Invalid request. Provide day_number and subject.')
        return redirect('portal-upload-center')

    day_number = int(day_number)
    if day_number < 1 or day_number > cur_day:
        messages.error(request, 'Invalid day number.')
        return redirect('portal-upload-center')

    # Verify the student has SDM for this (day, subject)
    if not StudentDayMission.objects.filter(
        student=student, day_number=day_number, subject=subject
    ).exists():
        messages.error(request, f'No SDM record for Day {day_number} {subject}.')
        return redirect('portal-upload-center')

    # Check if there's already a PENDING or APPROVED-with-remaining request
    existing_pending = RetakeRequest.objects.filter(
        student=student, day_number=day_number, subject=subject, status='PENDING'
    ).first()
    if existing_pending:
        messages.info(request, f'Day {day_number} {subject} retake is already pending approval.')
        return redirect('portal-upload-center')

    # ══════════════════════════════════════════════════════════════════
    # RETAKE POLICY ENFORCEMENT
    # Block retake request if student hasn't completed Memorization
    # for all SDM questions of this (day, subject), unless exempted.
    # ══════════════════════════════════════════════════════════════════
    from exams.models import RetakePolicy, RetakeExemption
    from exams.models_flow import FlowRun

    policy = RetakePolicy.objects.filter(is_active=True).first()
    if policy and policy.require_memorization:
        # Check for exemption
        from django.utils import timezone as _tz
        exemption_qs = RetakeExemption.objects.filter(
            student=student,
        ).filter(
            Q(day_number=day_number) | Q(day_number__isnull=True)
        ).filter(
            Q(subject=subject) | Q(subject='')
        )
        # Filter non-expired
        active_exemption = exemption_qs.filter(
            Q(expires_at__isnull=True) | Q(expires_at__gte=_tz.now())
        ).exists()

        if not active_exemption:
            # Get all SDM questions for this (student, day, subject)
            sdm_questions = StudentDayMission.objects.filter(
                student=student,
                day_number=day_number,
                subject=subject,
            ).values_list('question_id', flat=True)

            # Check which have completed memorization flows
            incomplete = []
            for qid in sdm_questions:
                # Flow topic = kc_code OR "Q{qid}"
                from exams.models import ModelQuestion
                mq = ModelQuestion.objects.filter(pk=qid).only('kc_code').first()
                if not mq:
                    continue
                topic = (mq.kc_code or '').strip() or f"Q{qid}"
                flow_completed = FlowRun.objects.filter(
                    student=student,
                    flow__topic=topic,
                    status='COMPLETED',
                ).exists()
                if not flow_completed:
                    incomplete.append(qid)

            if incomplete:
                from django.urls import reverse as _rev_retake
                from django.utils.html import format_html as _fmt_retake, escape as _esc_retake
                # Direct link to the FIRST missing question's memorization flow
                _first_missing_qid = incomplete[0]
                _memorize_url = _rev_retake('portal-memorize', args=[_first_missing_qid])
                _safe_policy = _esc_retake(policy.policy_message or '')
                _html_msg = _fmt_retake(
                    '🚫 <strong>Retake Blocked</strong>: Aap ko <strong>{}</strong> question(s) ki '
                    'Memorization complete karni hogi pehle.<br>'
                    '<span class="text-muted text-sm"><em>{}</em></span><br>'
                    '<a href="{}" class="btn btn-sm btn-primary mt-2">📖 Memorization Start Karein (Q{})</a>',
                    len(incomplete), _safe_policy, _memorize_url, _first_missing_qid
                )
                messages.error(request, _html_msg, extra_tags='html-safe')
                return redirect(f"/api/portal/upload-center/?day={day_number}")

    # ══════════════════════════════════════════════════════════════════
    # CHARGE -10 POINTS BEFORE CREATING REQUEST
    from exams.services.points_ledger import penalize, get_balance
    RETAKE_COST = 10
    penalize(student, RETAKE_COST, f"Retake request: Day {day_number} {subject}", code="RETAKE_REQUEST")
    new_balance = get_balance(student)

    # Create the request
    RetakeRequest.objects.create(
        student=student,
        day_number=day_number,
        subject=subject,
        attempts_requested=1,
        status='PENDING',
    )
    messages.success(
        request,
        f'✅ Retake requested for Day {day_number} {subject} (-{RETAKE_COST} pts, balance: {new_balance}). Wait for teacher approval.'
    )
    return redirect('portal-upload-center')



# ============================================================
# EXPERT PANEL — Memorization Flow (copy-paste AI, no API key)
# ============================================================
@login_required(login_url="portal-login")
def portal_memorize(request, qid):
    """Entry point. If flow for this topic exists → redirect to player.
    Else → show the expert-panel-generated prompt for copy-paste."""
    from exams.models import ModelQuestion
    from exams.models_flow import FlowDefinition
    from exams.services.experts.orchestrator import get_expert_prompt

    student = _current_student(request.user)
    if not student:
        return redirect('portal-login')

    try:
        q = ModelQuestion.objects.get(pk=qid)
    except ModelQuestion.DoesNotExist:
        messages.error(request, 'Question not found')
        return redirect('portal-progress')

    if not q.model_answer or not q.model_answer.strip() or q.model_answer.strip() == 'NO_ANSWER_PRINTED':
        from exams.models import QuestionEditRequest
        approved = QuestionEditRequest.objects.filter(question=q, status='APPROVED').order_by('-created_at').first()
        if approved:
            q.model_answer = approved.proposed_answer
            q.save()
        else:
            return render(request, 'exams/portal_fix_answer.html', {
        'all_subjects': locals().get('all_subjects', []),'question': q, 'qid': qid})

    subject = getattr(getattr(q, 'paper', None), 'subject', '') or ''
    topic = (q.kc_code or '').strip() or f"Q{q.pk}"

    medium = (request.GET.get('medium') or '').strip().upper()
    if medium not in ('EN', 'UR', 'UD'):
        medium = (student.medium or 'EN').upper()
    if medium not in ('EN', 'UR', 'UD'):
        medium = 'EN'
    tier = student.tier if student.tier in (1, 2, 3) else 1
    pasted_answer = (request.GET.get('pasted_answer') or '').strip()

    existing = (FlowDefinition.objects
                .filter(subject=subject, topic=topic, lesson_type='FLOW', medium=medium)
                .order_by('-created_at').first())
    if existing and existing.nodes.exists():
        return redirect('portal-flow-run', pk=existing.pk)

    prompt = get_expert_prompt(
        q, subject or 'General',
        tier=tier, path='memorize',
        medium=medium, pasted_answer=pasted_answer or None,
    )
    return render(request, 'exams/portal_ai_flow_prompt.html', {
        'all_subjects': locals().get('all_subjects', []),
        'question': q, 'subject': subject,
        'prompt': prompt, 'qid': qid,
        'medium': medium, 'tier': tier,
        'pasted_answer': pasted_answer,
    })


@login_required(login_url="portal-login")
@require_POST
def portal_memorize_submit(request, qid):
    """Receive AI JSON pasted by student, create FlowDefinition, redirect to player."""
    from exams.models import ModelQuestion
    from exams.models_flow import FlowDefinition, FlowNode, FlowEdge

    student = _current_student(request.user)
    if not student:
        return redirect('portal-login')

    try:
        q = ModelQuestion.objects.get(pk=qid)
    except ModelQuestion.DoesNotExist:
        messages.error(request, 'Question not found')
        return redirect('portal-progress')

    json_text = (request.POST.get('flow_json') or '').strip()
    if not json_text:
        messages.error(request, 'Please paste the AI output.')
        return redirect('portal-memorize', qid=qid)

    try:
        data = json.loads(json_text)
        if isinstance(data, dict) and 'flow' in data:
            data = data['flow']
        nodes_spec = data.get('nodes', [])
        edges_spec = data.get('edges', [])
        # STRIP HALLUCINATED: remove AI's extra 'Gated-Read' / 'Ready' stub nodes
        try:
            nodes_spec, edges_spec, _stripped = _strip_hallucinated_nodes(nodes_spec, edges_spec)
            if _stripped > 0:
                import logging
                logging.getLogger(__name__).info(f'STRIP: removed {_stripped} hallucinated nodes')
        except Exception as _strip_err:
            import logging
            logging.getLogger(__name__).warning(f'Strip failed: {_strip_err}')

        # AUTO-HEAL: force correct medium-select options
        try:
            _healed = _heal_selection_nodes(nodes_spec)
            if _healed > 0:
                import logging
                logging.getLogger(__name__).info(f'AUTO-HEAL: {_healed} selection nodes normalized')
        except Exception as _heal_err:
            import logging
            logging.getLogger(__name__).warning(f'Selection heal failed: {_heal_err}')
        
        # AUTO-CONVERT: transform any fill_blank recall nodes into progressive_mcq
        try:
            _ac_count = _auto_convert_to_progressive(nodes_spec, q.model_answer or '')
            if _ac_count > 0:
                import logging
                logging.getLogger(__name__).info(f'AUTO-CONVERT: {_ac_count} nodes -> progressive_mcq')
        except Exception as _ac_err:
            import logging
            logging.getLogger(__name__).warning(f'Auto-convert failed: {_ac_err}')
        if not nodes_spec:
            raise ValueError('No nodes in JSON')

        subject = getattr(getattr(q, 'paper', None), 'subject', '') or ''
        topic = (q.kc_code or '').strip() or f"Q{q.pk}"

        # Double-check reuse (another student may have built it just now)
        existing = (FlowDefinition.objects
                    .filter(subject=subject, topic=topic, lesson_type='FLOW')
                    .first())
        if existing and existing.nodes.exists():
            return redirect('portal-flow-run', pk=existing.pk)

        flow = FlowDefinition.objects.create(
            title=f"Memorize Q{q.pk}",
            subject=subject, topic=topic,
            teacher=request.user,
            lesson_type='FLOW', status='PUBLISHED', is_published=True,
            mastery_threshold=3,
            sharjeel_mode='MEMORIZE',
        )
        id_map = {}
        for idx, n in enumerate(nodes_spec):
            spec_id = n.get('id', idx + 1)
            node_type = str(n.get('type', 'STORY')).upper()
            if node_type not in dict(FlowNode.NODE_TYPE_CHOICES):
                node_type = 'STORY'
            id_map[spec_id] = FlowNode.objects.create(
                flow=flow, node_type=node_type,
                label=str(n.get('label', ''))[:200],
                position_x=150 + (idx % 4) * 280,
                position_y=100 + (idx // 4) * 180,
                config_json=json.dumps(n.get('config', {})),
            )

        for e in edges_spec:
            src = e.get('from') or e.get('source')
            tgt = e.get('to') or e.get('target')
            if src not in id_map or tgt not in id_map:
                continue
            cond = str(e.get('condition', '')).strip()
            cond_json = '{}'
            if cond == 'correct': cond_json = '{"if": "correct"}'
            elif cond == 'wrong': cond_json = '{"if": "wrong"}'
            elif cond == 'timeout': cond_json = '{"if": "timeout"}'
            FlowEdge.objects.create(
                flow=flow, source_node=id_map[src], target_node=id_map[tgt],
                label=cond[:100],
                priority=int(e.get('priority', 1) or 1),
                condition_json=cond_json,
            )

        messages.success(request, f'Flow ready! {flow.nodes.count()} steps.')
        return redirect('portal-flow-run', pk=flow.pk)
    except Exception as ex:
        messages.error(request, f'Could not parse JSON: {ex}. Try again.')
        return redirect('portal-memorize', qid=qid)


@login_required(login_url="portal-login")
@require_POST
def portal_submit_edit(request, qid):
    from exams.models import ModelQuestion, QuestionEditRequest
    student = _current_student(request.user)
    q = get_object_or_404(ModelQuestion, pk=qid)
    ans = request.POST.get('proposed_answer', '').strip()
    if ans:
        QuestionEditRequest.objects.create(student=student, question=q, proposed_answer=ans)
        messages.success(request, 'Answer submitted! Aap ka teacher ise approve karega, phir flow start ho jayega.')
    return redirect('portal-progress')


@login_required(login_url="portal-login")
@user_passes_test(lambda u: True, login_url="portal-login") # Allow students
@require_POST



def _generate_distractors(correct_phrase, model_answer):
    """Generate 9 plausible wrong answers from the model answer."""
    import random
    correct_lower = correct_phrase.lower().strip()
    distractors = []
    seen = {correct_lower}

    # 1. Similar-length words/phrases from model answer
    words = [w.strip('.,;()[]') for w in model_answer.split() if len(w) > 3]
    candidates = []
    for w in words:
        if w.lower() not in seen:
            candidates.append(w)
            seen.add(w.lower())

    random.shuffle(candidates)
    for c in candidates[:6]:
        if len(distractors) >= 9:
            break
        distractors.append(c)

    # 2. Generic plausible variations
    generic = [
        correct_phrase + 's',
        'not ' + correct_phrase,
        'other ' + correct_phrase,
        'similar ' + correct_phrase,
        correct_phrase + ' (wrong)',
        correct_phrase + ' type',
    ]
    for g in generic:
        if len(distractors) >= 9:
            break
        if g.lower() not in seen:
            distractors.append(g)
            seen.add(g.lower())

    # 3. Pad with generic filler if still short
    while len(distractors) < 9:
        distractors.append('option ' + str(len(distractors) + 1))

    return distractors[:9]






def _strip_hallucinated_nodes(nodes_spec, edges_spec):
    """Remove AI-hallucinated 'Gated-Read' / 'Ready' nodes and rewire edges."""
    if not nodes_spec:
        return nodes_spec, edges_spec, 0

    # Identify hallucinated nodes: label contains 'gated' or 'ready' AND question_en contains 'READY'
    hallucinated_ids = set()
    for n in nodes_spec:
        label = str(n.get('label', '')).lower()
        cfg = n.get('config', {})
        q_en = str(cfg.get('question_en', '')).lower()
        is_stub = (
            ('gated' in label or 'ready' in label) 
            and ('ready' in q_en or 'read it' in q_en or 'parh' in q_en)
        )
        if is_stub:
            hallucinated_ids.add(n.get('id'))

    if not hallucinated_ids:
        return nodes_spec, edges_spec, 0

    # Keep only valid nodes
    new_nodes = [n for n in nodes_spec if n.get('id') not in hallucinated_ids]

    # Rewire edges: any edge pointing TO a hallucinated node goes to that node's first outgoing target instead
    # Build map: hallucinated_id -> its first outgoing target
    redirect_map = {}
    for e in edges_spec:
        src_id = e.get('from') or e.get('source')
        tgt_id = e.get('to') or e.get('target')
        if src_id in hallucinated_ids and tgt_id not in hallucinated_ids:
            if src_id not in redirect_map:
                redirect_map[src_id] = tgt_id

    # Rewrite edges
    new_edges = []
    seen_edges = set()
    for e in edges_spec:
        src_id = e.get('from') or e.get('source')
        tgt_id = e.get('to') or e.get('target')
        
        # Skip edges FROM hallucinated (they'll be gone) unless we need to preserve outgoing
        if src_id in hallucinated_ids:
            continue
        
        # Redirect edges TO hallucinated → TO the hallucinated's target
        if tgt_id in hallucinated_ids:
            real_target = redirect_map.get(tgt_id)
            if real_target is not None:
                tgt_id = real_target
            else:
                continue
        
        key = (src_id, tgt_id, e.get('condition', ''))
        if key in seen_edges:
            continue
        seen_edges.add(key)
        
        new_e = dict(e)
        if 'from' in new_e:
            new_e['from'] = src_id
        if 'to' in new_e:
            new_e['to'] = tgt_id
        if 'source' in new_e:
            new_e['source'] = src_id
        if 'target' in new_e:
            new_e['target'] = tgt_id
        new_edges.append(new_e)

    # Update START edge to point to first real node
    for e in new_edges:
        src_id = e.get('from') or e.get('source')
        if src_id == 1:  # START
            # point to first non-START, non-END node
            for n in new_nodes:
                if n.get('type') not in ('START', 'END'):
                    if 'to' in e: e['to'] = n.get('id')
                    if 'target' in e: e['target'] = n.get('id')
                    break
            break

    return new_nodes, new_edges, len(hallucinated_ids)

def _heal_selection_nodes(nodes_spec):
    """Force any is_selection node to have the correct bilingual medium options."""
    healed = 0
    for node in nodes_spec:
        cfg = node.get('config', {})
        if cfg.get('is_selection'):
            cfg['type'] = 'mcq'
            cfg['text'] = "[EN]Choose your medium:[/EN][UR]Apna medium chunein:[/UR]"
            cfg['options'] = ['English Medium', 'Roman Urdu Medium']
            cfg['correct_answer'] = 'English Medium'
            cfg['hint'] = "[EN]Pick one[/EN][UR]Ek chunein[/UR]"
            node['config'] = cfg
            healed += 1
    return healed

def _auto_convert_to_progressive(nodes_spec, model_answer):
    """DISABLED: 7-turn micro flow uses fill_blank directly (cued recall is research-backed)."""
    return 0


def portal_ai_flow_submit(request, qid):
    from exams.models import ModelQuestion
    from exams.models_flow import FlowDefinition, FlowNode, FlowEdge
    import json

    student = _current_student(request.user)
    if not student:
        return redirect('portal-login')

    try:
        q = ModelQuestion.objects.get(pk=qid)
    except ModelQuestion.DoesNotExist:
        messages.error(request, 'Question not found')
        return redirect('portal-progress')

    json_text = (request.POST.get('flow_json') or '').strip()
    if not json_text:
        messages.error(request, 'Please paste the AI output.')
        return redirect('portal-memorize', qid=qid)

    try:
        data = json.loads(json_text)
        if isinstance(data, dict) and 'flow' in data:
            data = data['flow']
        nodes_spec = data.get('nodes', [])
        edges_spec = data.get('edges', [])
        # STRIP HALLUCINATED: remove AI's extra 'Gated-Read' / 'Ready' stub nodes
        try:
            nodes_spec, edges_spec, _stripped = _strip_hallucinated_nodes(nodes_spec, edges_spec)
            if _stripped > 0:
                import logging
                logging.getLogger(__name__).info(f'STRIP: removed {_stripped} hallucinated nodes')
        except Exception as _strip_err:
            import logging
            logging.getLogger(__name__).warning(f'Strip failed: {_strip_err}')

        # AUTO-HEAL: force correct medium-select options
        try:
            _healed = _heal_selection_nodes(nodes_spec)
            if _healed > 0:
                import logging
                logging.getLogger(__name__).info(f'AUTO-HEAL: {_healed} selection nodes normalized')
        except Exception as _heal_err:
            import logging
            logging.getLogger(__name__).warning(f'Selection heal failed: {_heal_err}')
        
        # AUTO-CONVERT: transform any fill_blank recall nodes into progressive_mcq
        try:
            _ac_count = _auto_convert_to_progressive(nodes_spec, q.model_answer or '')
            if _ac_count > 0:
                import logging
                logging.getLogger(__name__).info(f'AUTO-CONVERT: {_ac_count} nodes -> progressive_mcq')
        except Exception as _ac_err:
            import logging
            logging.getLogger(__name__).warning(f'Auto-convert failed: {_ac_err}')
        if not nodes_spec:
            raise ValueError('No nodes in JSON')

        subject = getattr(getattr(q, 'paper', None), 'subject', '') or ''
        topic = (q.kc_code or '').strip() or f"Q{q.pk}"

        medium = (request.POST.get('medium') or '').strip().upper()
        if medium not in ('EN', 'UR', 'UD'):
            medium = (student.medium or 'EN').upper()
        if medium not in ('EN', 'UR', 'UD'):
            medium = 'EN'

        existing = (FlowDefinition.objects
                    .filter(subject=subject, topic=topic, lesson_type='FLOW', medium=medium)
                    .first())
        if existing and existing.nodes.exists():
            return redirect('portal-flow-run', pk=existing.pk)

        _flow_path = request.POST.get('path', 'memorize')
        _flow_title = f"Understand Q!{q.pk}" if _flow_path == 'understand' else f"Memorize Q!{q.pk}"
        flow = FlowDefinition.objects.create(
            title=_flow_title,
            subject=subject, topic=topic,
            teacher=request.user,
            lesson_type='FLOW', status='PUBLISHED', is_published=True,
            mastery_threshold=3,
            medium=medium,
            sharjeel_mode='UNDERSTAND' if _flow_path == 'understand' else 'MEMORIZE',
        )

        id_map = {}
        for idx, n in enumerate(nodes_spec):
            spec_id = n.get('id', idx + 1)
            node_type = str(n.get('type', 'STORY')).upper()
            if node_type not in dict(FlowNode.NODE_TYPE_CHOICES):
                node_type = 'STORY'
            id_map[spec_id] = FlowNode.objects.create(
                flow=flow, node_type=node_type,
                label=str(n.get('label', ''))[:200],
                position_x=150 + (idx % 4) * 280,
                position_y=100 + (idx // 4) * 180,
                config_json=json.dumps(n.get('config', {})),
            )

        for e in edges_spec:
            src = e.get('from') or e.get('source')
            tgt = e.get('to') or e.get('target')
            if src not in id_map or tgt not in id_map:
                continue
            cond = str(e.get('condition', '')).strip()
            cond_json = '{}'
            if cond == 'correct': cond_json = '{"if": "correct"}'
            elif cond == 'wrong': cond_json = '{"if": "wrong"}'
            elif cond == 'timeout': cond_json = '{"if": "timeout"}'
            FlowEdge.objects.create(
                flow=flow, source_node=id_map[src], target_node=id_map[tgt],
                label=cond[:100],
                priority=int(e.get('priority', 1) or 1),
                condition_json=cond_json,
            )

        messages.success(request, f'Flow created successfully!')
        return redirect('portal-flow-run', pk=flow.pk)

    except Exception as ex:
        messages.error(request, f'Could not parse JSON: {ex}. Try again.')
        return redirect('portal-memorize', qid=qid)



_URDU_EXTENSION = (
    "\n\n=== URDU-SCRIPT EXTENSION (MANDATORY) ===\n"
    "The question/answer above contains Urdu script (اردو). "
    "In addition to the standard `_en` and `_ur` fields, EVERY node's config "
    "object MUST include:\n"
    "  - `question_urdu` — question in proper Urdu script (اردو), not Roman\n"
    "  - `answer_urdu`   — answer in proper Urdu script (اردو), not Roman\n"
    "  - `hint_urdu`     — hint in proper Urdu script (اردو), if hint exists\n"
    "Keep `_en` and `_ur` unchanged. `_urdu` fields are additive only.\n"
)

def _needs_urdu_script(q_text, a_text):
    from exams.parsing import has_arabic_script
    return has_arabic_script(q_text) or has_arabic_script(a_text)


@login_required(login_url="portal-login")
def portal_memorize_custom(request):
    """Custom-flow entry point. Student supplies own question + answer;
    we build an in-memory ModelQuestion (never saved) and reuse the
    same expert-prompt pipeline as normal memorize."""
    from exams.models import ModelQuestion
    from exams.services.experts.orchestrator import get_expert_prompt

    student = _current_student(request.user)
    if not student:
        if not (request.user.is_staff or request.user.is_superuser):
            return redirect('portal-login')
        # Teacher preview mode: use stub student
        student = _TeacherPreviewStudent(request.user.id)

    # Mode: memorize (default) or understand
    mode = (request.GET.get('mode') or request.POST.get('mode') or 'memorize').strip().lower()
    if mode not in ('memorize', 'understand'):
        mode = 'memorize'

    if request.method == 'POST':
        q_text = (request.POST.get('question_text') or '').strip()
        a_text = (request.POST.get('model_answer') or '').strip()
        subject = (request.POST.get('subject') or '').strip() or 'General'
        medium = (request.POST.get('medium') or 'EN').strip().upper()
        if medium not in ('EN', 'UR', 'UD'):
            medium = 'EN'

        if not q_text or not a_text:
            messages.error(request, 'Sawal aur Model Answer dono zaroori hain.')
            return render(request, 'exams/portal_ai_flow_custom.html', {
        'all_subjects': locals().get('all_subjects', []),
                'question_text': q_text, 'model_answer': a_text,
                'subject': subject, 'medium': medium, 'mode': mode,
            })

        # In-memory dummy question — never .save()
        dummy_q = ModelQuestion(question_text=q_text, model_answer=a_text)
        dummy_q.pk = 0

        tier = student.tier if student.tier in (1, 2, 3) else 1

        try:
            prompt = get_expert_prompt(
                dummy_q, subject, tier=tier, path=mode,
                medium=medium, pasted_answer=None,
            )
            if _needs_urdu_script(q_text, a_text):
                prompt += _URDU_EXTENSION
        except Exception as ex:
            messages.error(request, f'Prompt generation failed: {ex}')
            return render(request, 'exams/portal_ai_flow_custom.html', {
        'all_subjects': locals().get('all_subjects', []),
                'question_text': q_text, 'model_answer': a_text,
                'subject': subject, 'medium': medium, 'mode': mode,
            })

        return render(request, 'exams/portal_ai_flow_prompt.html', {
        'all_subjects': locals().get('all_subjects', []),
            'question': dummy_q, 'subject': subject,
            'prompt': prompt, 'qid': 'custom',
            'medium': medium, 'tier': tier,
            'pasted_answer': '',
            'is_custom': True,
            'is_understanding': (mode == 'understand'),
            'mode': mode,
            'custom_question_text': q_text,
            'custom_model_answer': a_text,
        })

    return render(request, 'exams/portal_ai_flow_custom.html', {
        'all_subjects': locals().get('all_subjects', []),
        'question_text': '', 'model_answer': '',
        'subject': '', 'medium': 'EN', 'mode': mode,
    })


@login_required(login_url="portal-login")
@require_POST
def portal_memorize_custom_submit(request):
    """Custom-flow submit. Mirrors portal_ai_flow_submit but reads question
    and answer from POST (student-supplied), not from DB."""
    from exams.models import ModelQuestion
    from exams.models_flow import FlowDefinition, FlowNode, FlowEdge
    from exams.services.experts.orchestrator import get_expert_prompt
    import json as _json
    import uuid as _uuid

    student = _current_student(request.user)
    if not student:
        if not (request.user.is_staff or request.user.is_superuser):
            return redirect('portal-login')
        # Teacher preview mode
        student = _TeacherPreviewStudent(request.user.id)

    q_text = (request.POST.get('question_text') or '').strip()
    a_text = (request.POST.get('model_answer') or '').strip()
    subject = (request.POST.get('subject') or '').strip() or 'General'
    medium = (request.POST.get('medium') or '').strip().upper()
    if medium not in ('EN', 'UR', 'UD'):
        medium = (student.medium or 'EN').upper()
    if medium not in ('EN', 'UR', 'UD'):
        medium = 'EN'
    json_text = (request.POST.get('flow_json') or '').strip()

    if not q_text or not a_text:
        messages.error(request, 'Sawal aur answer dono chahiye.')
        return redirect('portal-memorize-custom')
    if not json_text:
        messages.error(request, 'Please paste the AI output.')
        return redirect('portal-memorize-custom')

    def _rerender_prompt(errmsg):
        messages.error(request, errmsg)
        try:
            dq = ModelQuestion(question_text=q_text, model_answer=a_text)
            dq.pk = 0
            t = student.tier if student.tier in (1, 2, 3) else 1
            p = get_expert_prompt(dq, subject, tier=t, path='memorize',
                                  medium=medium, pasted_answer=None)
            if _needs_urdu_script(q_text, a_text):
                p += _URDU_EXTENSION
        except Exception:
            return redirect('portal-memorize-custom')
        return render(request, 'exams/portal_ai_flow_prompt.html', {
        'all_subjects': locals().get('all_subjects', []),
            'question': dq, 'subject': subject, 'prompt': p, 'qid': 'custom',
            'medium': medium, 'tier': t, 'pasted_answer': '',
            'is_custom': True,
            'custom_question_text': q_text, 'custom_model_answer': a_text,
        })

    try:
        data = _json.loads(json_text)
        if isinstance(data, dict) and 'flow' in data:
            data = data['flow']
        nodes_spec = data.get('nodes', [])
        edges_spec = data.get('edges', [])
        try:
            nodes_spec, edges_spec, _stripped = _strip_hallucinated_nodes(nodes_spec, edges_spec)
        except Exception:
            pass
        try:
            _heal_selection_nodes(nodes_spec)
        except Exception:
            pass
        try:
            _auto_convert_to_progressive(nodes_spec, a_text)
        except Exception:
            pass
        if not nodes_spec:
            raise ValueError('No nodes in JSON')

        topic = f"CUSTOM-{student.id}-{_uuid.uuid4().hex[:8]}"

        flow = FlowDefinition.objects.create(
            title=f"Custom: {q_text[:60]}",
            subject=subject, topic=topic,
            teacher=request.user,
            lesson_type='FLOW', status='PUBLISHED', is_published=True,
            mastery_threshold=3,
            medium=medium,
            sharjeel_mode='CUSTOM',
        )

        id_map = {}
        for idx, n in enumerate(nodes_spec):
            spec_id = n.get('id', idx + 1)
            node_type = str(n.get('type', 'STORY')).upper()
            if node_type not in dict(FlowNode.NODE_TYPE_CHOICES):
                node_type = 'STORY'
            id_map[spec_id] = FlowNode.objects.create(
                flow=flow, node_type=node_type,
                label=str(n.get('label', ''))[:200],
                position_x=150 + (idx % 4) * 280,
                position_y=100 + (idx // 4) * 180,
                config_json=_json.dumps(n.get('config', {})),
            )

        for e in edges_spec:
            src = e.get('from') or e.get('source')
            tgt = e.get('to') or e.get('target')
            if src not in id_map or tgt not in id_map:
                continue
            cond = str(e.get('condition', '')).strip()
            cond_json = '{}'
            if cond == 'correct': cond_json = '{"if": "correct"}'
            elif cond == 'wrong': cond_json = '{"if": "wrong"}'
            elif cond == 'timeout': cond_json = '{"if": "timeout"}'
            FlowEdge.objects.create(
                flow=flow, source_node=id_map[src], target_node=id_map[tgt],
                label=cond[:100],
                priority=int(e.get('priority', 1) or 1),
                condition_json=cond_json,
            )

        messages.success(request, 'Custom flow created successfully!')
        return redirect('portal-flow-run', pk=flow.pk)

    except Exception as ex:
        return _rerender_prompt(f'JSON parse failed: {ex}. Prompt dobara generate ho gaya hai — AI se dubara copy karein.')


@login_required(login_url="portal-login")
def portal_understand(request, qid):
    from exams.models import ModelQuestion
    from exams.models_flow import FlowDefinition
    from exams.services.experts.understanding.u_orchestrator import UnderstandingExpert
    from exams.services.experts.orchestrator import get_expert_prompt

    student = _current_student(request.user)
    if not student:
        return redirect('portal-login')

    try:
        q = ModelQuestion.objects.get(pk=qid)
    except ModelQuestion.DoesNotExist:
        messages.error(request, 'Question not found')
        return redirect('portal-progress')

    if not q.model_answer or not q.model_answer.strip() or q.model_answer.strip() == 'NO_ANSWER_PRINTED':
        from exams.models import QuestionEditRequest
        approved = QuestionEditRequest.objects.filter(question=q, status='APPROVED').order_by('-created_at').first()
        if approved:
            q.model_answer = approved.proposed_answer
            q.save()
        else:
            return render(request, 'exams/portal_fix_answer.html', {
        'all_subjects': locals().get('all_subjects', []),'question': q, 'qid': qid})

    subject = getattr(getattr(q, 'paper', None), 'subject', '') or ''
    topic = (q.kc_code or '').strip() or f"Q!{q.pk}"

    existing = (FlowDefinition.objects
            .filter(subject=subject, topic=topic, lesson_type='FLOW')
            .order_by('-created_at').first())
    if existing and existing.nodes.exists():
        return redirect('portal-flow-run', pk=existing.pk)

    prompt = get_expert_prompt(q, subject or 'General', tier=2, path='understand')
    
    return render(request, 'exams/portal_ai_flow_prompt.html', {
        'all_subjects': locals().get('all_subjects', []),
        'question': q, 'prompt': prompt, 'subject': subject,
        'is_understanding': True
    })


@login_required
def teacher_upload_flow_node_image(request, node_id):
    """Allows teachers to upload an image directly to a FlowNode's config."""
    if not (request.user.is_staff or request.user.is_superuser):
        return JsonResponse({'error': 'Unauthorized'}, status=403)
        
    if request.method == 'POST' and request.FILES.get('image'):
        from exams.models_flow import FlowNode
        from django.core.files.storage import FileSystemStorage
        from django.conf import settings
        import json, os
        
        node = get_object_or_404(FlowNode, id=node_id)
        img = request.FILES['image']
        
        # Save image to media folder
        fs = FileSystemStorage(location=os.path.join(settings.MEDIA_ROOT, 'flow_images'))
        filename = fs.save(f"node_{node_id}_{img.name}", img)
        url = fs.url(f'flow_images/{filename}')
        
        # Update the Node's config_json
        config = json.loads(node.config_json) if node.config_json else {}
        config['image_url'] = url
        
        # If the node has a placeholder, remove it from the label or config
        if '[[IMAGE]]' in node.label:
            node.label = node.label.replace('[[IMAGE]]', '')
            
        node.config_json = json.dumps(config)
        node.save()
        
        return JsonResponse({'ok': True, 'image_url': url})
        
    return JsonResponse({'error': 'Invalid request'}, status=400)

