"""Teacher content views (bulk, paste, cards, codes, pipelines, assignments).

Split from views_teacher.py 2026-11-10.
Re-exported by views_teacher.py for backward compat."""

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

@login_required(login_url="portal-login")
@user_passes_test(_is_teacher, login_url="portal-login")
def portal_teacher_bulk(request):
    """Bulk upload page (Session 6).

    Five-stage workflow: pre-import guidance, file upload, validate,
    repair, ingest. v1 accepts multiple JSON files. Each is validated
    before ingest. Results returned as a per-file summary.

    Standards: Smart Interface Design Patterns (5-stage bulk import);
    OWASP ASVS 5.1.3 (file upload validation); ISO 27001 A.8.10 (no
    retention beyond import); WCAG 2.2 AA (SC 3.3.1 errors, 3.3.7
    redundant entry); Rule 10 (reuses ingest_reports writer); Rule G
    (Roman Urdu).
    """
    message = ""
    error = ""
    results = []

    if request.method == "POST":
        files = request.FILES.getlist("payload_files")
        if not files:
            error = "Koi file upload nahi ki gayi."
        elif len(files) > 30:
            error = "Ek baar mein 30 se zyada files nahi."
        else:
            from django.core.files.storage import default_storage
            import json as _json
            import tempfile, os
            for f in files:
                name = f.name
                if not name.lower().endswith(".json"):
                    results.append({"name": name, "status": "skip",
                                    "detail": "sirf .json files"})
                    continue
                if f.size > 2_000_000:
                    results.append({"name": name, "status": "skip",
                                    "detail": "file 2MB se bari"})
                    continue
                raw = f.read()
                try:
                    payload = _json.loads(raw.decode("utf-8"))
                except Exception as exc:
                    results.append({"name": name, "status": "fail",
                                    "detail": "invalid JSON: " + str(exc)[:80]})
                    continue
                fd, path = tempfile.mkstemp(suffix=".json", prefix="bulk_")
                os.close(fd)
                try:
                    with open(path, "wb") as out:
                        out.write(raw)
                    from io import StringIO
                    out_buf = StringIO(); err_buf = StringIO()
                    try:
                        call_command("ingest_reports", path,
                                     stdout=out_buf, stderr=err_buf)
                        results.append({"name": name, "status": "ok",
                                        "detail": (out_buf.getvalue() or "")
                                                  .strip()[:200]})
                    except Exception as exc:
                        results.append({"name": name, "status": "fail",
                                        "detail": str(exc)[:200]})
                finally:
                    try:
                        os.unlink(path)
                    except OSError:
                        pass
            message = str(len([r for r in results if r["status"] == "ok"])) \
                      + " file(s) OK, " \
                      + str(len([r for r in results if r["status"] == "fail"])) \
                      + " fail, " \
                      + str(len([r for r in results if r["status"] == "skip"])) \
                      + " skip."

    return render(request, "exams/portal_teacher_bulk.html", {
        'all_subjects': locals().get('all_subjects', []),
        "message": message, "error": error, "results": results,
    })


@login_required
@require_teacher_or_delegation
def portal_teacher_paste(request):
    """Task 4 - Teacher paste page for the daily grading loop.

    Step 1: the MASTER_GRADING_PROMPT is shown as-is (Rule 11 - prompt
    is printer output, not chat paraphrase). Student codes are written
    on paper before photographing (guide Section 3 addendum 4, option
    A), so no per-session metadata form is needed. Step 2: paste the
    grading JSON returned by the external model.

    Non-admin surface (staff yes, superuser no). Reuses ingest_reports,
    the single canonical writer (Rule 10). G7 is the admin wizard gate
    over the same command; this page is the daily-loop shortcut.

    Standards: OWASP ASVS 4.3.1 (auth), 4.3.2 (no directory browsing);
    OWASP ASVS 5.1.3 (input validation); NIST SP 800-53 SI-10;
    CWE-78 (avoided - call_command, no shell);
    WCAG 2.2 AA (SC 3.3.1, 3.3.3, 2.4.1); Wiggins & McTighe 2005;
    Hattie & Timperley 2007; Guskey 2020; ISO 9001:2015 7.5.3;
    Rule 8 (Roman Urdu only); Rule 9 (log first, delete second);
    Rule 10 (one canonical path); Rule 11 (prompt is printer output).
    """
    # Per-question single-upload branch
    _qid = request.GET.get('qid') or request.POST.get('qid')
    if _qid:
        try:
            from exams.views_v3 import paste_single_question
            _qid_int = int(_qid)
        except (ImportError, ValueError, TypeError):
            pass
        else:
            return paste_single_question(request, _qid_int)

    # Bulk teacher paste (staff only)
    if not (request.user.is_staff or request.user.is_superuser):
        from django.contrib import messages as _msgs
        _msgs.error(request, 'Teacher access required.')
        return redirect('portal-dashboard')

    tmp_dir = _Path("/home/orkoworo/idealogy/tmp")
    out_dir = _Path("/home/orkoworo/idealogy/output/daily_reports")
    prompt_file = _Path("/home/orkoworo/idealogy/prompts/MASTER_GRADING_PROMPT.md")
    try:
        grading_prompt = prompt_file.read_text(encoding="utf-8")
    except Exception:
        grading_prompt = ""

    error = ""
    message = ""
    output = ""
    pasted = ""
    produced = []

    if request.method == "POST":
        pasted = (request.POST.get("payload") or "").strip()
        make_pdf = (request.POST.get("pdf") == "1")
        test_mode = (request.POST.get("test_mode") or "INDIVIDUAL").strip()
        if test_mode not in ("INDIVIDUAL", "DAILY_QUOTA"):
            test_mode = "INDIVIDUAL"

        if not pasted:
            error = "Paste the grading JSON first."
        else:
            tmp_path = None
            try:
                # Inject test_mode at top of JSON before saving
                import json as _json
                try:
                    parsed = _json.loads(pasted)
                    if isinstance(parsed, dict):
                        # LAW: BORDER CONTROL (Validate AI JSON before ingest)
                        from exams.services.ai_validator import validate_ai_grading_response
                        is_valid, val_error = validate_ai_grading_response(parsed)
                        if not is_valid:
                            raise ValueError(f"AI Validation Failed: {val_error}")

                        parsed.setdefault("test_mode", test_mode)
                        pasted = _json.dumps(parsed, indent=2)
                except Exception as e:
                    if "AI Validation Failed" in str(e):
                        error = str(e)
                        # We raise to skip the rest of the try block and jump to the finally/error handler
                        raise Exception(str(e))
                    pass  # Invalid JSON will fail at ingest anyway

                tmp_dir.mkdir(parents=True, exist_ok=True)
                token = uuid.uuid4().hex[:12]
                tmp_path = tmp_dir / ("teacher_paste_" + token + ".json")
                tmp_path.write_text(pasted, encoding="utf-8")

                before = set()
                if out_dir.exists():
                    before = {f.name for f in out_dir.iterdir() if f.is_file()}

                out_buf = io.StringIO()
                err_buf = io.StringIO()
                ingest_error = None
                try:
                    call_command(
                        "ingest_reports", str(tmp_path), pdf=make_pdf,
                        stdout=out_buf, stderr=err_buf,
                    )
                except Exception as exc:
                    logging.exception("paste_ingest_failed")
                    ingest_error = "Ingest mein masla hua. Server log check karein."

                output = out_buf.getvalue() + err_buf.getvalue()

                if out_dir.exists():
                    after = {f.name for f in out_dir.iterdir() if f.is_file()}
                    for name in sorted(after - before):
                        f = out_dir / name
                        produced.append({"name": name, "size": f.stat().st_size})

                audit = {
                    "ts": datetime.datetime.now(datetime.UTC).isoformat(),
                    "surface": "portal_teacher_paste",
                    "user": request.user.username,
                    "pdf": make_pdf,
                    "bytes": len(pasted),
                    "ingest_ok": ingest_error is None,
                    "ingest_error": ingest_error,
                    "produced": [x["name"] for x in produced],
                }
                audit_path = tmp_dir / (
                    "teacher_paste_"
                    + datetime.datetime.now(datetime.UTC).strftime("%Y%m%dT%H%M%SZ")
                    + "_" + token + ".json"
                )
                audit_path.write_text(json.dumps(audit, indent=2), encoding="utf-8")

                if ingest_error:
                    error = "Ingest failed: " + ingest_error
                else:
                    message = "Ingest successful."
            except Exception as exc:
                logging.exception("paste_failed")
                error = "Paste process karne mein masla hua. Format check karain."
            finally:
                try:
                    if tmp_path is not None and tmp_path.exists():
                        tmp_path.unlink()
                except Exception:
                    pass

    return render(request, "exams/portal_teacher_paste.html", {
        'all_subjects': locals().get('all_subjects', []),
        "error": error,
        "message": message,
        "output": output,
        "pasted": pasted,
        "produced": produced,
        "out_dir": str(out_dir),
        "grading_prompt": grading_prompt,
    })


@login_required(login_url="portal-login")
@user_passes_test(_is_teacher, login_url="portal-login")
def portal_teacher_build_cards(request):
    """Task 5.5 wiring - run build_result_cards --pdf from the dashboard.

    POST month=YYYY-MM (optional code=). Runs the existing command
    (Rule 10 - single canonical writer). Returns a summary line and
    the list of PDFs produced.

    Standards: Guskey, On Your Mark 3rd ed. 2020 (report card is the
    parent communication device); ISO 9241-210 (one screen);
    Section 15.4 (no terminal step for the teacher); OWASP ASVS 4.3.1
    (teacher-gated); OWASP ASVS 5.1.3 (input validation); CWE-78
    (avoided - call_command); ISO 9001:2015 7.5.3 (audit per run);
    WCAG 2.2 AA (SC 3.3.1, 3.3.3); Rule 8 (Roman Urdu);
    Rule 9 (log first, delete second).
    """
    import datetime as _dt
    from pathlib import Path as _P

    tmp_dir = _P("/home/orkoworo/idealogy/tmp")
    out_dir = _P("/home/orkoworo/idealogy/output/result_cards")
    error = ""
    message = ""
    output = ""
    produced = []
    month_val = ""
    code_val = ""

    if request.method == "POST":
        month_val = (request.POST.get("month") or "").strip()
        code_val = (request.POST.get("code") or "").strip()
        # Validate month shape before running the command (cheap, clear msg)
        ok = False
        try:
            y_s, m_s = month_val.split("-")
            y = int(y_s); m = int(m_s)
            ok = 1 <= m <= 12 and 2000 <= y <= 2100
        except (ValueError, AttributeError):
            ok = False
        if not ok:
            error = "Month YYYY-MM format mein likhein (e.g. 2026-10)."
        else:
            try:
                tmp_dir.mkdir(parents=True, exist_ok=True)
                token = uuid.uuid4().hex[:12]
                before = set()
                if out_dir.exists():
                    before = {f.name for f in out_dir.iterdir() if f.is_file()}
                out_buf = io.StringIO(); err_buf = io.StringIO()
                run_error = None
                try:
                    kwargs = {"month": month_val, "pdf": True,
                              "stdout": out_buf, "stderr": err_buf}
                    if code_val:
                        kwargs["code"] = code_val
                    call_command("build_result_cards", **kwargs)
                except Exception as exc:
                    run_error = str(exc)
                output = out_buf.getvalue() + err_buf.getvalue()
                if out_dir.exists():
                    after = {f.name for f in out_dir.iterdir() if f.is_file()}
                    for name in sorted(after - before):
                        f = out_dir / name
                        produced.append({"name": name, "size": f.stat().st_size})
                audit = {
                    "ts": _dt.datetime.now(_dt.UTC).isoformat(),
                    "surface": "portal_teacher_build_cards",
                    "user": request.user.username,
                    "month": month_val, "code": code_val or None,
                    "ok": run_error is None,
                    "produced": [x["name"] for x in produced],
                }
                ap = tmp_dir / ("result_cards_"
                                + _dt.datetime.now(_dt.UTC).strftime("%Y%m%dT%H%M%SZ")
                                + "_" + token + ".json")
                ap.write_text(json.dumps(audit, indent=2), encoding="utf-8")
                if run_error:
                    error = "Build failed: " + run_error
                else:
                    message = ("Report cards bana diye (" + str(len(produced))
                               + " PDF). Folder: " + str(out_dir))
            except Exception as exc:
                error = "Build error: " + str(exc)

    # Session 8: dropdowns for month + student (recognise, do not recall).
    # Month list = every month that has at least one Exam row, plus the
    # current month; newest first. Avoids offering empty months.
    import datetime as _dt2
    from django.db.models.functions import TruncMonth
    _today = _dt2.date.today()
    _seen = set()
    _has_data = (
        Exam.objects
        .annotate(_m=TruncMonth("exam_date"))
        .values_list("_m", flat=True)
        .distinct()
    )
    for _d in _has_data:
        if _d is None:
            continue
        _seen.add(f"{_d.year:04d}-{_d.month:02d}")
    _seen.add(f"{_today.year:04d}-{_today.month:02d}")
    month_options = sorted(_seen, reverse=True)
    student_options = list(
        Student.objects.filter(is_active=True)
        .order_by("code")
        .values("code", "name")
    )
    return render(request, "exams/portal_teacher_build_cards.html", {
        'all_subjects': locals().get('all_subjects', []),
        "error": error, "message": message, "output": output,
        "produced": produced, "out_dir": str(out_dir),
        "month": month_val, "code": code_val,
        "month_options": month_options,
        "student_options": student_options,
    })


@login_required
@user_passes_test(_is_teacher)
def portal_teacher_pipelines(request):
    from exams.models import TaskPipeline, StudentTask, PortalFeatureLog

    if request.method == "POST":
        action = (request.POST.get("action") or "").strip()
        if action == "kc_discovery_approve":
            import json as _json, tempfile as _tf, os as _os
            pid = request.POST.get("pipeline_id") or ""
            pipe = TaskPipeline.objects.filter(id=pid).first()
            if pipe and pipe.current_stage == 4:
                st3 = StudentTask.objects.filter(
                    pipeline=pipe, pipeline_stage=3
                ).order_by("-id").first()
                if st3 and isinstance(st3.json_payload, dict):
                    proposed = st3.json_payload.get("kcs") or []
                    if proposed:
                        prefix = (pipe.paper_code or "").split("-")[0].upper()
                        subj_map = {"MT":"Mathematics","PH":"Physics","CH":"Chemistry",
                                    "BI":"Biology","EN":"English","UR":"Urdu",
                                    "IS":"Islamiyat","CS":"Computer Science",
                                    "TQ":"Tarjumatul Quran"}
                        subject = subj_map.get(prefix, "General")
                        seed = {"subject": subject, "kcs": proposed}
                        tfh = _tf.NamedTemporaryFile("w", suffix=".json",
                                                     delete=False, encoding="utf-8")
                        _json.dump(seed, tfh); tfh.close()
                        try:
                            from django.core.management import call_command
                            call_command("seed_kcs", file=tfh.name)
                            from exams.models import KnowledgeComponent as _KC
                            codes = [k.get("code") for k in proposed if k.get("code")]
                            _KC.objects.filter(code__in=codes).update(teacher_approved=True)
                            st3.status = "DONE"; st3.ingest_status = "OK"
                            st3.save(update_fields=["status","ingest_status"])
                            done = list(pipe.stages_completed or [])
                            for s in (3, 4):
                                if s not in done: done.append(s)
                            pipe.stages_completed = sorted(done)
                            pipe.current_stage = 5
                            pipe.status = "ACTIVE"
                            pipe.save(update_fields=["stages_completed","current_stage","status"])
                            owner = pipe.owner_student
                            if owner and not StudentTask.objects.filter(
                                    pipeline=pipe, pipeline_stage=5).exists():
                                ref = _paper_from_book(pipe.paper_code)
                                StudentTask.objects.create(
                                    student=owner, task_type="KC_TAG",
                                    task_ref=ref, status="ASSIGNED",
                                    pipeline=pipe, pipeline_stage=5,
                                    assigned_by=request.user)
                            PortalFeatureLog.objects.create(
                                key="kc_discovery_approve." + subject,
                                old_enabled=True, new_enabled=True,
                                changed_by=request.user,
                                note="approved " + str(len(codes)) + " KCs for " + subject)
                        finally:
                            try: _os.unlink(tfh.name)
                            except Exception: pass
            return redirect("portal-teacher-pipelines")
        if action == "teacher_advance":
            pid = request.POST.get("pipeline_id") or ""
            stage = request.POST.get("stage") or ""
            try:
                stage = int(stage)
            except ValueError:
                return redirect("portal-teacher-pipelines")
            pipe = TaskPipeline.objects.filter(id=pid).first()
            if pipe and stage in (2, 4, 8, 9):  # stage 2 = ingest bank gate (Rule 10, Rule 27)
                done = list(pipe.stages_completed or [])
                if stage not in done:
                    done.append(stage)
                done = sorted(set(done))
                pipe.stages_completed = done
                # advance to next unfinished student stage
                nxt = None
                for s in range(1, 12):
                    if s not in done:
                        nxt = s
                        break
                if nxt is None:
                    pipe.current_stage = 11
                    pipe.status = "DONE"
                else:
                    pipe.current_stage = nxt
                    # Turn 4 (2026-10-11): canonical status. Rule 10.
                    pipe.status = _compute_pipeline_status(pipe)
                pipe.save()
                # Turn 3e (2026-10-11): delegate to the canonical helper.
                # Rule 10 - one writer for pipeline-stage task creation.
                # Fixes: (1) live-check instead of any-status check;
                # (2) KC ref format for stages 10 and 11.
                _create_pipeline_task_for_stage(pipe, nxt,
                                                 actor=request.user)
            return redirect("portal-teacher-pipelines")

    rows = []
    for p in TaskPipeline.objects.order_by("paper_code"):
        stage_tasks = list(StudentTask.objects.filter(pipeline=p))
        total = len(stage_tasks)
        done = sum(1 for t in stage_tasks if t.status == "DONE")
        blocked_on_teacher = p.status == "BLOCKED_ON_TEACHER"
        awaiting = []
        if blocked_on_teacher and p.current_stage in (2, 4, 8, 9):
            awaiting.append(p.current_stage)
        rows.append({
            "pipe": p,
            "total": total,
            "done": done,
            "blocked_on_teacher": blocked_on_teacher,
            "awaiting_stage": awaiting[0] if awaiting else None,
        })

    return render(request, "exams/portal_teacher_pipelines.html", {
        'all_subjects': locals().get('all_subjects', []),
        "rows": rows,
        "total_pipelines": len(rows),
        "blocked_count": sum(1 for r in rows if r["blocked_on_teacher"]),
        "total_stages": len(PIPELINE_STAGES),
    })


@login_required
@user_passes_test(_is_teacher)
def portal_teacher_assign_glossary(request):
    """Teacher page: assign GLOSSARY + STORY. Rule 10 dispatches to commands."""
    from django.core.management import call_command
    from io import StringIO
    from django.contrib import messages
    from exams.models import Student, KnowledgeComponent
    msg = ""
    if request.method == "POST":
        action = request.POST.get("action", "")
        codes = request.POST.getlist("students")
        if action == "glossary":
            subj = (request.POST.get("subject") or "CH").upper().strip()
            try:
                out = StringIO()
                call_command("assign_glossary_tasks",
                             students=codes, subject=subj, stdout=out)
                msg = out.getvalue()
                messages.success(request, f"Glossary assign done. {len(codes)} students.")
            except Exception as e:
                messages.error(request, f"Glossary assign failed: {e}")
        elif action == "story":
            kc_code = (request.POST.get("kc") or "").strip().upper()
            try:
                out = StringIO()
                call_command("assign_story_tasks",
                             students=codes, kc=kc_code, stdout=out)
                msg = out.getvalue()
                messages.success(request, f"Story assign done. {len(codes)} students.")
            except Exception as e:
                messages.error(request, f"Story assign failed: {e}")
    students = Student.objects.filter(is_active=True).order_by("code")
    kcs = KnowledgeComponent.objects.filter(code__endswith="-GLOSSARY").order_by("code")
    ctx = {"students": students, "kcs": kcs, "output": msg}
    return render(request, "exams/portal_teacher_assign_glossary.html", ctx)


@login_required(login_url="portal-login")
@user_passes_test(_is_teacher, login_url="portal-login")
def portal_teacher_stage_completions(request):
    """Teacher page: review + approve/reject student stage-completion requests."""
    from exams.models import StudentTask, StageCompletionRequest, TaskPipeline
    from django.utils import timezone

    message = None
    if request.method == "POST":
        req_id = request.POST.get("request_id") or ""
        action = request.POST.get("action") or ""
        note = (request.POST.get("teacher_note") or "").strip()
        if not req_id.isdigit():
            return render(request, "exams/portal_teacher_stage_completions.html", {
        'all_subjects': locals().get('all_subjects', []),"message": "Invalid request ID."})
        req = StageCompletionRequest.objects.filter(id=req_id, status="PENDING").first()
        if not req:
            message = "Request not found or already reviewed."
        elif action == "approve":
            retired = (StudentTask.objects
                       .filter(student=req.student,
                               task_type=req.task_type,
                               task_ref__startswith=req.task_ref_prefix)
                       .exclude(status__in=["DONE", "SKIPPED"])
                       .update(status="SKIPPED",
                               unassigned_at=timezone.now(),
                               notes=f"[stage-complete] approved by teacher: {note[:100]}"))
            req.status = "APPROVED"
            req.reviewed_at = timezone.now()
            req.reviewed_by = request.user
            req.teacher_note = note
            req.save(update_fields=["status", "reviewed_at", "reviewed_by", "teacher_note"])
            # Reconcile any pipeline for the affected book
            if req.task_type == "BOOK_INGEST":
                for p in TaskPipeline.objects.filter(paper_code=req.task_ref_prefix):
                    from django.core.management import call_command
                    try:
                        call_command("reconcile_pipelines", code=p.paper_code, apply=True,
                                     stdout=open("/dev/null", "w"))
                    except Exception:
                        pass
            message = f"Approved. {retired} task(s) retired."
        elif action == "reject":
            req.status = "REJECTED"
            req.reviewed_at = timezone.now()
            req.reviewed_by = request.user
            req.teacher_note = note
            req.save(update_fields=["status", "reviewed_at", "reviewed_by", "teacher_note"])
            message = "Rejected."

    pending = StageCompletionRequest.objects.filter(status="PENDING").select_related("student").order_by("-requested_at")
    page_obj = paginate(request, pending)
    pending = page_obj.object_list
    recent = StageCompletionRequest.objects.exclude(status="PENDING").select_related("student").order_by("-reviewed_at")[:20]
    return render(request, "exams/portal_teacher_stage_completions.html", {
        'all_subjects': locals().get('all_subjects', []),
        "pending": pending, 'page_obj': page_obj,
        "recent": recent,
        "message": message,
    })


def portal_teacher_assign_books(request):
    """Teacher-only: assign a subject/book to each student.
    Rule 10: single writer — this view owns Student.assigned_* fields.
    Rule 25: one book per student at a time.
    """
    from django.http import HttpResponseForbidden
    from django.shortcuts import render as _render, redirect as _redir
    from django.contrib import messages as _msg
    from django.utils import timezone as _tz
    from exams.models import Student as _Student, PortalFeatureLog as _PFL

    # teacher check (Rule 24/28; ISO 9241-110 s5.5; WCAG 2.2 SC 3.3.1)
    # Session 23 D-8: consistent with every sibling teacher view --
    # unauthenticated -> 302 to login (was: 403).
    user = request.user
    if not user.is_authenticated:
        from django.shortcuts import redirect as _login_redir
        return _login_redir(
            f"/api/portal/login/?next={request.get_full_path()}"
        )
    is_teacher = user.is_staff or getattr(user, "is_teacher", False)
    if not is_teacher:
        return HttpResponseForbidden("Teacher account required.")

    if request.method == "POST":
        stu_code = (request.POST.get("student_code") or "").strip()
        new_subj = (request.POST.get("assigned_subject") or "").strip()
        new_code = (request.POST.get("assigned_book_code") or "").strip()

        if not stu_code:
            _msg.error(request, "Student code missing.")
            return _redir("teacher-assign-books")

        try:
            s = _Student.objects.get(code=stu_code)
        except _Student.DoesNotExist:
            _msg.error(request, f"Student {stu_code} not found.")
            return _redir("teacher-assign-books")

        # validate subject
        allowed = {k for k, _ in _SUBJECT_CHOICES if k}
        if new_subj and new_subj not in allowed:
            _msg.error(request, f"Unknown subject: {new_subj}")
            return _redir("teacher-assign-books")

        # P-FIX-assignbooks: book_code is DERIVED, not user-submitted.
        # Subject is the canonical writer (Rule 10).
        new_code = _SUBJECT_DEFAULT_BOOK.get(new_subj, "") if new_subj else ""

        old_subj = s.assigned_subject or ""
        old_code = s.assigned_book_code or ""

        s.assigned_subject = new_subj
        s.assigned_book_code = new_code
        s.assigned_at = _tz.now()
        s.assigned_by = user.get_username()
        s.save(update_fields=["assigned_subject","assigned_book_code","assigned_at","assigned_by"])

        try:
            _PFL.objects.create(
                key=f"assign_book.{stu_code}",
                note=f"{old_subj or '-'} / {old_code or '-'} -> {new_subj or '-'} / {new_code or '-'}",
            )
        except Exception:
            pass

        _msg.success(request, f"{stu_code}: subject={new_subj or '-'}  book={new_code or '-'}")
        return _redir("teacher-assign-books")

    # GET
    students = _Student.objects.filter(is_active=True).order_by("code")
    rows = [{
        "code": s.code,
        "name": s.name,
        "subject": s.assigned_subject or "",
        "book_code": s.assigned_book_code or "",
        "assigned_at": s.assigned_at,
        "assigned_by": s.assigned_by or "",
    } for s in students]

    return _render(request, "exams/portal_teacher_assign_books.html", {
        "rows": rows,
        "subject_choices": _SUBJECT_CHOICES,
        "book_defaults": _SUBJECT_DEFAULT_BOOK,
        "total": len(rows),
    })


@login_required
@user_passes_test(_is_teacher, login_url="portal-login")
def portal_teacher_content(request):
    """Safe stub: renders Content Library. Fetches KCs if possible."""
    from exams.models import KnowledgeComponent
    kcs = KnowledgeComponent.objects.all().order_by('code')[:100]
    return render(request, "exams/portal_teacher_content.html", {
        'all_subjects': locals().get('all_subjects', []),"kcs": kcs})


@login_required
@user_passes_test(_is_teacher, login_url="portal-login")
def portal_teacher_add_kc(request):
    """Stub: Add KC form. Renders form, handles POST."""
    from exams.models import KnowledgeComponent
    if request.method == 'POST':
        code = request.POST.get('code', '').strip()
        title = request.POST.get('title', '').strip()
        subject = request.POST.get('subject', '').strip()
        if code and title:
            KnowledgeComponent.objects.get_or_create(
                code=code, defaults={'title': title, 'subject': subject}
            )
            return render(request, "exams/portal_teacher_content.html",
                          {
        'all_subjects': locals().get('all_subjects', []),"kcs": KnowledgeComponent.objects.all()[:100], "message": "KC added"})
    return render(request, "exams/portal_teacher_add_kc.html", {
        'all_subjects': locals().get('all_subjects', []),})


def teacher_get_student_questions(request):
    from django.http import JsonResponse
    from exams.models import Student
    from exams.models_day_mission import StudentDayMission

    student_code = request.GET.get('student_code', '').strip()
    day_str = request.GET.get('day', '').strip()
    if not student_code or not day_str:
        return JsonResponse({'error': 'Missing params'}, status=400)

    try:
        day_num = int(day_str)
    except ValueError:
        return JsonResponse({'error': 'Invalid day'}, status=400)

    student = Student.objects.filter(code=student_code).first()
    if not student:
        return JsonResponse({'error': 'Student not found'}, status=404)

    subject_filter = request.GET.get('subject', '').strip()
    missions = StudentDayMission.objects.filter(
        student=student, day_number=day_num
    ).select_related('question', 'question__paper')
    
    if subject_filter:
        missions = missions.filter(subject__iexact=subject_filter)
        
    missions = missions.order_by('subject', 'position')

    data = []
    for m in missions:
        data.append({
            'position': m.position,
            'subject': m.subject,
            'text': (m.question.question_text[:50] + '...') if m.question and m.question.question_text else 'No text',
        })
    return JsonResponse({'questions': data})


@login_required
def portal_teacher_student_questions(request, student_code):
    """Staff view: student questions grouped by book for a specific day."""
    from django.core.exceptions import PermissionDenied
    if not (request.user.is_staff or request.user.is_superuser):
        raise PermissionDenied
    
    from exams.models import Student, AttemptLog, EngineState
    from exams.models_day_mission import StudentDayMission

    # === PHASE 4: per-question approve/reject with class-wide broadcast ===
    # Fix A+B+C+F applied
    if request.method == 'POST' and 'question_id' in request.POST:
        import logging as _logging
        from django.contrib import messages as _msgs
        from django.db import transaction as _txn
        from django.db.models import Max as _Max
        from django.utils import timezone as _tz
        from django.shortcuts import redirect as _redirect
        from django.urls import reverse as _reverse
        from exams.models import ModelQuestion as _MQ, Student as _Stu, ModelPaper as _MP
        from exams.models_day_mission import QuestionAssignment as _QA

        _log = _logging.getLogger(__name__)
        _q_id = request.POST.get('question_id')
        _action = request.POST.get('action')
        _day = request.POST.get('day') or request.GET.get('day') or ''

        try:
            _student = _Stu.objects.get(code=student_code, is_active=True)
            _q = _MQ.objects.select_related('paper').get(id=_q_id)
            with _txn.atomic():
                if _action == 'approve':
                    _q.needs_teacher_review = False
                    _q.review_status = 'approved'
                    _q.teacher_reviewed_at = _tz.now()
                    _q.teacher_reviewed_by = request.user
                    _q.save()
                    _today = _tz.localdate()
                    _paper = _q.paper
                    # Fix A: paper.student_class is authoritative; fall back to student's class.
                    _cls = ((_paper.student_class if _paper else '') or _student.student_class or '').strip()
                    _subj = ((_paper.subject if _paper else '') or '').strip()
                    if _cls and _subj and _paper:
                        # Fix B: serialize concurrent approvals on the same paper row.
                        _MP.objects.select_for_update().filter(id=_paper.id).first()
                        _existing = _QA.objects.filter(
                            date=_today, target_student__isnull=True,
                            target_class=_cls, subject=_subj, question=_q,
                        ).first()
                        if _existing:
                            _msgs.info(request, f"Q#{_q.id} already broadcast for class {_cls}.")
                        else:
                            _max = _QA.objects.filter(
                                date=_today, target_student__isnull=True,
                                target_class=_cls, subject=_subj,
                            ).aggregate(_Max('position'))['position__max'] or 0
                            _QA.objects.create(
                                date=_today, target_student=None,
                                target_class=_cls, target_shift='',
                                subject=_subj, position=_max + 1,
                                question=_q, assigned_by=request.user,
                                notes=f"Approved from {_student.code} page - class-wide.",
                            )
                            _msgs.success(request, f"Q#{_q.id} approved and broadcast to class {_cls}.")
                    else:
                        _msgs.warning(request, f"Q#{_q.id} approved; paper or class/subject missing, no broadcast.")
                elif _action == 'reject':
                    _q.needs_teacher_review = False
                    _q.review_status = 'rejected'
                    _q.teacher_reviewed_at = _tz.now()
                    _q.teacher_reviewed_by = request.user
                    _q.save()
                    _msgs.warning(request, f"Q#{_q.id} rejected.")
        except _MQ.DoesNotExist:
            _msgs.error(request, "Question not found.")
            _log.warning("Phase4: ModelQuestion id=%s not found (student=%s)", _q_id, student_code)
        except _Stu.DoesNotExist:
            _msgs.error(request, "Student not found.")
            _log.warning("Phase4: Student code=%s not found", student_code)
        except Exception as _e:
            _msgs.error(request, f"Action failed: {_e}")
            _log.exception("Phase4 failed student=%s q=%s action=%s", student_code, _q_id, _action)
        # Fix F: use reverse() so redirect works behind the /api/ prefix.
        try:
            _target = _reverse('portal-teacher-student-questions', kwargs={'student_code': student_code}) + f"?day={_day}"
        except Exception:
            _target = f"/api/portal/teacher/student-questions/{student_code}/?day={_day}"
        return _redirect(_target)
    # === end Phase 4 ===

    
    student = get_object_or_404(Student, code=student_code, is_active=True)
    
    # Get current day from engine
    engine = EngineState.objects.first()
    current_day = engine.get_current_day() if (engine and engine.has_started) else 1
    
    # Get selected day (default to today/current day)
    selected_day_str = request.GET.get('day')
    try:
        selected_day = int(selected_day_str) if selected_day_str else current_day
    except ValueError:
        selected_day = current_day
        
    # Fetch missions for that day
    missions = StudentDayMission.objects.filter(
        student=student, 
        day_number=selected_day
    ).select_related('question', 'question__paper').order_by('subject', 'question__question_index')
    
    # Group by subject
    grouped_questions = {}
    _pace = student.daily_question_count or 1
    _seen_ids = set()
    for m in missions:
        subj = m.question.paper.subject if m.question.paper else 'Unknown'
        if subj not in grouped_questions:
            grouped_questions[subj] = []
        if m.question.id in _seen_ids:
            continue
        if len(grouped_questions[subj]) >= _pace:
            continue
        _seen_ids.add(m.question.id)
        grouped_questions[subj].append(m)
        
    # Recent attempts (keep existing logic)
    recent_attempts = AttemptLog.objects.filter(student=student).select_related('question').order_by('-created_at')[:20]
    
    # Day options for dropdown (Day 1 to Current Day)
    day_options = list(range(1, current_day + 1))
    
    return render(request, 'exams/portal_teacher_student_questions.html', {
        'all_subjects': locals().get('all_subjects', []),
        'student': student,
        'grouped_questions': grouped_questions,
        'selected_day': selected_day,
        'current_day': current_day,
        'day_options': day_options,
        'recent_attempts': recent_attempts,
    })


def portal_teacher_daily_codes(request):
    selected_class = request.POST.get('class') or request.GET.get('class', '9')
    """Teacher console — manage daily test codes for ANY day (1-120).

    Industry standard:
      - Date navigation via day number OR ISO date
      - Bulk generation for single day or range
      - Code-existence tracking (compulsory for uploads)
      - Publication audit trail (ISO 27001 A.8.15)
      - No-edit-after-submission guardrail
    """
    from django.shortcuts import render, redirect
    from django.utils import timezone
    from django.contrib import messages
    from exams.models import Student, StudentDailyCode, AttemptLog, EngineState
    from exams.models_day_mission import DailyCodeVisibility, DayAttemptPolicy
    from exams.services.daily_code import edit_code
    from datetime import datetime as _dt, timedelta as _td
    import random

    if not request.user.is_authenticated:
        from django.contrib.auth.views import redirect_to_login
        return redirect_to_login(request.get_full_path())
    if not (request.user.is_staff or request.user.is_superuser):
        from django.core.exceptions import PermissionDenied
        raise PermissionDenied

    # ── AJAX question search endpoint ──
    if request.method == 'GET' and request.GET.get('action') == 'search_questions':
        from django.http import JsonResponse
        from exams.models import ModelQuestion
        q_str = (request.GET.get('q') or '').strip()
        subj_str = (request.GET.get('subject') or '').strip()
        qs = ModelQuestion.objects.filter(superseded_at__isnull=True).exclude(question_text='').exclude(question_text__startswith='[]')
        if subj_str:
            qs = qs.filter(paper__subject__iexact=subj_str)
        if q_str:
            qs = qs.filter(question_text__icontains=q_str)
        # Dynamic limit: 100 when browsing (no query), 30 when searching
        _limit = 30 if q_str else 500
        qs = qs.select_related('paper').order_by(
            'paper__subject', 'question_index'
        )[:_limit]
        results = []
        for q in qs:
            results.append({
                'id': q.id,
                'text': (q.question_text or '')[:120],
                'subject': q.paper.subject if q.paper else '',
                'marks': float(q.marks) if q.marks else 0,
                'paper': q.paper.code if q.paper else '',
            })
        return JsonResponse({'results': results})

    if request.method == 'GET' and request.GET.get('action') == 'preview_assignment':
        from django.http import JsonResponse
        from exams.models import Student
        scope_type = (request.GET.get('scope_type') or 'STUDENT').strip().upper()
        s_code = (request.GET.get('student_code') or '').strip()
        t_class = (request.GET.get('target_class') or '').strip()
        t_shift = (request.GET.get('target_shift') or '').strip().lower()

        students = Student.objects.filter(is_active=True)
        if scope_type == 'STUDENT':
            if s_code:
                students = students.filter(code=s_code)
            else:
                students = students.none()
        elif scope_type == 'CLASS':
            if t_class:
                students = students.filter(student_class=t_class)
            else:
                students = students.none()
        elif scope_type == 'CLASS_SHIFT':
            if t_class and t_shift in ('morning', 'evening'):
                students = students.filter(student_class=t_class, shift=t_shift)
            else:
                students = students.none()
        elif scope_type == 'SHIFT':
            if t_shift in ('morning', 'evening'):
                students = students.filter(shift=t_shift)
            else:
                students = students.none()
        return JsonResponse({'count': students.count()})

    engine = EngineState.objects.filter(id=1).first()
    if not engine or not engine.start_date:
        messages.error(request, 'Engine not initialized.')
        return redirect('portal-dashboard')

    current_day = engine.get_current_day()
    max_day = 120

    # ─── DATE SELECTION ───
    selected_day = None
    _day = request.GET.get('day') or request.POST.get('day')
    _date = request.GET.get('date') or request.POST.get('date')
    if _day:
        try:
            _d = int(_day)
            if 1 <= _d <= max_day:
                selected_day = _d
        except (ValueError, TypeError):
            pass
    if selected_day is None and _date:
        try:
            _parsed = _dt.strptime(_date, '%Y-%m-%d').date()
            _delta = (_parsed - engine.start_date).days
            if 0 <= _delta < max_day:
                selected_day = _delta + 1
        except (ValueError, TypeError):
            pass
    if selected_day is None:
        selected_day = current_day

    selected_date = engine.start_date + _td(days=selected_day - 1)
    _back = f'/api/portal/teacher/daily-codes/?day={selected_day}&class={selected_class}'

    if selected_day == current_day:
        day_label = 'Today'
    elif selected_day == current_day - 1:
        day_label = 'Yesterday'
    elif selected_day == current_day + 1:
        day_label = 'Tomorrow'
    elif selected_day < current_day:
        day_label = f'Day {selected_day} (past)'
    else:
        day_label = f'Day {selected_day} (future)'

    visibility, _ = DailyCodeVisibility.objects.get_or_create(
        date=selected_date, target_student__isnull=True,
        target_class='', target_shift='',
        defaults={'is_visible': False})
    day_policy, _ = DayAttemptPolicy.objects.get_or_create(
        date=selected_date, target_student__isnull=True,
        target_class='', target_shift='',
        defaults={'status': 'LOCKED'})

    # ─── POST ACTIONS ───
    if request.method == 'POST':
        action = request.POST.get('action', '')

        if action in ('publish_scoped', 'hide_scoped'):
            scope_type = request.POST.get('scope_type', 'CLASS').strip().upper()
            target_class = request.POST.get('scope_class', '').strip()
            target_student_code = request.POST.get('scope_student', '').strip()
            target_shift = request.POST.get('scope_shift', '').strip().lower()
            toggle_shift = request.POST.get('toggle_shift', 'both').strip().lower()
            make_visible = (action == 'publish_scoped')

            target_student = None
            if scope_type == 'STUDENT':
                target_student = Student.objects.filter(code=target_student_code).first()
                if not target_student:
                    messages.error(request, f'Student {target_student_code} not found.')
                    return redirect(_back)
                target_class = ''
                target_shift = ''
            elif scope_type == 'CLASS':
                if not target_class:
                    messages.error(request, 'Class required for CLASS scope.')
                    return redirect(_back)
                target_shift = ''
            elif scope_type == 'CLASS_SHIFT':
                if not target_class or target_shift not in ('morning', 'evening'):
                    messages.error(request, 'Class and valid shift required for CLASS_SHIFT scope.')
                    return redirect(_back)
            elif scope_type == 'SHIFT':
                if target_shift not in ('morning', 'evening'):
                    messages.error(request, 'Valid shift required for SHIFT scope.')
                    return redirect(_back)
                target_class = ''
            elif scope_type == 'ALL':
                target_class = ''
                target_shift = ''
                target_student = None

            vis, _ = DailyCodeVisibility.objects.get_or_create(
                date=selected_date,
                target_student=target_student,
                target_class=target_class,
                target_shift=target_shift,
                defaults={'is_visible': False}
            )
            
            if toggle_shift in ('morning', 'both'):
                vis.morning_visible = make_visible
            if toggle_shift in ('evening', 'both'):
                vis.evening_visible = make_visible

            if vis.morning_visible or vis.evening_visible:
                vis.is_visible = True
            else:
                vis.is_visible = False
                
            if make_visible:
                vis.published_at = timezone.now()
                vis.published_by = request.user
                vis.hidden_at = None
                vis.hidden_by = None
            else:
                vis.hidden_at = timezone.now()
                vis.hidden_by = request.user
                
            vis.save()
            
            if not make_visible and not vis.morning_visible and not vis.evening_visible:
                vis.delete()
                messages.success(request, f'🗑️ Scoped visibility removed for {scope_type}.')
            else:
                status_msg = 'published' if make_visible else 'hidden'
                messages.success(request, f'✅ Scoped visibility {status_msg} for {scope_type}.')
            return redirect(_back)

        # Publish / Hide (Split by Shift)
        if action in ('publish_morning', 'hide_morning', 'publish_evening', 'hide_evening'):
            shift = 'morning' if 'morning' in action else 'evening'
            is_pub = 'publish' in action
            setattr(visibility, f'{shift}_visible', is_pub)
            visibility.is_visible = visibility.morning_visible or visibility.evening_visible
            if is_pub:
                visibility.published_at = timezone.now()
                visibility.published_by = request.user
                visibility.hidden_at = None
                visibility.hidden_by = None
                messages.success(request, f'✅ {shift.title()} codes PUBLISHED for Day {selected_day}')
            else:
                visibility.hidden_at = timezone.now()
                visibility.hidden_by = request.user
                messages.warning(request, f'🔒 {shift.title()} codes HIDDEN for Day {selected_day}')
            visibility.save()
            return redirect(_back)

        # Day policy
        # ── RETAKE REQUEST: Approve ──
        if action == 'approve_retake_request':
            from exams.models import RetakeRequest
            try:
                req_id = int(request.POST.get('request_id', 0))
                attempts = int(request.POST.get('attempts_granted', 1))
            except (ValueError, TypeError):
                messages.error(request, 'Invalid request.')
                return redirect(_back)

            req = RetakeRequest.objects.filter(id=req_id, status='PENDING').first()
            if not req:
                messages.error(request, 'Request not found or already processed.')
                return redirect(_back)

            req.status = 'APPROVED'
            req.attempts_granted = max(1, min(10, attempts))
            
            new_code_str = request.POST.get('new_code', '').strip()
            if new_code_str.isdigit():
                req.override_code = int(new_code_str)
                from exams.models import EngineState
                from datetime import timedelta
                eng = EngineState.objects.first()
                if eng and eng.start_date:
                    target_date = eng.start_date + timedelta(days=req.day_number - 1)
                    try:
                        edit_code(req.student, req.subject, int(new_code_str), request.user, for_date=target_date)
                    except Exception as _ec_err:
                        messages.warning(request, f'Retake approved, but code update failed: {_ec_err}')
                        
            req.processed_at = timezone.now()
            req.processed_by = request.user
            req.save()

            # Auto-reject any OTHER pending requests for same (student, day, subject)
            from exams.models import RetakeRequest as _RR
            _stale_count = _RR.objects.filter(
                student=req.student, day_number=req.day_number,
                subject=req.subject, status='PENDING'
            ).exclude(id=req.id).update(
                status='REJECTED',
                processed_at=timezone.now(),
                processed_by=request.user,
            )
            if _stale_count:
                messages.info(request, f'(Auto-closed {_stale_count} duplicate pending request(s) for same subject.)')

            messages.success(
                request,
                f'✅ Approved: {req.student.code} Day {req.day_number} {req.subject} '
                f'— {req.attempts_granted} attempt(s) granted'
            )
            return redirect(_back)

        # ── RETAKE REQUEST: Bulk Approve All ──
        if action == 'approve_all_retake_requests':
            from exams.models import RetakeRequest
            try:
                attempts_per = int(request.POST.get('attempts_per', 1))
            except (ValueError, TypeError):
                attempts_per = 1
            attempts_per = max(1, min(10, attempts_per))

            bulk_new_code = request.POST.get('bulk_new_code', '').strip()
            pending = RetakeRequest.objects.filter(status='PENDING')
            count = pending.count()
            from exams.models import StudentDailyCode, EngineState
            from datetime import timedelta
            eng = EngineState.objects.first()
            
            for req in pending:
                req.status = 'APPROVED'
                req.attempts_granted = attempts_per
                
                if bulk_new_code.isdigit():
                    req.override_code = int(bulk_new_code)
                    if eng and eng.start_date:
                        target_date = eng.start_date + timedelta(days=req.day_number - 1)
                        try:
                            edit_code(req.student, req.subject, int(bulk_new_code), request.user, for_date=target_date)
                        except Exception as _ec_err:
                            messages.warning(request, f'Bulk retake code update failed for {req.student.code}: {_ec_err}')
                            
                req.processed_at = timezone.now()
                req.processed_by = request.user
                req.save()

            if count > 0:
                messages.success(
                    request,
                    f'✅ Bulk approved {count} retake request(s) — each granted {attempts_per} attempt(s)'
                )
            else:
                messages.info(request, 'No pending retake requests to approve.')
            return redirect(_back)

        # ── RETAKE REQUEST: Reject ──
        if action == 'reject_retake_request':
            from exams.models import RetakeRequest
            try:
                req_id = int(request.POST.get('request_id', 0))
            except (ValueError, TypeError):
                messages.error(request, 'Invalid request.')
                return redirect(_back)

            req = RetakeRequest.objects.filter(id=req_id, status='PENDING').first()
            if not req:
                messages.error(request, 'Request not found or already processed.')
                return redirect(_back)

            req.status = 'REJECTED'
            req.processed_at = timezone.now()
            req.processed_by = request.user
            req.save()
            messages.success(
                request,
                f'❌ Rejected: {req.student.code} Day {req.day_number} {req.subject}'
            )
            return redirect(_back)

        if action == 'set_day_policy':
            _st = request.POST.get('policy_status', 'LOCKED')
            if _st in ('LOCKED', 'OPEN', 'PAST_REATTEMPT'):
                day_policy.status = _st
                try: day_policy.late_penalty_pct = float(request.POST.get('late_penalty_pct', '10.00'))
                except (ValueError, TypeError): pass
                day_policy.opened_by = request.user
                day_policy.save()
                messages.success(request, f'✅ Day {selected_day} policy set to {_st}')
            return redirect(_back)

        # Individual code
        if action == 'set_individual':
            s_code = (request.POST.get('scope_student') or request.POST.get('student_code') or '').strip()
            subject = (request.POST.get('subject') or '').strip()
            try:
                code_num = int(request.POST.get('code', '0'))
            except (ValueError, TypeError):
                messages.error(request, 'Code must be a number.')
                return redirect(_back)
            s = Student.objects.filter(code=s_code, is_active=True).first()
            if not s:
                messages.error(request, f'Student {s_code} not found.')
                return redirect(_back)
            pace = s.daily_question_count or 1
            if not (1 <= code_num <= pace):
                messages.error(request, f'Code must be 1..{pace} for {s.code}.')
                return redirect(_back)
            if selected_date <= timezone.localdate() and AttemptLog.objects.filter(
                student=s, question__paper__subject=subject, created_at__date=selected_date
            ).exists():
                messages.error(request, f'Cannot change {subject} for {s.code}: already submitted on Day {selected_day}.')
                return redirect(_back)
            edit_code(s, subject, code_num, request.user, for_date=selected_date)
            messages.success(request, f'{s.code} {subject} = {code_num} (Day {selected_day})')
            return redirect(_back)

        # Class codes
        if action == 'set_class':
            class_name = (request.POST.get('class') or '').strip()
            if not class_name:
                messages.error(request, 'Class required.')
                return redirect(_back)
            BOOK_ABBR = {
                'Urdu': 'UR', 'English': 'EN', 'Islamiyat': 'IS',
                'Mathematics': 'MA', 'Chemistry': 'CH', 'Physics': 'PH',
                'Tarjumatul Quran': 'TQ', 'Computer Science': 'CS',
                'Biology': 'BI', 'Bio': 'BI', 'Computer': 'CS',
                'Pak Study': 'PS',
            }
            subj_codes = {}
            for subj, abbr in BOOK_ABBR.items():
                val = (request.POST.get(f'code_{abbr}') or '').strip()
                if val:
                    try: subj_codes[subj] = int(val)
                    except (ValueError, TypeError): pass
            if not subj_codes:
                messages.error(request, 'No codes supplied.')
                return redirect(_back)
            updated, skipped = 0, 0
            for s in Student.objects.filter(is_active=True, student_class=class_name):
                pace = s.daily_question_count or 1
                for subj, num in subj_codes.items():
                    if not (1 <= num <= pace):
                        continue
                    if selected_date <= timezone.localdate() and AttemptLog.objects.filter(
                        student=s, question__paper__subject=subj, created_at__date=selected_date
                    ).exists():
                        skipped += 1
                        continue
                    edit_code(s, subj, num, request.user, for_date=selected_date)
                    updated += 1
            # Auto-publish visibility so students can see the new codes
            from exams.models_day_mission import DailyCodeVisibility
            for shift_name in ('morning', 'evening'):
                vis, _ = DailyCodeVisibility.objects.get_or_create(
                    date=selected_date, target_student=None,
                    target_class=class_name, target_shift=shift_name,
                    defaults={'is_visible': True}
                )
                vis.is_visible = True
                if shift_name == 'morning':
                    vis.morning_visible = True
                else:
                    vis.evening_visible = True
                vis.save()

            messages.success(
                request,
                f'Class {class_name}: {updated} codes set, {skipped} skipped. '
                f'✅ Visibility auto-published for both shifts on Day {selected_day}.'
            )
            return redirect(_back)

        # Bulk generate — single day
        if action == 'bulk_generate_day':
            from exams.management.commands.assign_daily_codes import (
                build_per_book_codes, ALL_SUBJECTS
            )
            target_class = request.POST.get('class', selected_class).strip()
            if not target_class:
                messages.error(request, 'Class required to generate codes.')
                return redirect(_back)
            
            # Cache codes per pace so all students in same pace get same codes (fairness)
            pace_codes_cache = {}
            created_n, updated_n = 0, 0
            for s in Student.objects.filter(is_active=True, student_class=target_class):
                pace = s.daily_question_count or 1
                if pace not in pace_codes_cache:
                    pace_codes_cache[pace] = {
                        subj: random.randint(1, pace) for subj in ALL_SUBJECTS
                    }
                per_book = build_per_book_codes(s, pace_codes_cache[pace])
                row, created = StudentDailyCode.objects.get_or_create(
                    student=s, date=selected_date,
                    defaults={
                        'code': random.randint(1, pace),
                        'per_book_codes': per_book,
                    }
                )
                if created:
                    created_n += 1
                else:
                    row.per_book_codes = per_book
                    row.code = random.randint(1, pace)
                    row.save(update_fields=['per_book_codes', 'code'])
                    updated_n += 1
            messages.success(
                request,
                f'✅ Class {target_class}: {created_n} new, {updated_n} updated for Day {selected_day}.'
            )
            return redirect(_back)


        # Bulk generate — range
        if action == 'bulk_generate_range':
            try:
                _rs = int(request.POST.get('range_start', str(current_day)))
                _re = int(request.POST.get('range_end', str(current_day)))
            except (ValueError, TypeError):
                messages.error(request, 'Range must be integers.')
                return redirect(_back)
            if not (1 <= _rs <= _re <= max_day):
                messages.error(request, f'Range must satisfy 1 <= start <= end <= {max_day}.')
                return redirect(_back)
            if _re - _rs > 30:
                messages.error(request, 'Range limited to 30 days at once (safety).')
                return redirect(_back)
            BOOK_ABBR = {
                'Urdu': 'UR', 'English': 'EN', 'Islamiyat': 'IS',
                'Mathematics': 'MA', 'Chemistry': 'CH', 'Physics': 'PH',
                'Tarjumatul Quran': 'TQ', 'Computer Science': 'CS',
                'Biology': 'BI', 'Bio': 'BI', 'Computer': 'CS',
                'Pak Study': 'PS',
            }
            def _gen_for_books(books, pace):
                result, order = {}, []
                for b in books:
                    abbr = BOOK_ABBR.get(b, b[:2].upper() if len(b) >= 2 else b.upper())
                    result[abbr] = random.randint(1, pace)
                    order.append(abbr)
                return result, order
            total_created, total_updated = 0, 0
            for day_n in range(_rs, _re + 1):
                date_n = engine.start_date + _td(days=day_n - 1)
                for s in Student.objects.filter(is_active=True, student_class__startswith='9'):
                    pace = s.daily_question_count or 1
                    opt = (getattr(s, 'assigned_subject', '') or 'Biology').strip() or 'Biology'
                    m = ['Physics', 'Chemistry', opt, 'Tarjumatul Quran']
                    e = ['Mathematics', 'English', 'Urdu', 'Pak Study' if s.student_class == '10' else 'Islamiyat']
                    m_c, m_o = _gen_for_books(m, pace)
                    e_c, e_o = _gen_for_books(e, pace)
                    obj, created = StudentDailyCode.objects.update_or_create(
                        student=s, date=date_n,
                        defaults={'per_book_codes': {
                            'morning': m_c, 'evening': e_c,
                            'morning_order': m_o, 'evening_order': e_o}})
                    if created: total_created += 1
                    else: total_updated += 1
            messages.success(request, f'✅ Days {_rs}–{_re}: {total_created} new, {total_updated} updated.')
            return redirect(_back)

        # Bulk publish — range
        if action == 'bulk_publish_range':
            try:
                _ps = int(request.POST.get('publish_start', '0'))
                _pe = int(request.POST.get('publish_end', '0'))
            except (ValueError, TypeError):
                messages.error(request, 'Publish range must be integers.')
                return redirect(_back)
            if not (1 <= _ps <= _pe <= max_day):
                messages.error(request, f'Publish range must satisfy 1 <= start <= end <= {max_day}.')
                return redirect(_back)
            if _pe - _ps > 30:
                messages.error(request, 'Publish range limited to 30 days at once (safety).')
                return redirect(_back)
            published_n = 0
            for day_n in range(_ps, _pe + 1):
                date_n = engine.start_date + _td(days=day_n - 1)
                DailyCodeVisibility.objects.update_or_create(
                    date=date_n, target_student__isnull=True,
                    target_class='', target_shift='',
                    defaults={
                        'is_visible': True,
                        'morning_visible': True,
                        'evening_visible': True,
                        'published_at': timezone.now(),
                        'published_by': request.user,
                        'hidden_at': None,
                        'hidden_by': None,
                    }
                )
                published_n += 1
            messages.success(request, f'✅ Days {_ps}–{_pe} published ({published_n} days).')
            return redirect(_back)

        # Grant retake — scoped (student / class / class+shift / shift / all)
        if action == 'grant_student_retake':
            scope_type = (request.POST.get('scope_type') or 'STUDENT').strip().upper()

            target_student_obj = None
            target_class_val = ''
            target_shift_val = ''

            if scope_type == 'STUDENT':
                s_code = (request.POST.get('scope_student') or request.POST.get('scope_student') or request.POST.get('student_code') or '').strip()
                s = Student.objects.filter(code__iexact=s_code, is_active=True).first()
                if not s:
                    messages.error(request, f'Student {s_code} not found.')
                    return redirect(_back)
                target_student_obj = s
                scope_label = f'Student {s.code}'
            elif scope_type == 'CLASS':
                target_class_val = (request.POST.get('target_class') or '').strip()
                if not target_class_val:
                    messages.error(request, 'Class required for CLASS scope.')
                    return redirect(_back)
                scope_label = f'Class {target_class_val}'
            elif scope_type == 'CLASS_SHIFT':
                target_class_val = (request.POST.get('target_class') or '').strip()
                target_shift_val = (request.POST.get('target_shift') or '').strip().lower()
                if not target_class_val or target_shift_val not in ('morning', 'evening'):
                    messages.error(request, 'Class + shift required for CLASS_SHIFT scope.')
                    return redirect(_back)
                scope_label = f'Class {target_class_val} · {target_shift_val.title()}'
            elif scope_type == 'SHIFT':
                target_shift_val = (request.POST.get('target_shift') or '').strip().lower()
                if target_shift_val not in ('morning', 'evening'):
                    messages.error(request, 'Valid shift required for SHIFT scope.')
                    return redirect(_back)
                scope_label = f'All {target_shift_val.title()} students'
            elif scope_type == 'ALL':
                scope_label = 'All students'
            else:
                messages.error(request, f'Invalid scope: {scope_type}')
                return redirect(_back)

            try:
                _max_att = int(request.POST.get('max_attempts', '2'))
            except (ValueError, TypeError):
                _max_att = 2
            try:
                _late_pen = float(request.POST.get('late_penalty_pct', '0.00'))
            except (ValueError, TypeError):
                _late_pen = 0.0

            DayAttemptPolicy.objects.update_or_create(
                date=selected_date,
                target_student=target_student_obj,
                target_class=target_class_val,
                target_shift=target_shift_val,
                defaults={
                    'status': 'PAST_REATTEMPT',
                    'max_attempts': _max_att,
                    'late_penalty_pct': _late_pen,
                    'opened_by': request.user,
                    'notes': f'Scoped retake override ({scope_type}) by {request.user.username}',
                }
            )

            # Optional code override (only meaningful for STUDENT scope)
            _code_subject = (request.POST.get('override_subject') or '').strip()
            _code_value = (request.POST.get('override_code') or '').strip()
            _msg_extra = ''
            if scope_type == 'STUDENT' and _code_subject and _code_value:
                try:
                    _code_int = int(_code_value)
                    _pace = target_student_obj.daily_question_count or 1
                    if 1 <= _code_int <= _pace:
                        edit_code(target_student_obj, _code_subject, _code_int, request.user, for_date=selected_date)
                        _msg_extra = f' · Code {_code_int} for {_code_subject}'
                    else:
                        messages.warning(request, f'Code must be 1..{_pace} — code skipped.')
                except (ValueError, TypeError):
                    messages.warning(request, f'Invalid code "{_code_value}" — code skipped.')

            messages.success(request, f'✅ Retake opened: {scope_label} on Day {selected_day}{_msg_extra}')
            return redirect(_back)

        # Publish/hide codes — scoped (student / class / class+shift / shift / all)
        if action == 'publish_student_codes':
            scope_type = (request.POST.get('scope_type') or 'STUDENT').strip().upper()
            visibility_action = (request.POST.get('visibility_action') or 'show').strip().lower()
            _is_show = visibility_action == 'show'

            target_student_obj = None
            target_class_val = ''
            target_shift_val = ''

            if scope_type == 'STUDENT':
                s_code = (request.POST.get('scope_student') or request.POST.get('scope_student') or request.POST.get('student_code') or '').strip()
                s = Student.objects.filter(code__iexact=s_code, is_active=True).first()
                if not s:
                    messages.error(request, f'Student {s_code} not found.')
                    return redirect(_back)
                target_student_obj = s
                scope_label = f'Student {s.code}'
            elif scope_type == 'CLASS':
                target_class_val = (request.POST.get('target_class') or '').strip()
                if not target_class_val:
                    messages.error(request, 'Class required for CLASS scope.')
                    return redirect(_back)
                scope_label = f'Class {target_class_val}'
            elif scope_type == 'CLASS_SHIFT':
                target_class_val = (request.POST.get('target_class') or '').strip()
                target_shift_val = (request.POST.get('target_shift') or '').strip().lower()
                if not target_class_val or target_shift_val not in ('morning', 'evening'):
                    messages.error(request, 'Class + shift required.')
                    return redirect(_back)
                scope_label = f'Class {target_class_val} · {target_shift_val.title()}'
            elif scope_type == 'SHIFT':
                target_shift_val = (request.POST.get('target_shift') or '').strip().lower()
                if target_shift_val not in ('morning', 'evening'):
                    messages.error(request, 'Valid shift required.')
                    return redirect(_back)
                scope_label = f'All {target_shift_val.title()} students'
            elif scope_type == 'ALL':
                scope_label = 'All students'
            else:
                messages.error(request, f'Invalid scope: {scope_type}')
                return redirect(_back)

            _shift = (request.POST.get('shift', 'both')).strip()
            _toggle_morning = _shift in ('morning', 'both')
            _toggle_evening = _shift in ('evening', 'both')

            # Fetch existing or create new (preserve other half when toggling one side)
            existing = DailyCodeVisibility.objects.filter(
                date=selected_date,
                target_student=target_student_obj,
                target_class=target_class_val,
                target_shift=target_shift_val,
            ).first()

            if existing:
                if _toggle_morning:
                    existing.morning_visible = _is_show
                if _toggle_evening:
                    existing.evening_visible = _is_show
                existing.is_visible = existing.morning_visible or existing.evening_visible
                if _is_show:
                    existing.published_at = timezone.now()
                    existing.published_by = request.user
                    existing.hidden_at = None
                    existing.hidden_by = None
                else:
                    existing.hidden_at = timezone.now()
                    existing.hidden_by = request.user
                existing.save()
            else:
                DailyCodeVisibility.objects.create(
                    date=selected_date,
                    target_student=target_student_obj,
                    target_class=target_class_val,
                    target_shift=target_shift_val,
                    is_visible=_is_show,
                    morning_visible=_is_show and _toggle_morning,
                    evening_visible=_is_show and _toggle_evening,
                    published_at=timezone.now() if _is_show else None,
                    published_by=request.user if _is_show else None,
                    hidden_at=None if _is_show else timezone.now(),
                    hidden_by=None if _is_show else request.user,
                )

            verb = 'shown to' if _is_show else 'hidden from'
            icon = '✅' if _is_show else '🔒'
            messages.success(request, f'{icon} Codes {verb} {scope_label} on Day {selected_day} ({_shift})')
            return redirect(_back)

        # Revoke overrides — scoped (works for any scope)
        if action == 'revoke_override':
            s_code = (request.POST.get('scope_student') or request.POST.get('student_code') or '').strip()
            t_class = (request.POST.get('target_class') or '').strip()
            t_shift = (request.POST.get('target_shift') or '').strip().lower()

            filters = {'date': selected_date, 'target_class': t_class, 'target_shift': t_shift}
            if s_code:
                s = Student.objects.filter(code=s_code, is_active=True).first()
                if not s:
                    messages.error(request, f'Student {s_code} not found.')
                    return redirect(_back)
                filters['target_student'] = s
                scope_label = f'Student {s.code}'
            else:
                filters['target_student__isnull'] = True
                if t_class and t_shift:
                    scope_label = f'Class {t_class} · {t_shift.title()}'
                elif t_class:
                    scope_label = f'Class {t_class}'
                elif t_shift:
                    scope_label = f'All {t_shift.title()} students'
                else:
                    scope_label = 'All students'

            DayAttemptPolicy.objects.filter(**filters).delete()
            DailyCodeVisibility.objects.filter(**filters).delete()
            messages.success(request, f'✅ Override revoked: {scope_label} on Day {selected_day}')
            return redirect(_back)

        # Assign question override — scoped
        if action == 'assign_question_override':
            from exams.models_day_mission import QuestionAssignment
            scope_type = (request.POST.get('scope_type') or 'STUDENT').strip().upper()

            target_student_obj = None
            target_class_val = ''
            target_shift_val = ''

            if scope_type == 'STUDENT':
                s_code = (request.POST.get('scope_student') or request.POST.get('scope_student') or request.POST.get('student_code') or '').strip()
                s = Student.objects.filter(code__iexact=s_code, is_active=True).first()
                if not s:
                    messages.error(request, f'Student {s_code} not found.')
                    return redirect(_back)
                target_student_obj = s
                scope_label = f'Student {s.code}'
            elif scope_type == 'CLASS':
                target_class_val = (request.POST.get('target_class') or '').strip()
                if not target_class_val:
                    messages.error(request, 'Class required.')
                    return redirect(_back)
                scope_label = f'Class {target_class_val}'
            elif scope_type == 'CLASS_SHIFT':
                target_class_val = (request.POST.get('target_class') or '').strip()
                target_shift_val = (request.POST.get('target_shift') or '').strip().lower()
                if not target_class_val or target_shift_val not in ('morning', 'evening'):
                    messages.error(request, 'Class + shift required.')
                    return redirect(_back)
                scope_label = f'Class {target_class_val} · {target_shift_val.title()}'
            elif scope_type == 'SHIFT':
                target_shift_val = (request.POST.get('target_shift') or '').strip().lower()
                if target_shift_val not in ('morning', 'evening'):
                    messages.error(request, 'Valid shift required.')
                    return redirect(_back)
                scope_label = f'All {target_shift_val.title()} students'
            elif scope_type == 'ALL':
                scope_label = 'All students'
            else:
                messages.error(request, f'Invalid scope: {scope_type}')
                return redirect(_back)

            subject_val = (request.POST.get('subject') or '').strip()
            try:
                position_val = int(request.POST.get('position') or 0)
            except (ValueError, TypeError):
                position_val = 0
            try:
                question_id_val = int(request.POST.get('question_id') or 0)
            except (ValueError, TypeError):
                question_id_val = 0

            from exams.models import ModelQuestion
            q = ModelQuestion.objects.filter(id=question_id_val).first()
            if not q:
                messages.error(request, 'Question not found.')
                return redirect(_back)
            if not subject_val:
                messages.error(request, 'Subject required.')
                return redirect(_back)
            if position_val < 1:
                messages.error(request, 'Position must be ≥ 1.')
                return redirect(_back)

            QuestionAssignment.objects.update_or_create(
                date=selected_date,
                target_student=target_student_obj,
                target_class=target_class_val,
                target_shift=target_shift_val,
                subject=subject_val,
                position=position_val,
                defaults={
                    'question': q,
                    'assigned_by': request.user,
                    'is_active': True,
                }
            )
            messages.success(request, f'✅ Q{q.id} assigned at {subject_val} pos {position_val} to {scope_label} on Day {selected_day}')
            return redirect(_back)

        # ── BULK: Assign N questions to consecutive positions ──
        if action == 'assign_question_override_bulk':
            from exams.models_day_mission import QuestionAssignment
            from exams.models import ModelQuestion
            scope_type = (request.POST.get('scope_type') or 'STUDENT').strip().upper()

            target_student_obj = None
            target_class_val = ''
            target_shift_val = ''

            if scope_type == 'STUDENT':
                s_code = (request.POST.get('scope_student') or request.POST.get('scope_student') or request.POST.get('student_code') or '').strip()
                s = Student.objects.filter(code__iexact=s_code, is_active=True).first()
                if not s:
                    messages.error(request, f'Student {s_code} not found.')
                    return redirect(_back)
                target_student_obj = s
                scope_label = f'Student {s.code}'
            elif scope_type == 'CLASS':
                target_class_val = (request.POST.get('target_class') or '').strip()
                if not target_class_val:
                    messages.error(request, 'Class required.')
                    return redirect(_back)
                scope_label = f'Class {target_class_val}'
            elif scope_type == 'CLASS_SHIFT':
                target_class_val = (request.POST.get('target_class') or '').strip()
                target_shift_val = (request.POST.get('target_shift') or '').strip().lower()
                if not target_class_val or target_shift_val not in ('morning', 'evening'):
                    messages.error(request, 'Class + shift required.')
                    return redirect(_back)
                scope_label = f'Class {target_class_val} · {target_shift_val.title()}'
            elif scope_type == 'SHIFT':
                target_shift_val = (request.POST.get('target_shift') or '').strip().lower()
                if target_shift_val not in ('morning', 'evening'):
                    messages.error(request, 'Valid shift required.')
                    return redirect(_back)
                scope_label = f'All {target_shift_val.title()} students'
            elif scope_type == 'ALL':
                scope_label = 'All students'
            else:
                messages.error(request, f'Invalid scope: {scope_type}')
                return redirect(_back)

            subject_val = (request.POST.get('subject') or '').strip()
            if not subject_val:
                messages.error(request, 'Subject required.')
                return redirect(_back)

            try:
                start_pos = int(request.POST.get('start_position') or 1)
            except (ValueError, TypeError):
                start_pos = 1
            if start_pos < 1:
                start_pos = 1

            # Parse question IDs (JSON array or comma-separated)
            import json as _json
            qids_raw = request.POST.get('question_ids') or ''
            question_ids = []
            try:
                parsed = _json.loads(qids_raw)
                if isinstance(parsed, list):
                    question_ids = [int(x) for x in parsed if str(x).strip().isdigit()]
            except Exception:
                # Fallback: comma-separated
                question_ids = [int(x.strip()) for x in qids_raw.split(',') if x.strip().isdigit()]

            if not question_ids:
                messages.error(request, 'Select at least one question.')
                return redirect(_back)
            if len(question_ids) > 50:
                messages.error(request, f'Too many questions ({len(question_ids)}). Max 50 per batch.')
                return redirect(_back)

            # Sanity: don't exceed position 50
            if start_pos + len(question_ids) - 1 > 50:
                messages.error(request, f'Start pos {start_pos} + {len(question_ids)} questions exceeds position 50.')
                return redirect(_back)

            # Fetch all questions
            qmap = {q.id: q for q in ModelQuestion.objects.filter(id__in=question_ids)}
            missing = [qid for qid in question_ids if qid not in qmap]
            if missing:
                messages.warning(request, f'{len(missing)} question(s) not found and skipped.')

            created = 0
            for idx, qid in enumerate(question_ids):
                q = qmap.get(qid)
                if not q:
                    continue
                position = start_pos + idx
                QuestionAssignment.objects.update_or_create(
                    date=selected_date,
                    target_student=target_student_obj,
                    target_class=target_class_val,
                    target_shift=target_shift_val,
                    subject=subject_val,
                    position=position,
                    defaults={
                        'question': q,
                        'assigned_by': request.user,
                        'is_active': True,
                    }
                )
                created += 1

            end_pos = start_pos + created - 1 if created else start_pos
            messages.success(
                request,
                f'✅ {created} question(s) assigned to {subject_val} positions {start_pos}–{end_pos} for {scope_label} on Day {selected_day}'
            )
            return redirect(_back)

        # Revoke a question assignment
        if action == 'revoke_question_assignment':
            from exams.models_day_mission import QuestionAssignment
            try:
                _qa_id = int(request.POST.get('assignment_id') or 0)
            except (ValueError, TypeError):
                _qa_id = 0
            qa = QuestionAssignment.objects.filter(id=_qa_id, date=selected_date).first()
            if not qa:
                messages.error(request, 'Assignment not found.')
                return redirect(_back)
            scope_desc = qa.target_student.code if qa.target_student else (
                qa.target_class or qa.target_shift or 'ALL'
            )
            qa.delete()
            messages.success(request, f'✅ Override revoked for {scope_desc} on Day {selected_day}')
            return redirect(_back)

        # Unknown action — fall through to GET display
        messages.error(request, f'Unknown action: {action}')
        return redirect(_back)

    # ─── GET: DISPLAY DATA ───
    BOOK_ABBR = {
        'Urdu': 'UR', 'English': 'EN', 'Islamiyat': 'IS',
        'Mathematics': 'MA', 'Chemistry': 'CH', 'Physics': 'PH',
        'Tarjumatul Quran': 'TQ', 'Computer Science': 'CS',
        'Biology': 'BI', 'Bio': 'BI', 'Computer': 'CS',
    }
    total_active = Student.objects.filter(is_active=True, student_class=selected_class).count()

    # Coverage map: {day_number: students_with_codes}
    _ninth_ids = set(Student.objects.filter(is_active=True, student_class__startswith='9').values_list('id', flat=True))
    coverage = {}
    for row in StudentDailyCode.objects.filter(student_id__in=_ninth_ids).only('date', 'per_book_codes'):
        d = (row.date - engine.start_date).days + 1
        if 1 <= d <= max_day:
            p = row.per_book_codes or {}
            if p.get('morning') or p.get('evening'):
                coverage[d] = coverage.get(d, 0) + 1
    coverage_days = []
    for d in range(1, max_day + 1):
        cnt = coverage.get(d, 0)
        if d > current_day: st = 'future'
        elif cnt == 0: st = 'missing'
        elif cnt >= total_active: st = 'full'
        else: st = 'partial'
        coverage_days.append({'day': d, 'count': cnt, 'total': total_active, 'state': st})

    class_filter = (request.GET.get('class') or '').strip()
    students_qs = Student.objects.filter(is_active=True).order_by('student_class', 'code')
    if class_filter:
        students_qs = students_qs.filter(student_class=class_filter)

    codes_today = {c.student_id: c for c in StudentDailyCode.objects.filter(date=selected_date)}

    rows = []
    for s in students_qs:
        pace = s.daily_question_count or 1
        record = codes_today.get(s.id)
        payload = (record.per_book_codes if record else {}) or {}

        if payload and 'morning' in payload and 'evening' in payload:
            m_codes = payload.get('morning', {}) or {}
            e_codes = payload.get('evening', {}) or {}
            m_order = payload.get('morning_order', list(m_codes.keys()))
            e_order = payload.get('evening_order', list(e_codes.keys()))
        elif payload:
            m_codes = {k: v for k, v in payload.items() if k in ('PH','CH','BI','CS','TQ')}
            e_codes = {k: v for k, v in payload.items() if k in ('MA','EN','UR','IS')}
            m_order = [k for k in ('PH','CH','BI','CS','TQ') if k in m_codes]
            e_order = [k for k in ('MA','EN','UR','IS') if k in e_codes]
        else:
            m_codes, e_codes, m_order, e_order = {}, {}, [], []

        morning_pairs = [(a, m_codes[a]) for a in m_order if a in m_codes]
        evening_pairs = [(a, e_codes[a]) for a in e_order if a in e_codes]
        morning_str = '-'.join(f'{a}{n}' for a, n in morning_pairs)
        evening_str = '-'.join(f'{a}{n}' for a, n in evening_pairs)
        legacy_code = record.code if record else 0

        rows.append({
            'student': s, 'pace': pace,
            'morning_pairs': morning_pairs, 'evening_pairs': evening_pairs,
            'morning_str': morning_str, 'evening_str': evening_str,
            'legacy_code': legacy_code,
            'has_new_codes': bool(morning_pairs or evening_pairs),
            'has_legacy': legacy_code > 0,
        })

    class_options = sorted(set(
        Student.objects.filter(is_active=True).values_list('student_class', flat=True)
    ))

    # Overrides — merge policy + visibility, keyed by exact scope (student_id, class, shift)
    _retakes = DayAttemptPolicy.objects.filter(date=selected_date).exclude(
        target_student__isnull=True, target_class='', target_shift=''
    ).select_related('target_student')
    _visible_overrides = DailyCodeVisibility.objects.filter(date=selected_date).exclude(
        target_student__isnull=True, target_class='', target_shift=''
    ).select_related('target_student')

    _override_map = {}
    def _compute_scope_label(student_obj, t_class, t_shift):
        if student_obj:
            return f'Student: {student_obj.code}'
        if t_class and t_shift:
            return f'Class {t_class} · {t_shift.title()}'
        if t_class:
            return f'Class {t_class}'
        if t_shift:
            return f'All {t_shift.title()}'
        return 'All students'

    for p in _retakes:
        key = (p.target_student_id, p.target_class, p.target_shift)
        _override_map[key] = {
            'student': p.target_student,
            'target_class': p.target_class,
            'target_shift': p.target_shift,
            'scope_label': _compute_scope_label(p.target_student, p.target_class, p.target_shift),
            'policy': p,
            'visibility': None,
        }
    for v in _visible_overrides:
        key = (v.target_student_id, v.target_class, v.target_shift)
        if key in _override_map:
            _override_map[key]['visibility'] = v
        else:
            _override_map[key] = {
                'student': v.target_student,
                'target_class': v.target_class,
                'target_shift': v.target_shift,
                'scope_label': _compute_scope_label(v.target_student, v.target_class, v.target_shift),
                'policy': None,
                'visibility': v,
            }
    overrides_list = sorted(_override_map.values(), key=lambda x: x['scope_label'])

    _students_for_context = Student.objects.filter(is_active=True).order_by('code')
    # ─── DYNAMIC CLASS CHOICES (Merge static choices with DB classes) ───
    _static_choices = list(Student.CLASS_CHOICES)
    _static_vals = {c[0] for c in _static_choices}
    _db_classes = Student.objects.values_list('student_class', flat=True).distinct()
    for _dc in _db_classes:
        if _dc and _dc not in _static_vals:
            # Format custom name beautifully (e.g., 'Umer_Ideology' -> 'Umer Ideology')
            _label = str(_dc).replace('_', ' ').title()
            _static_choices.append((_dc, _label))
            
    # ── POPULATE ALL_SUBJECTS (Fix for empty Subject dropdown) ──
    from exams.management.commands.assign_daily_codes import ALL_SUBJECTS
    all_subjects = list(ALL_SUBJECTS)

    return render(request, 'exams/portal_teacher_daily_codes.html', {
        'all_subjects': all_subjects,
        'class_choices': _static_choices,
        'students': _students_for_context,
        
        'engine': engine,
        'current_day': current_day,
        'max_day': max_day,
        'selected_day': selected_day,
        'selected_date': selected_date,
        'selected_date_iso': selected_date.strftime('%Y-%m-%d'),
        'day_label': day_label,
        'visibility': visibility,
        'day_policy': day_policy,
        'coverage': coverage,
        'coverage_days': coverage_days,
        'total_active': total_active,
        'rows': rows,
        'class_filter': class_filter,
        'class_options': class_options,
        'today_iso': timezone.localdate().strftime('%Y-%m-%d'),
        'overrides_list': overrides_list,
        'effective_visibility_count': _compute_effective_visibility(selected_date, visibility),
        'question_assignments_list': _compute_question_assignments(selected_date),
        'pending_retake_requests': __import__('exams.models', fromlist=['RetakeRequest']).RetakeRequest.objects.filter(status='PENDING').select_related('student').order_by('-requested_at'),
        'retake_policy': __import__('exams.models', fromlist=['RetakePolicy']).RetakePolicy.objects.first(),
        'active_exemptions': __import__('exams.models', fromlist=['RetakeExemption']).RetakeExemption.objects.select_related('student', 'granted_by').order_by('-granted_at')[:50],
        'all_students': __import__('exams.models', fromlist=['Student']).Student.objects.filter(is_active=True).order_by('code'),

        'subject_options': _get_subject_options(),
    'selected_class': selected_class,
        })


@login_required
def teacher_pool_alerts(request):
    """Dashboard for Human-in-the-Loop pool exhaustion decisions."""
    if not (request.user.is_staff or request.user.is_superuser):
        messages.error(request, 'Access denied.')
        return redirect('portal-dashboard')
    
    from exams.models_day_mission import PoolExhaustionAlert
    
    if request.method == 'POST':
        alert_id = request.POST.get('alert_id')
        decision = request.POST.get('decision')
        notes = (request.POST.get('notes') or '').strip()
        
        if decision in ('LOOP_BACK', 'EXTENDED', 'SKIPPED'):
            alert = PoolExhaustionAlert.objects.filter(id=alert_id).first()
            if alert:
                alert.decision = decision
                alert.decided_by = request.user
                alert.decided_at = timezone.now()
                alert.notes = notes
                alert.save()
                messages.success(
                    request,
                    f'✅ {alert.book} ({alert.student_class}): {alert.get_decision_display()}'
                )
            else:
                messages.error(request, 'Alert not found.')
        else:
            messages.error(request, 'Invalid decision.')
        return redirect('teacher-pool-alerts')
    
    # Group by decision
    alerts = PoolExhaustionAlert.objects.all().order_by('-created_at')
    open_alerts = [a for a in alerts if a.decision == 'OPEN']
    decided_alerts = [a for a in alerts if a.decision != 'OPEN']
    
    return render(request, 'exams/teacher_pool_alerts.html', {
        'all_subjects': locals().get('all_subjects', []),
        'open_alerts': open_alerts,
        'decided_alerts': decided_alerts,
    })



def teacher_tamper_alerts(request):
    if not request.user.is_staff and not request.user.is_superuser:
        from django.core.exceptions import PermissionDenied
        raise PermissionDenied

    from exams.models import AttemptLog
    from django.shortcuts import render, redirect
    from django.contrib import messages
    from django.core.paginator import Paginator

    if request.method == 'POST' and request.POST.get('action') == 'reject':
        attempt_id = request.POST.get('attempt_id')
        try:
            attempt = AttemptLog.objects.get(id=attempt_id)
            attempt.score = 0
            attempt.outcome = 'WRONG'
            if isinstance(attempt.result_json, dict):
                attempt.result_json['ghost_alert'] = {} # clear alert
            attempt.save(update_fields=['score', 'outcome', 'result_json'])
            messages.success(request, "Submission rejected. Score set to 0.")
        except AttemptLog.DoesNotExist:
            messages.error(request, "Attempt not found.")
        return redirect('teacher-tamper-alerts')

    attempts = AttemptLog.objects.filter(is_physical=True).order_by('-created_at')[:2000]
    alerts = []
    for a in attempts:
        if isinstance(a.result_json, dict):
            ghost = a.result_json.get('ghost_alert', {})
            # Only show NEW genuine alerts. Ignore old 'Data Inconsistency' false alarms.
            if ghost and ghost.get('tampered') and ghost.get('reason') != 'Data Inconsistency':
                alerts.append({
                    'id': a.id,
                    'student_name': a.student.name,
                    'student_code': a.student.code,
                    'question': a.question.question_text[:60] + '...' if a.question.question_text else '',
                    'date': a.created_at.strftime('%Y-%m-%d %H:%M'),
                    'reason': ghost.get('reason', 'Security Mismatch'),
                    'story_stage': ghost.get('story_stage', 'N/A'),
                    'actual_pct': round(ghost.get('actual_pct', 0), 1),
                    'score': a.score,
                    'max_score': a.max_score,
                })

    # Add Pagination
    paginator = Paginator(alerts, 20) # Show 20 alerts per page
    page_number = request.GET.get('page')
    page_obj = paginator.get_page(page_number)

    return render(request, 'exams/teacher_tamper_alerts.html', {
        'all_subjects': locals().get('all_subjects', []),
        'alerts': page_obj, # Pass paginated object
        'page_obj': page_obj,
    })
def teacher_grant_retake_exemption(request):
    """Grant exemptions for one or more students. Bulk supported."""
    from exams.models import RetakeExemption, Student
    from django.utils import timezone
    from datetime import timedelta

    back = request.META.get('HTTP_REFERER', '/api/portal/teacher/daily-codes/')

    # AJAX Select2 submits a list of student codes
    student_codes = request.POST.getlist('student_codes')
    
    # Fallback for any old forms
    single = request.POST.get('single_student_code', '').strip()
    if single and not student_codes:
        student_codes = [s.strip() for s in single.split(',') if s.strip()]

    day_date_str = request.POST.get('day_date', '').strip()
    subject = request.POST.get('subject', '').strip()
    reason = request.POST.get('reason', '').strip()
    expires_date_str = request.POST.get('expires_date', '').strip()

    # 1. Calculate Day Number from chosen Date
    day_number = None
    if day_date_str:
        try:
            from datetime import datetime
            from exams.models import EngineState
            picked_date = datetime.strptime(day_date_str, '%Y-%m-%d').date()
            eng = EngineState.objects.first()
            if eng and eng.start_date:
                # Calculate which curriculum day this date corresponds to
                calc_day = (picked_date - eng.start_date).days + 1
                day_number = max(1, min(120, calc_day))
        except Exception as e:
            print(f"Date parsing error: {e}")
            pass

    # 2. Calculate Expiration Timestamp from chosen Date
    expires_at = None
    if expires_date_str:
        try:
            from datetime import datetime
            picked_exp = datetime.strptime(expires_date_str, '%Y-%m-%d').date()
            # Set to end of day (23:59:59)
            end_of_day = datetime.combine(picked_exp, datetime.max.time())
            expires_at = timezone.make_aware(end_of_day)
        except Exception:
            pass

    count = 0
    errors = []
    for code in student_codes:
        code = code.strip()
        if not code:
            continue
        s = Student.objects.filter(code=code, is_active=True).first()
        if not s:
            errors.append(f'{code} not found')
            continue
        RetakeExemption.objects.create(
            student=s,
            day_number=day_number,
            subject=subject,
            granted_by=request.user,
            reason=reason,
            expires_at=expires_at,
        )
        count += 1

    if count:
        messages.success(request, f'✅ Granted {count} retake exemption(s).')
    if errors:
        messages.warning(request, f'⚠️ Issues: {", ".join(errors)}')
    return redirect(back)


@login_required(login_url="portal-login")
@user_passes_test(lambda u: u.is_staff or u.is_superuser, login_url="portal-login")
@require_POST
def teacher_toggle_retake_policy(request):
    """Toggle the master RetakePolicy switch."""
    from exams.models import RetakePolicy

    back = request.META.get('HTTP_REFERER', '/api/portal/teacher/daily-codes/')
    policy, _ = RetakePolicy.objects.get_or_create(defaults={'require_memorization': True})

    action = request.POST.get('action', '')
    if action == 'toggle_memorization':
        policy.require_memorization = not policy.require_memorization
        policy.updated_by = request.user
        policy.save()
        state = 'ENABLED' if policy.require_memorization else 'DISABLED'
        messages.success(request, f'✅ Memorization requirement is now {state}.')
    elif action == 'toggle_active':
        policy.is_active = not policy.is_active
        policy.updated_by = request.user
        policy.save()
        state = 'ACTIVE' if policy.is_active else 'INACTIVE'
        messages.success(request, f'✅ Policy is now {state}.')

    return redirect(back)


@login_required(login_url="portal-login")
@user_passes_test(lambda u: u.is_staff or u.is_superuser, login_url="portal-login")
@require_POST
def teacher_revoke_exemption(request):
    """Revoke an exemption."""
    from exams.models import RetakeExemption
    back = request.META.get('HTTP_REFERER', '/api/portal/teacher/daily-codes/')
    eid = request.POST.get('exemption_id', '')
    if eid.isdigit():
        deleted, _ = RetakeExemption.objects.filter(pk=int(eid)).delete()
        if deleted:
            messages.success(request, '✅ Exemption revoked.')
    return redirect(back)

@login_required(login_url="portal-login")
@user_passes_test(lambda u: u.is_staff or u.is_superuser, login_url="portal-login")
def teacher_search_students_api(request):
    """AJAX endpoint for Select2 to search students by code or name."""
    from exams.models import Student
    from django.http import JsonResponse
    from django.db.models import Q

    q = request.GET.get('q', '').strip()
    results = []
    if q:
        students = Student.objects.filter(
            Q(code__icontains=q) | Q(name__icontains=q),
            is_active=True
        ).order_by('code')[:20]
        
        results = [{'id': s.code, 'text': f'{s.code} — {s.name}'} for s in students]
    
    return JsonResponse({'results': results})


# ═══════════════════════════════════════════════════════════════
# HITL TEACHER REVIEW DASHBOARD (Industry Standard)
# ═══════════════════════════════════════════════════════════════
from django.contrib.admin.views.decorators import staff_member_required
from django.utils import timezone
from django.db.models import Count, Q

@staff_member_required
def portal_teacher_review_queue(request):
    """Dashboard: List all submissions. Supports search for ANY paper."""
    from exams.models import AttemptLog
    from django.core.paginator import Paginator
    from django.db.models import Q

    status_filter = request.GET.get('status', 'pending_review')
    subject_filter = request.GET.get('subject', '')
    search_query = request.GET.get('search', '').strip()

    qs = AttemptLog.objects.select_related('student', 'question__paper').order_by('-created_at')

    # Apply Search (Student Code, Name, or Attempt ID)
    if search_query:
        qs = qs.filter(
            Q(student__code__icontains=search_query) | 
            Q(student__name__icontains=search_query) |
            Q(id__iexact=search_query)
        )

    # Apply Status Filter (Default to Pending, but allow viewing all)
    if status_filter == 'pending_review':
        qs = qs.filter(needs_review=True, review_status='pending_review')
    elif status_filter == 'approved':
        qs = qs.filter(needs_review=True, review_status='approved')
    elif status_filter == 'published':
        qs = qs.filter(review_status='published')
    # If status_filter is 'all', we don't filter by needs_review or status

    if subject_filter:
        qs = qs.filter(question__paper__subject=subject_filter)

    paginator = Paginator(qs, 25)
    page = request.GET.get('page', 1)
    attempts = paginator.get_page(page)

    subjects = AttemptLog.objects.values_list('question__paper__subject', flat=True).distinct().order_by('question__paper__subject')

    return render(request, 'exams/portal_teacher_review_queue.html', {
        'attempts': attempts,
        'subjects': subjects,
        'status_filter': status_filter,
        'subject_filter': subject_filter,
        'search_query': search_query,
        'total_pending': AttemptLog.objects.filter(needs_review=True, review_status='pending_review').count(),
        'total_approved': AttemptLog.objects.filter(needs_review=True, review_status='approved').count(),
    })


@staff_member_required
def portal_teacher_review_detail(request, attempt_id):
    """Deep-dive overlay: View submission, AI reasoning, and manually grade/edit."""
    from exams.models import AttemptLog
    attempt = get_object_or_404(AttemptLog, id=attempt_id)
    diag = attempt.result_json or {}

    # Ensure required dicts exist so template doesn't crash
    diag.setdefault('chief_examiner', {})
    diag.setdefault('story_data', {})
    diag.setdefault('panel_diagnosis', {}).setdefault('subject_specialist', {})
    diag['chief_examiner'].setdefault('model_topper_answer', {})
    diag['chief_examiner'].setdefault('masterpiece_feedback', {})
    diag['chief_examiner'].setdefault('treatment_plan', {})
    diag.setdefault('expert_scores', {})

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

        if not teacher_score:
            messages.error(request, 'Teacher score is required.')
        else:
            try:
                score_val = float(teacher_score)
                max_m = attempt.max_score or 2
                if score_val < 0 or score_val > max_m:
                    messages.error(request, f'Score must be between 0 and {max_m}.')
                else:
                    # AUDIT TRAIL
                    audit_log = {
                        'original_ai_score': attempt.score,
                        'original_ai_outcome': attempt.outcome,
                        'original_ai_band': diag.get('band', 'N/A'),
                        'teacher_score': score_val,
                        'teacher_feedback': teacher_feedback,
                        'reviewed_by': request.user.username,
                        'reviewed_at': timezone.now().isoformat(),
                        'action': action,
                    }

                    # UPDATE EVERY EDITABLE FIELD IN result_json
                    diag['student_answer_transcribed'] = request.POST.get('student_answer_transcribed', diag.get('student_answer_transcribed', ''))
                    diag['chief_examiner']['summary'] = request.POST.get('summary', diag['chief_examiner'].get('summary', ''))
                    diag['story_data']['story'] = request.POST.get('story', diag['story_data'].get('story', ''))
                    diag['panel_diagnosis']['subject_specialist']['conceptual_gap'] = request.POST.get('conceptual_gap', diag['panel_diagnosis']['subject_specialist'].get('conceptual_gap', ''))
                    diag['chief_examiner']['model_topper_answer']['definition'] = request.POST.get('ideal_answer', diag['chief_examiner']['model_topper_answer'].get('definition', ''))
                    diag['chief_examiner']['masterpiece_feedback']['why_this_score'] = request.POST.get('why_this_score', diag['chief_examiner']['masterpiece_feedback'].get('why_this_score', ''))
                    diag['chief_examiner']['treatment_plan']['teacher_action'] = request.POST.get('teacher_action', diag['chief_examiner']['treatment_plan'].get('teacher_action', ''))
                    diag['chief_examiner']['treatment_plan']['home_practice'] = request.POST.get('home_practice', diag['chief_examiner']['treatment_plan'].get('home_practice', ''))
                    diag['chief_examiner']['treatment_plan']['classroom_accommodation'] = request.POST.get('classroom_accommodation', diag['chief_examiner']['treatment_plan'].get('classroom_accommodation', ''))
                    
                    # Expert Scores
                    for k in ['concept', 'procedure', 'cognition', 'handwriting']:
                        try:
                            diag['expert_scores'][k] = float(request.POST.get(f'expert_{k}', diag['expert_scores'].get(k, 0)))
                        except (ValueError, TypeError):
                            diag['expert_scores'][k] = 0

                    attempt.teacher_score = score_val
                    attempt.teacher_feedback = teacher_feedback
                    attempt.reviewed_at = timezone.now()

                    if action == 'approve':
                        attempt.review_status = 'approved'
                    elif action == 'publish':
                        attempt.review_status = 'published'
                        attempt.score = score_val
                        attempt.outcome = 'CORRECT' if score_val >= (attempt.max_score * 0.6) else 'WRONG'
                        attempt.needs_review = False

                    diag['teacher_review_audit'] = audit_log
                    attempt.result_json = diag
                    attempt.save()

                    # Trophy refresh: recompute paper trophies for this (student, day, subject)
                    # after a publish score change. recompute_paper_trophy is idempotent:
                    #   same date -> noop | lower score -> cancel | higher score -> replace
                    try:
                        _q = getattr(attempt, "question", None)
                        _p = getattr(_q, "paper", None) if _q else None
                        _subject = getattr(_p, "subject", None) if _p else None
                        _day = getattr(attempt, "target_day_number", None)
                        if _subject and _day is not None:
                            from exams.services.trophy_service import recompute_subject_trophies
                            recompute_subject_trophies(
                                attempt.student, _day, _subject,
                                actor=request.user if request.user.is_authenticated else None,
                            )
                    except Exception:
                        import logging as _lg
                        _lg.getLogger(__name__).exception(
                            "trophy refresh after publish failed: attempt=%s", attempt.id
                        )

                    messages.success(request, f'Attempt {attempt.id} {action}ed successfully.')
                    return redirect('portal-teacher-review-queue')
            except ValueError:
                messages.error(request, 'Score must be a valid number.')

    return render(request, 'exams/portal_teacher_review_detail.html', {
        'attempt': attempt,
        'diag': diag,
        'max_marks': attempt.max_score or 2,
    })


@staff_member_required
def portal_teacher_review_bulk_action(request):
    """Bulk approve/publish from the queue."""
    if request.method == 'POST':
        attempt_ids = request.POST.getlist('attempt_ids')
        action = request.POST.get('bulk_action', '')
        if attempt_ids and action in ('approve', 'publish'):
            from exams.models import AttemptLog
            qs = AttemptLog.objects.filter(id__in=attempt_ids, needs_review=True)
            for attempt in qs:
                attempt.review_status = action
                attempt.reviewed_at = timezone.now()
                attempt.save()
            messages.success(request, f'{qs.count()} attempts marked as {action}.')
    return redirect('portal-teacher-review-queue')
