"""DB-touching shared view helpers for exams app.

Extracted from views.py 2026-11-09 (Handover V2 Phase 2, helper surgery).

Rationale:
    _current_student is used by 25 functions in views.py and by
    gem_view.py (via `from exams.views import _current_student`).
    Extracting portal_health (the last health function) requires it to
    live in a neutral module so views_health.py can import it without
    creating an import cycle:

        views.py -> views_health.py -> view_db_helpers.py
                                            ^ no back-edges

Design rules for this module:
    - DB-touching helpers ONLY. Pure functions belong in view_helpers.py.
    - Imports restricted to `django.*` and `.models` — no imports from
      .views, .views_*, or .view_helpers — this module cannot be part
      of an import cycle.
    - Add a helper only when at least TWO sibling modules need it.
      Single-consumer helpers stay local to their module.

Not to be confused with:
    - view_helpers.py — pure functions, zero DB imports (_is_teacher)
    - views_v3.py:90 — different _current_student(request) with a
      superuser fallback; that one is intentionally separate and must
      not be touched.
"""

from django.contrib import messages
from django.shortcuts import redirect
from django.http import Http404
from .models import PortalFeatureLog, Exam
from .view_helpers import _compute_pipeline_status, _student_enrolled_subjects, _SUBJECT_TO_PREFIX, _band
from .models import Student
from .view_helpers import _paper_from_book, STAGE_TO_TASK_TYPE  # used by _create_pipeline_task_for_stage


def _current_student(user):
    """Return the Student record linked to this user."""
    if not user or not user.is_authenticated:
        return None
    from exams.models import Student
    s = Student.objects.filter(student_user=user).first()
    if s:
        return s
    s = Student.objects.filter(code__iexact=user.username).first()
    if s:
        return s
    return None


def _gate_state(user, feature_key):
    """Effective state: DENY > ALLOW > DEFAULT (expired DENY ignored)."""
    from django.utils import timezone as _tz
    from exams.models import FeatureAccess
    fa = FeatureAccess.objects.filter(user=user, feature_key=feature_key).first()
    if fa is None:
        return "DEFAULT", None
    if fa.state == "DENY" and fa.expires_at and fa.expires_at < _tz.now():
        return "DEFAULT", fa
    return fa.state, fa


def _create_pipeline_task_for_stage(pipe, stage, actor=None, closer=None):
    """Canonical task creator for a pipeline's next stage.

    Turn 3e (2026-10-11). Idempotent. Only blocks on LIVE tasks
    (ASSIGNED/IN_PROGRESS with unassigned_at NULL). Silent on
    teacher stages (2, 4, 8, 9) and unknown stages.

    Task refs by stage:
      3, 5      -> _paper_from_book(pipe.paper_code)   e.g. "UR-9"
      6, 7      -> one per KC in the subject           e.g. "C9-UR01-HAMD"
      10        -> "C9-{SUBJ}00-GLOSSARY"
      11        -> "C9-{SUBJ}00-STORY"

    Standards: Rule 10 (one canonical writer per stage transition);
      Rule 25 (one task, one owner); Cooper Stage-Gate; AERA 2014 Std 1.0.
    """
    from exams.models import StudentTask, KnowledgeComponent

    tt = STAGE_TO_TASK_TYPE.get(stage)
    if not tt:
        return  # teacher stage or unknown

    assignee = closer or pipe.owner_student
    if assignee is None:
        return

    # Idempotence: only LIVE tasks block a fresh create
    if StudentTask.objects.filter(
            pipeline=pipe, pipeline_stage=stage,
            status__in=("ASSIGNED", "IN_PROGRESS"),
            unassigned_at__isnull=True).exists():
        return

    if stage in (3, 5):
        ref = _paper_from_book(pipe.paper_code)
        StudentTask.objects.create(
            student=assignee, task_type=tt, task_ref=ref,
            status="ASSIGNED", category="MANAGEMENT",
            pipeline=pipe, pipeline_stage=stage, assigned_by=actor,
        )
        return

    if stage in (6, 7):
        subj_code = pipe.paper_code.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(subj_code, "Mathematics")
        kcs = list(KnowledgeComponent.objects.filter(
            subject=subject, is_active=True).values_list("code", flat=True))
        if not kcs:
            kcs = list(KnowledgeComponent.objects.filter(
                is_active=True).values_list("code", flat=True))
        existing = set(StudentTask.objects.filter(
            pipeline=pipe, pipeline_stage=stage).values_list("task_ref", flat=True))
        for kc_code in [c for c in kcs if c not in existing]:
            StudentTask.objects.create(
                student=assignee, task_type=tt, task_ref=kc_code,
                status="ASSIGNED", category="MANAGEMENT",
                pipeline=pipe, pipeline_stage=stage, assigned_by=actor,
            )
        return

    if stage == 10:
        ref = "C9-" + pipe.paper_code.split("-")[0].upper() + "00-GLOSSARY"
    elif stage == 11:
        ref = "C9-" + pipe.paper_code.split("-")[0].upper() + "00-STORY"
    else:
        ref = _paper_from_book(pipe.paper_code)
    StudentTask.objects.create(
        student=assignee, task_type=tt, task_ref=ref,
        status="ASSIGNED", category="MANAGEMENT",
        pipeline=pipe, pipeline_stage=stage, assigned_by=actor,
    )


def _kc_subject_matches_student(kc_code, student):
    """Return (ok, reason). ok=True only if KC exists AND its subject
    is one the student is enrolled in. Fails safe (False) otherwise."""
    from exams.models import KnowledgeComponent as _KC
    kc = _KC.objects.filter(code=kc_code).first()
    if not kc:
        return False, "KC not found: " + str(kc_code)
    prefixes = _student_enrolled_subjects(student)
    if not prefixes:
        return False, ("student " + student.code
                       + " has no enrolled subjects "
                       + "(no BOOK_INGEST tasks, no Exam rows)")
    kc_prefix = _SUBJECT_TO_PREFIX.get(kc.subject or "", "")
    if not kc_prefix:
        return False, "KC subject not mapped: " + repr(kc.subject)
    if kc_prefix not in prefixes:
        return False, ("KC subject " + kc.subject + " (" + kc_prefix
                       + ") not in student enrolled subjects: "
                       + str(sorted(prefixes)))
    return True, ""


def _advance_pipeline(pipe, completed_stage, actor=None, closer=None):
    """Advance only when the CURRENT stage is fully done (Cooper Stage-Gate).

    Every return is logged (Section 3.6 / Rule 9 — no silent failures).
    Stage 4 auto-passes if Mizan approved stage 3 (Rule 12).
    Stage 6/7 refs resolve to the next pending KC code, not the book code.
    Stage 9 = terminal; status set to DONE.
    Stages 10, 11 are reachable.
    """
    from exams.models import StudentTask, KnowledgeComponent, PortalFeatureLog

    def _log(reason):
        try:
            PortalFeatureLog.objects.create(
                key="pipeline_advance." + pipe.paper_code,
                old_enabled=True, new_enabled=True,
                changed_by=actor,
                note="stage=" + str(completed_stage) + " " + reason,
            )
        except Exception:
            pass

    done = list(pipe.stages_completed or [])
    if completed_stage not in done:
        if not _stage_all_done(pipe, completed_stage):
            _log("bail: stage " + str(completed_stage) + " not all done")
            return
        done.append(int(completed_stage))
    # stage 2 (ingest to bank) auto-completes when stage 1 succeeds
    if 1 in done and 2 not in done:
        done.append(2)
    # stage 4 (KC list review): auto-passes when 3 is done (Mizan approved)
    if 3 in done and 4 not in done:
        done.append(4)
    done = sorted(set(done))
    pipe.stages_completed = done

    next_stage = None
    for s in range(1, 12):
        if s not in done:
            next_stage = s
            break

    if next_stage is None:
        pipe.status = "DONE"
        pipe.current_stage = 11
        pipe.save()
        _log("complete: pipeline DONE")
        return

    pipe.current_stage = next_stage
    # Turn 4 (2026-10-11): use canonical status computation.
    # Rule 10 - one writer for pipeline status.
    pipe.status = _compute_pipeline_status(pipe)
    pipe.save()

    assignee = closer or pipe.owner_student
    if assignee is None:
        _log("bail: no assignee")
        return

    tt = STAGE_TO_TASK_TYPE.get(next_stage)
    if not tt:
        _log("bail: no task type for stage " + str(next_stage))
        return

    # idempotence: skip only if a LIVE task exists at this stage.
    # SKIPPED or unassigned tasks must NOT block fresh creation.
    if StudentTask.objects.filter(
        pipeline=pipe, pipeline_stage=next_stage,
        status__in=["ASSIGNED", "IN_PROGRESS"],
        unassigned_at__isnull=True,
    ).exists():
        _log("bail: stage " + str(next_stage) + " live task exists")
        return

    # Resolve task_ref per stage
    if next_stage in (3, 5):
        # KC_DISCOVERY and KC_TAG: one per subject bank
        ref = _paper_from_book(pipe.paper_code)
        StudentTask.objects.create(
            student=assignee, task_type=tt, task_ref=ref,
            status="ASSIGNED", category="MANAGEMENT",
            pipeline=pipe, pipeline_stage=next_stage, assigned_by=actor,
        )
        _log("created stage " + str(next_stage) + " task ref=" + ref)
        return

    if next_stage in (6, 7):
        # KC_MISCONCEPTION and KC_SOCRATIC_LADDER: one per KC that
        # does not yet have content at this stage. Queue ALL pending
        # KCs so the stage closes in one pass (Cooper Stage-Gate).
        from exams.models import KnowledgeComponent
        kcs = list(KnowledgeComponent.objects.filter(
            subject=pipe.paper_code.split("-")[0].replace("MT","Mathematics")
                                                 .replace("PH","Physics")
                                                 .replace("CH","Chemistry")
                                                 .replace("BI","Biology")
                                                 .replace("IS","Islamiyat")
                                                 .replace("TQ","Tarjumatul Quran")
                                                 .replace("EN","English")
                                                 .replace("UR","Urdu")
                                                 .replace("CS","Computer Science")
                                                 or "Mathematics",
            is_active=True,
        ).values_list("code", flat=True))
        # Fallback: if no subject filter matched, use all active KCs
        if not kcs:
            kcs = list(KnowledgeComponent.objects.filter(
                is_active=True).values_list("code", flat=True))
        # Exclude KCs that already have a task at this stage
        existing = set(StudentTask.objects.filter(
            pipeline=pipe, pipeline_stage=next_stage).values_list(
            "task_ref", flat=True))
        pending = [c for c in kcs if c not in existing]
        if not pending:
            _log("bail: no pending KCs for stage " + str(next_stage))
            return
        for kc_code in pending:
            StudentTask.objects.create(
                student=assignee, task_type=tt, task_ref=kc_code,
                status="ASSIGNED", category="MANAGEMENT",
                pipeline=pipe, pipeline_stage=next_stage, assigned_by=actor,
            )
        _log("created " + str(len(pending)) + " stage " + str(next_stage)
             + " KC tasks")
        return

    # Stages 10, 11 (Turn 3a 2026-10-11): stage 10 (GLOSSARY) uses the
    # subject-aggregate KC code as ref, not the paper code. The writer
    # ingest_terms expects "C9-XX00-GLOSSARY", not "UR-9".
    # Stage 11 (STORY) stays as-is until Turn 3d.
    # Standards: Rule 10 (one canonical); Rule 25 (unit of work = KC);
    #   Cooper Stage-Gate (exit criteria tied to the unit); AERA 2014 Std 1.0.
    # Turn 4d (2026-10-11): stage 10 (GLOSSARY) and stage 11 (STORY)
    # both use subject-aggregate KC codes as ref, not the paper code.
    # Writers expect "C9-XX00-GLOSSARY" and "C9-XX00-STORY".
    # Standards: Rule 10 (one canonical); Rule 25 (unit of work = KC);
    #   Cooper Stage-Gate; AERA 2014 Std 1.0.
    if next_stage in (10, 11):
        _subj_prefix = pipe.paper_code.split("-")[0].upper()
        _suffix = "GLOSSARY" if next_stage == 10 else "STORY"
        ref = "C9-" + _subj_prefix + "00-" + _suffix
    else:
        ref = _paper_from_book(pipe.paper_code)
    StudentTask.objects.create(
        student=assignee, task_type=tt, task_ref=ref,
        status="ASSIGNED", category="MANAGEMENT",
        pipeline=pipe, pipeline_stage=next_stage, assigned_by=actor,
    )
    _log("created stage " + str(next_stage) + " task ref=" + ref)


def _stage_all_done(pipe, stage):
    """True if every StudentTask of this pipeline at this stage is DONE or SKIPPED.

    SKIPPED means either (a) a sibling completed it (shared queue), or
    (b) the teacher exempted it. Both are legitimate resolutions per
    Cooper Stage-Gate (gates must close) and ISO 21500 4.3.3 (sequence).
    """
    from exams.models import StudentTask
    qs = StudentTask.objects.filter(pipeline=pipe, pipeline_stage=stage)
    total = qs.count()
    if total == 0:
        return False
    resolved = qs.filter(status__in=["DONE", "SKIPPED"]).count()
    return resolved == total


def _teacher_assign(request):
    from exams.models import StudentTask, PortalFeature
    from django.db import transaction as _tx
    task_type = (request.POST.get("task_type") or "").strip()
    refs_raw = (request.POST.get("task_refs") or "").strip()
    students_raw = (request.POST.get("students") or "").strip()
    if not task_type or not refs_raw or not students_raw:
        messages.error(request, "Task assignment failed: missing task type, task refs, or students.")
        return redirect("portal-teacher-tasks")
    refs = [r.strip() for r in refs_raw.splitlines() if r.strip()]
    student_codes = [s.strip().upper() for s in students_raw.splitlines() if s.strip()]
    if len(set(refs)) < len(refs):
        messages.error(request, "Task assignment failed: duplicate task references detected.")
        return redirect("portal-teacher-tasks")
    students = list(Student.objects.filter(code__in=student_codes).order_by("code"))
    if not students:
        messages.error(request, f"Task assignment failed: no matching students found for codes {', '.join(student_codes)}.")
        return redirect("portal-teacher-tasks")
    feat = PortalFeature.objects.filter(key="student_tasks." + task_type).first()
    policy = feat.allocation_policy if feat else "EXCLUSIVE"
    if policy == "EXCLUSIVE":
        existing = set(StudentTask.objects.filter(task_type=task_type)
                       .values_list("task_ref", flat=True))
        refs = [r for r in refs if r not in existing]
    with _tx.atomic():
        n = 0
        for i, ref in enumerate(refs):
            s = students[i % len(students)]
            allowed, rsn = _filter_kc_refs_for_student([ref], s, task_type)
            if not allowed:
                PortalFeatureLog.objects.create(
                    key="task_assign_refused." + task_type,
                    old_enabled=True, new_enabled=False,
                    changed_by=request.user,
                    note=("refused " + ref + " for " + s.code + ": "
                          + (rsn[0][1] if rsn else "unknown")),
                )
                continue
            StudentTask.objects.create(
                student=s, task_type=task_type, task_ref=ref,
                status="ASSIGNED", assigned_by=request.user,
            )
            n += 1
    if n > 0:
        messages.success(request, f"{n} task(s) successfully assigned to {len(students)} student(s).")
    else:
        messages.warning(request, "No new tasks were assigned (all refs filtered or already assigned).")
    return redirect("portal-teacher-tasks")


def _get_subject_options():
    """Return all distinct subject names for the dropdown."""
    from exams.models import ModelPaper
    subs = ModelPaper.objects.values_list('subject', flat=True).distinct().order_by('subject')
    return [s for s in subs if s]


def _compute_question_assignments(target_date):
    """Return active QuestionAssignment rows for target_date with scope labels."""
    from exams.models_day_mission import QuestionAssignment
    qs = QuestionAssignment.objects.filter(date=target_date).select_related(
        'question', 'question__paper', 'target_student'
    ).order_by('-assigned_at')

    rows = []
    for qa in qs:
        if qa.target_student:
            scope = f'Student: {qa.target_student.code}'
            scope_short = qa.target_student.code
        elif qa.target_class and qa.target_shift:
            scope = f'Class {qa.target_class} · {qa.target_shift.title()}'
            scope_short = f'{qa.target_class}·{qa.target_shift}'
        elif qa.target_class:
            scope = f'Class {qa.target_class}'
            scope_short = qa.target_class
        elif qa.target_shift:
            scope = f'All {qa.target_shift.title()}'
            scope_short = qa.target_shift
        else:
            scope = 'All students'
            scope_short = 'ALL'

        rows.append({
            'id': qa.id,
            'scope_label': scope,
            'scope_short': scope_short,
            'subject': qa.subject,
            'position': qa.position,
            'question_id': qa.question.id,
            'question_text': (qa.question.question_text or '')[:100],
            'question_marks': float(qa.question.marks) if qa.question.marks else 0,
            'paper_code': qa.question.paper.code if qa.question.paper else '',
            'assigned_at': qa.assigned_at,
        })
    return rows


def _compute_effective_visibility(target_date, global_visibility):
    """Compute per-shift effective student counts with source attribution.

    Distinguishes:
      - shown_global     : global toggle is ON, no override
      - shown_override   : global is OFF, but override says True (exceptionally shown)
      - hidden_global    : global is OFF, no override (normal hidden state)
      - hidden_override  : global is ON, but override says False (exceptionally hidden)

    The "hidden by override" and "shown via override" counts should only be >0
    when actual exceptions exist.
    """
    from exams.models import Student
    from exams.models_day_mission import DailyCodeVisibility

    active_students = list(Student.objects.filter(
        is_active=True, student_class__startswith='9'
    ).values('id', 'student_class', 'shift'))

    overrides = list(DailyCodeVisibility.objects.filter(
        date=target_date
    ).values('target_student_id', 'target_class', 'target_shift',
             'morning_visible', 'evening_visible'))

    global_morning = bool(global_visibility and global_visibility.morning_visible)
    global_evening = bool(global_visibility and global_visibility.evening_visible)

    def _resolve_with_source(stu, shift_key):
        """Return (visible_bool, source) where source ∈ {'override', 'global'}."""
        s_id = stu['id']
        s_class = (stu.get('student_class') or '').strip()
        s_shift = (stu.get('shift') or '').strip().lower()

        # 1. Student-specific
        for o in overrides:
            if o['target_student_id'] == s_id and not o['target_class'] and not o['target_shift']:
                return bool(o[shift_key]), 'override'
        # 2. Class + Shift
        for o in overrides:
            if (not o['target_student_id'] and o['target_class'] == s_class
                and o['target_shift'] == s_shift):
                return bool(o[shift_key]), 'override'
        # 3. Class only
        for o in overrides:
            if (not o['target_student_id'] and o['target_class'] == s_class
                and not o['target_shift']):
                return bool(o[shift_key]), 'override'
        # 4. Shift only
        for o in overrides:
            if (not o['target_student_id'] and not o['target_class']
                and o['target_shift'] == s_shift):
                return bool(o[shift_key]), 'override'
        # 5. Global
        g = global_morning if shift_key == 'morning_visible' else global_evening
        return g, 'global'

    stats = {
        'morning_shown_global': 0, 'morning_shown_override': 0,
        'morning_hidden_global': 0, 'morning_hidden_override': 0,
        'evening_shown_global': 0, 'evening_shown_override': 0,
        'evening_hidden_global': 0, 'evening_hidden_override': 0,
        'total': len(active_students),
    }

    for stu in active_students:
        v, src = _resolve_with_source(stu, 'morning_visible')
        if v:
            stats['morning_shown_override' if src == 'override' else 'morning_shown_global'] += 1
        else:
            stats['morning_hidden_override' if src == 'override' else 'morning_hidden_global'] += 1

        v, src = _resolve_with_source(stu, 'evening_visible')
        if v:
            stats['evening_shown_override' if src == 'override' else 'evening_shown_global'] += 1
        else:
            stats['evening_hidden_override' if src == 'override' else 'evening_hidden_global'] += 1

    stats['morning_shown'] = stats['morning_shown_global'] + stats['morning_shown_override']
    stats['evening_shown'] = stats['evening_shown_global'] + stats['evening_shown_override']
    return stats


def _user_has_feature(user, feature_key):
    """True if the user should see/use the feature. Server-side only."""
    state, _ = _gate_state(user, feature_key)
    return state != "DENY"




# ---------------------------------------------------------------------------
# KC-subject guard (added 2026-10-08)
# Standards: NIST SP 800-53 SI-10 (reject invalid input);
#   Saltzer & Schroeder 1975 (fail-safe default = deny);
#   AERA/APA/NCME 2014 Std 1.0 (construct must match reported subject);
#   Rule 12 (Mizan must gate, not fall back); Rule 10 (one canonical source).
# ---------------------------------------------------------------------------


def _filter_kc_refs_for_student(refs, student, task_type):
    """Return (allowed, refusals). Guard applies ONLY to KC_MISCONCEPTION."""
    if task_type != "KC_MISCONCEPTION":
        return list(refs), []
    allowed, refusals = [], []
    for ref in refs:
        ok, reason = _kc_subject_matches_student(ref, student)
        if ok:
            allowed.append(ref)
        else:
            refusals.append((ref, reason))
    return allowed, refusals


def _is_student_user(user):
    return Student.objects.filter(student_user=user, is_active=True).exists()


def _reflection_stats(student):
    """SOLO-based reflection component (Section 9.7).

    Reported as a SEPARATE measure, not folded into overall_pct.
    Standards: AERA/APA/NCME 2014 Std 13.7 (name the construct);
    Guskey 2020 (composite grades must be transparent);
    MTSS/DBI (keep measures separate until weighting is validated).
    """
    from .models import StoryReflection, ReflectionScore
    scored = (StoryReflection.objects
              .filter(student=student, score__isnull=False)
              .select_related("score"))
    total = StoryReflection.objects.filter(student=student).count()
    n = scored.count()
    if not n:
        return {"scored": 0, "pending": total, "avg_solo": None,
                "pct": 0, "band_key": "low", "band_label": "Baqi",
                "band_icon": "x"}
    avg = sum(r.score.solo_level for r in scored) / n
    pct = round(avg / 4 * 100, 1)
    b = _band(pct)
    return {"scored": n, "pending": total - n, "avg_solo": round(avg, 2),
            "pct": pct, "band_key": b["key"], "band_label": b["label"],
            "band_icon": b["icon"]}


def _progress_for(student):
    exams = Exam.objects.filter(student=student).order_by("exam_date", "question_index")
    by_subject = {}
    by_day = {}
    total_score = 0
    total_max = 0
    for e in exams:
        sub = e.submissions.order_by("-created_at").first()
        if not sub or sub.ai_score is None:
            continue
        s = float(sub.ai_score)
        m = float(e.max_marks)
        total_score += s
        total_max += m
        by_subject.setdefault(e.subject, {"score": 0.0, "max": 0.0, "count": 0})
        by_subject[e.subject]["score"] += s
        by_subject[e.subject]["max"] += m
        by_subject[e.subject]["count"] += 1
        key = e.exam_date.isoformat()
        by_day.setdefault(key, {"score": 0.0, "max": 0.0, "count": 0})
        by_day[key]["score"] += s
        by_day[key]["max"] += m
        by_day[key]["count"] += 1
    subjects = []
    for name in sorted(by_subject):
        d = by_subject[name]
        pct = round(d["score"] / d["max"] * 100, 1) if d["max"] else 0
        b = _band(pct)
        subjects.append({"name": name, "count": d["count"], "avg": pct,
                         "band_key": b["key"], "band_label": b["label"], "band_icon": b["icon"]})
    days = []
    for key in sorted(by_day, reverse=True):
        d = by_day[key]
        days.append({"date": key, "count": d["count"],
                     "score": round(d["score"], 2), "max": round(d["max"], 2)})
    overall_pct = round(total_score / total_max * 100, 1) if total_max else 0
    return subjects, days, overall_pct
