from django.views.decorators.http import require_POST
"""V3 pipeline views. Clean, single-definition, markdown-safe."""
import json
import uuid
from django.urls import reverse
import logging

from django.shortcuts import render, redirect, get_object_or_404
from django.contrib.auth.decorators import login_required
from django.contrib import messages
from django.db.models import Sum
from django.utils import timezone
from exams.utils.pagination import paginate  # UI Rule L1

from exams.models import (
    Student, ModelQuestion, QuestionEditRequest, QuestionCorrectionRequest,
    EngineState, RPSItem, StudentQuestionLock, KnowledgeComponent,
    StoryHealRequest, CreditEvent, AttemptLog, Attendance, StudentNote,
)
from exams.models_delegation import TaskDelegation
from exams.services.daily_mission_engine import (
    get_student_books, get_daily_mission_questions, get_available_subjects,
)
from exams.services.book_pipeline import (
    get_all_books, get_all_book_states, get_book_state,
    get_bulk_skip_availability,
)
from exams.services.badge_awards import check_and_award_for_book
from exams.services import points_ledger
from exams.services.content_gaps import get_content_gaps, count_gaps_by_type
from exams.services.pipeline_state import (
    get_question_stage, get_mission_stage, get_stepper_data,
    get_skip_cost, get_bulk_skip_cost, SKIPPABLE, STAGES, STAGE_TITLES,
)

logger = logging.getLogger(__name__)


# ═══════════════════════════════════════════════════════════
# Helpers
# ═══════════════════════════════════════════════════════════



def _strip_mathml(text):
    """Replace raw MathML with readable [equation] placeholder."""
    if not text or '<math' not in text:
        return text
    import re as _re
    text = _re.sub(r'<math[^>]*>.*?</math>', '[equation]', text, flags=_re.DOTALL)
    text = _re.sub(r'<[^>]+>', '', text)
    return text.strip()


def _acc_for(student):
    """Return allowed class variants. Empty list = deny all."""
    if not student:
        return []
    _c = (student.student_class or '').strip().lower()
    from exams.utils_class import allowed_classes_for
    return allowed_classes_for(_c) or ([_c] if _c else [])

def _strip_md_fences(raw):
    """Strip ```json ... ``` or ``` ... ``` markdown fences ChatGPT adds."""
    raw = (raw or '').strip()
    if raw.startswith('```'):
        lines = raw.split('\n')
        if lines and lines[0].strip().startswith('```'):
            lines = lines[1:]
        if lines and lines[-1].strip().startswith('```'):
            lines = lines[:-1]
        raw = '\n'.join(lines).strip()
    return raw


def _build_heal_prompt(q):
    """Build story-heal prompt for a question's KC. Returns None on failure."""
    if not q or not getattr(q, 'kc', None):
        return None
    try:
        from exams.services.story_panel.prompt_builder import build_prompt
        prompt = build_prompt(q.kc)
        return prompt or None
    except Exception:
        logger.warning('_build_heal_prompt failed for Q%s', getattr(q, 'id', '?'), exc_info=True)
        return None


def _apply_fork_c_session_handoff(request, mission_data, actual_total,
                                   target_total, session_mission_day,
                                   effective_day, student):
    if 'mission_data' in request.session and request.session['mission_data']:
        return request.session['mission_data']
    if (not mission_data or actual_total < target_total
            or session_mission_day != effective_day):
        if effective_day > 0:
            mission_data = get_daily_mission_questions(
                student, pace_per_book=3, curriculum_day=effective_day)
        else:
            mission_data = {}
        request.session['mission_data'] = mission_data
        request.session['mission_day'] = effective_day
    return mission_data


def _current_balance(student):
    from exams.services.points_ledger import get_balance
    return get_balance(student)


def _current_student(request):
    student = Student.objects.filter(
        student_user=request.user, is_active=True).first()
    if not student and request.user.is_superuser:
        student = Student.objects.filter(is_active=True).first()
    return student


# ═══════════════════════════════════════════════════════════
# V3 main page
# ═══════════════════════════════════════════════════════════

def _required_content_for_stage(stage):
    """Return list of KC fields required for this stage."""
    if stage in ('STUDY', 'REMEDIATION'):
        return ['story']
    if stage == 'VERIFY':
        return ['misconceptions', 'socratic_ladder', 'key_terms']
    # ATTEMPT does not require any special KC content to proceed
    return []


def _check_stage_gaps(questions, stage):
    """Return list of {question, missing} for any content gaps."""
    required = _required_content_for_stage(stage)
    if not required:
        return []
    gaps = []
    for q in questions:
        kc = q.get('kc')
        if not kc:
            gaps.append({'question': q['obj'], 'missing': required + ['KC']})
            continue
        missing = [f for f in required if not getattr(kc, f, None)]
        if missing:
            gaps.append({'question': q['obj'], 'missing': missing})
    return gaps


@login_required
def portal_daily_mission_v3(request):
    from exams.models import StudentDailyCode
    from django.utils import timezone

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

    requested_stage = request.GET.get('stage', '').upper()
    _user_requested_stage = requested_stage  # Preserve explicit click before default fallback
    requested_book = request.GET.get('book', '').strip()

    from exams.models_day_mission import StudentDayMission as _SDM_V3
    
    # Calculate current day
    from exams.models import EngineState as _Eng_V3
    _eng_v3 = _Eng_V3.objects.filter(id=1).first()
    _cur_day_v3 = _eng_v3.get_current_day() if (_eng_v3 and _eng_v3.has_started) else 1
    
    # Read exclusively from the Master Register (SDM)
    from exams.models_day_mission import DailyCodeVisibility
    from exams.services.daily_code import SUBJECT_SESSION
    from datetime import timedelta
    
    _eng_dc_early = _Eng_V3.objects.filter(id=1).first()
    _target_dc_date_early = (_eng_dc_early.start_date + timedelta(days=_cur_day_v3 - 1)) if (_eng_dc_early and _eng_dc_early.start_date) else timezone.localdate()
    _vis_dc_early = DailyCodeVisibility.objects.filter(date=_target_dc_date_early).first()
    _morning_vis_early = getattr(_vis_dc_early, 'morning_visible', False) if _vis_dc_early else False
    _evening_vis_early = getattr(_vis_dc_early, 'evening_visible', False) if _vis_dc_early else False

    _sdm_rows = _SDM_V3.objects.filter(
        student=student, day_number=_cur_day_v3,
        question__paper__superseded_at__isnull=True,
    )

        
    _sdm_rows = _sdm_rows.select_related('question', 'question__paper').order_by('subject', 'position')


    all_question_objs = [row.question for row in _sdm_rows]
    no_locks = not all_question_objs

    # ── LAYER 5: Calendar fallback — rebuild StudentDayMission if empty for today ──
    import logging as _lg5
    try:
        from exams.models import EngineState as _Eng5
        from exams.models_day_mission import StudentDayMission as _SDM5
        _eng5 = _Eng5.objects.filter(id=1).first()
        _cur_day5 = _eng5.get_current_day() if (_eng5 and _eng5.has_started) else 1
        _session_base5 = request.session.get('mission_base_day', None)
        _session_override5 = request.session.get('mission_override', 0)
        if _session_base5 == _cur_day5 and _session_override5:
            _cur_day5 = _cur_day5 + _session_override5
        if all_question_objs and _cur_day5:
            _existing5 = _SDM5.objects.filter(student=student, day_number=_cur_day5).count()
            if False: # Layer 5 disabled to protect Master Register
                _created5 = 0
                # FIX (2026-11-10): Pre-fetch existing question IDs to respect
                # the unique_question_per_student constraint.
                _existing_qids5 = set(
                    _SDM5.objects.filter(student=student).values_list('question_id', flat=True)
                )
                # Compute positions per subject for new rows
                _subj_counts = {}
                for _lock5 in all_locks:
                    # Skip if this question was already assigned on a previous day
                    if _lock5.question_id in _existing_qids5:
                        continue
                        
                    _subj5 = _lock5.question.paper.subject if _lock5.question.paper else 'GEN'
                    _subj_counts[_subj5] = _subj_counts.get(_subj5, 0) + 1
                    _, _made5 = _SDM5.objects.get_or_create(
                        student=student, day_number=_cur_day5, question=_lock5.question,
                        defaults={'subject': _subj5, 'position': _subj_counts[_subj5]},
                    )
                    if _made5:
                        _created5 += 1
                        _existing_qids5.add(_lock5.question_id)
                if _created5:
                    _lg5.getLogger('idealogy.mission_calendar').info(
                        'MISSION_CALENDAR_REBUILT student=%s day=%d created=%d',
                        student.code, _cur_day5, _created5
                    )
    except Exception as _e5:
        _lg5.getLogger('idealogy.mission_calendar').error(
            'MISSION_CALENDAR_REBUILD_FAILED student=%s err=%s', student.code, _e5
        )

    # ── Per-book pipeline context ──
    # FIX (2026-11-10): show class-default subjects for no-locks students
    if no_locks:
        from exams.services.daily_mission_engine import get_student_books
        all_books = get_student_books(student)
    else:
        all_books = get_all_books(student)
    book_states = get_all_book_states(student)

    # ── Robust Session Persistence for Book Selection ──
    current_book = None
    
    # 1. Try to match the requested book (ignoring spaces and case)
    if requested_book:
        req_normalized = requested_book.lower().replace(' ', '')
        for b in all_books:
            if b.lower().replace(' ', '') == req_normalized:
                current_book = b
                break
                
    # 2. If no requested book (or it didn't match), fall back to session
    if not current_book:
        session_book = request.session.get('selected_book')
        if session_book:
            sess_normalized = session_book.lower().replace(' ', '')
            for b in all_books:
                if b.lower().replace(' ', '') == sess_normalized:
                    current_book = b
                    break
                    
    # 3. If still nothing, use the active state or first book
    if not current_book:
        if all_books:
            active_states = [b for b in book_states if b['status'] == 'active']
            if active_states:
                current_book = active_states[0]['book']
            else:
                incomplete_states = [b for b in book_states if b.get('status') != 'complete']
                current_book = incomplete_states[0]['book'] if incomplete_states else all_books[0]
            
    # 4. VALIDATE against today's SDM — pick a book that actually has questions
    from exams.models_day_mission import StudentDayMission as _SDM_check
    _sdm_subjects = set(
        _SDM_check.objects.filter(student=student, day_number=_cur_day_v3)
        .values_list('subject', flat=True)
    )
    _sdm_lower = {x.lower().strip() for x in _sdm_subjects}
    if current_book and current_book.lower().strip() not in _sdm_lower:
        # Respect explicit user choice (?book= or session).
        # Only auto-correct if the user has NO preference at all.
        _has_explicit_choice = bool(requested_book) or bool(request.session.get('selected_book'))
        if not _has_explicit_choice:
            for _b in all_books:
                if _b.lower().strip() in _sdm_lower:
                    current_book = _b
                    break
    if current_book and requested_book:
        request.session['selected_book'] = current_book
        request.session.modified = True

    current_book_state = None
    bulk_skip_stages = []
    if current_book:
        current_book_state = next(
            (b for b in book_states if b['book'] == current_book), None
        )
        bulk_skip_stages = get_bulk_skip_availability(student, current_book)
        
    # INDUSTRY STANDARD: Default to the current active stage if none requested
    if not requested_stage and current_book_state:
        requested_stage = current_book_state.get('current_stage', 'SELECT')

    # ── Effective day calculation (MUST be defined before use) ──
    engine = EngineState.objects.filter(id=1).first()
    try:
        base_day = engine.get_current_day() if engine and engine.has_started else 0
    except Exception:
        base_day = 0
    session_base = request.session.get('mission_base_day', None)
    override = request.session.get('mission_override', 0)
    if session_base != base_day:
        override = 0
        request.session['mission_base_day'] = base_day
        request.session['mission_override'] = 0
    effective_day = base_day + override


    # ── Questions scoped to current book AND effective day ──
    filtered_locks = _sdm_rows  # SDM is our single source of truth
    if current_book:
        filtered_locks = filtered_locks.filter(
            question__paper__subject=current_book
        )
    
    # FIX: Include today's questions AND in-progress carryover from ANY day.
    # Only completed (SAFAR) questions from past days are hidden.
    # When user explicitly requests a stage, skip day filter entirely (review mode).
    if not (_user_requested_stage and _user_requested_stage not in ('', 'SELECT')):
        if effective_day and effective_day >= 1:
            from exams.models_day_mission import StudentDayMission
            # If user is viewing a different day than current, re-fetch SDM for that day
            if effective_day != _cur_day_v3:
                _target_dc_date_refetch = (_eng_dc_early.start_date + timedelta(days=effective_day - 1)) if (_eng_dc_early and _eng_dc_early.start_date) else timezone.localdate()
                _vis_dc_refetch = DailyCodeVisibility.objects.filter(date=_target_dc_date_refetch).first()
                _morning_vis_refetch = getattr(_vis_dc_refetch, 'morning_visible', False) if _vis_dc_refetch else False
                _evening_vis_refetch = getattr(_vis_dc_refetch, 'evening_visible', False) if _vis_dc_refetch else False

                _sdm_rows = StudentDayMission.objects.filter(
                    student=student, day_number=effective_day,
                    question__paper__superseded_at__isnull=True,
                )

                    
                _sdm_rows = _sdm_rows.select_related('question', 'question__paper').order_by('subject', 'position')
                filtered_locks = _sdm_rows
                all_question_objs = [row.question for row in _sdm_rows]
            day_qids = set(StudentDayMission.objects.filter(
                student=student, day_number=effective_day,
                question__paper__superseded_at__isnull=True,
            ).values_list('question_id', flat=True))

            # Strictly use StudentDayMission. No carryover from previous days.
            if day_qids:
                filtered_locks = filtered_locks.filter(question_id__in=day_qids)
            else:
                filtered_locks = filtered_locks.none()
        else:
            filtered_locks = filtered_locks.none()
            
    question_objs = [lock.question for lock in filtered_locks]

    # Compute content gaps for contribution hub (needs question_objs to be defined first)
    content_gaps = []
    content_gap_counts = {}
    if current_book:
        content_gaps = get_content_gaps(student, current_book, question_objs, limit=5)
        content_gap_counts = count_gaps_by_type(content_gaps)

    # (Effective day logic moved above)

    questions = []
    from exams.services.pipeline_state import award_safar_points

    # ── BULK FETCH TO PREVENT N+1 QUERIES ──
    kc_codes = [q.kc_code for q in question_objs if q.kc_code]
    rps_map = {r.kc_code: r for r in RPSItem.objects.filter(student=student, kc_code__in=kc_codes)}

    notes_bulk = StudentNote.objects.filter(student=student)
    note_map = {}
    for n in notes_bulk:
        key = f"{n.subject}_{n.q_number}"
        if key not in note_map:  # Get the latest
            note_map[key] = n

    for idx, q in enumerate(question_objs):
        if q.question_text and '<math' in q.question_text:
            q.question_text = _strip_mathml(q.question_text)
        state = get_question_stage(student, q)

        if state['current_stage'] == 'SAFAR':
            try:
                award_safar_points(student, q)
            except Exception:
                pass
        
        rps = rps_map.get(q.kc_code)
        heal_prompt = _build_heal_prompt(q) if (q.kc and not q.kc.story) else None
        
        _subject_name = q.paper.subject if q.paper and q.paper.subject else 'GEN'
        _q_num = str(q.question_index)
        _student_note = note_map.get(f"{_subject_name}_{_q_num}")
        questions.append({
            'obj': q,
            'index': idx,
            'subject': q.paper.subject if q.paper else '',
            'kc': q.kc,
            'rps': rps,
            'stage': state['current_stage'],
            'locked_reason': state['locked_reason'],
            'latest_attempt': state['latest_attempt'],
            'skippable': state.get('skippable', False),
            'heal_prompt': heal_prompt,
            'has_heal_prompt': bool(heal_prompt),
            'student_note': _student_note,
            'skip_cost': get_skip_cost(state['current_stage']),
        })

    if question_objs:
        # FIX: Only calculate the aggregate stage based on the questions
        # actually shown to the student on this page. Otherwise, hidden
        # questions from past/future days drag the stepper back to ATTEMPT.
        pace = student.daily_question_count or 1
        visible_qs = question_objs[:pace]
        mission_state = get_mission_stage(student, visible_qs)
    else:
        mission_state = {'aggregate_stage': 'SELECT', 'counts': {}, 'total': 0}
    stepper = get_stepper_data(mission_state, current_book, requested_stage=requested_stage)

    explicit_select = (requested_stage == 'SELECT')
    stage = requested_stage or mission_state['aggregate_stage']

    # ── INDUSTRY STANDARD FIX: Filter questions by requested stage ──
    # If the user clicked a specific stage in the stepper, only show those questions.
    if _user_requested_stage and requested_stage not in ('', 'SELECT') and requested_stage in STAGES:
        _req_idx = STAGES.index(_user_requested_stage)
        _filtered = []
        for q in questions:
            _q_stage = q.get('stage', 'SELECT')
            if _q_stage in STAGES:
                _q_idx = STAGES.index(_q_stage)
                if _q_idx >= _req_idx:
                    q['review_mode'] = (_q_idx > _req_idx)
                    _filtered.append(q)
        questions = _filtered[:200]  # defensive cap (batch 3AB)
    # ── CONTENT PREPARATION GATE (BYPASSED FOR UX) ──
    # if _user_requested_stage in ('STUDY', 'REMEDIATION', 'ATTEMPT', 'VERIFY'):
    # _gaps = _check_stage_gaps(questions, _user_requested_stage)
    # if _gaps:
    # return redirect(
    #     f"/api/portal/prepare-stage/?stage={_user_requested_stage}&book={(current_book or '')}"
    # )
    # ──────────────────────────────


    # xAPI-aligned auto-detect: if today's mission is fully SAFAR,
    # stamp the completion ledger (bounded cost: one day, ~16 questions).
    if effective_day and effective_day >= 1:
        try:
            from exams.services.day_completion import maybe_complete_day
            maybe_complete_day(student, effective_day)
        except Exception:
            pass

    # ── FETCH TEST CODES FOR THE EFFECTIVE DAY ──
    from datetime import timedelta
    from exams.models_day_mission import DailyCodeVisibility
    
    _eng_dc = EngineState.objects.filter(id=1).first()
    if _eng_dc and _eng_dc.start_date and effective_day:
        _target_dc_date = _eng_dc.start_date + timedelta(days=effective_day - 1)
    else:
        _target_dc_date = timezone.localdate()
        
    today_code = StudentDailyCode.objects.filter(student=student, date=_target_dc_date).first()
    
    # CRITICAL: Only show if teacher explicitly published it
    _vis_dc = DailyCodeVisibility.objects.filter(date=_target_dc_date, target_student=student).first()
    if not _vis_dc:
        _s_class = (student.student_class or '').strip()
        _vis_dc = DailyCodeVisibility.objects.filter(date=_target_dc_date, target_class=_s_class).first()
    if not _vis_dc:
        _vis_dc = DailyCodeVisibility.objects.filter(date=_target_dc_date, target_student__isnull=True, target_class='').first()

    if not _vis_dc:
        today_code = None
    else:
        if today_code and today_code.per_book_codes:
            if not getattr(_vis_dc, 'morning_visible', False):
                today_code.per_book_codes.pop('morning', None)
            if not getattr(_vis_dc, 'evening_visible', False):
                today_code.per_book_codes.pop('evening', None)
            if not today_code.per_book_codes.get('morning') and not today_code.per_book_codes.get('evening'):
                today_code = None
    if today_code and today_code.per_book_codes:
        # per_book_codes is {'morning': {...}, 'morning_order': [...], 'evening': {...}, ...}
        pass 
    else:
        today_code = None

    # ── FETCH UNREAD NOTIFICATIONS (1-hour expiry) ──
    from exams.models import StudentNotification
    from django.utils import timezone as _tz_now
    _notifs = StudentNotification.objects.filter(
        student=student,
        is_read=False,
        expires_at__gt=_tz_now.now(),
    ).order_by('-created_at')[:3]

    _guide_ctx = {
        "title": "Aaj Ka Mission (V3)",
        "purpose": "Yeh aap ke rozana ke sawalat ka naya page hai.",
        "value": "Yahan aap apne din ke tamam sawalat, test codes, aur progress dekh sakte hain.",
        "how_to": "Har sawal ke saath 'Study & Notes', 'Pro Learning', aur 'Upload' options milte hain. Pro Learning step-by-step samjhaata hai.",
        "controls": "Book selector se subject badlein. Test Codes teacher set karte hain — rozana check karein.",
    }
    return render(request, 'exams/portal_daily_mission_v3.html', {
        'guide': _guide_ctx,
        'unread_notifications': _notifs,
        'today_code': today_code,
        'student': student,
        'questions': questions,
        'effective_day': effective_day,
        'stepper': stepper if isinstance(stepper, list) else [],
        'no_locks': no_locks,
        'explicit_select': explicit_select,
        'current_stage': stage,
        'aggregate_stage': mission_state['aggregate_stage'],
        'counts': mission_state['counts'],
        'total': len(question_objs),
        'subject_filter': current_book or '',
        'available_subjects': all_books,
        'points_balance': _current_balance(student),
        'mission_override': request.session.get('mission_override', 0),
        # ── NEW per-book pipeline ──
        'books': all_books if isinstance(all_books, list) else [],
        'book_states': book_states if isinstance(book_states, list) else [],
        'current_book': current_book,
        'current_book_state': current_book_state,
        'requested_stage': requested_stage,
        'bulk_skip_stages': bulk_skip_stages if isinstance(bulk_skip_stages, list) else [],
        'content_gaps': content_gaps if isinstance(content_gaps, list) else [],
        'content_gap_counts': content_gap_counts,
    })


def _queue_question_correction(student, question, field_name, proposed_value, reason):
    """Create one validated correction request; return a result code."""
    if field_name not in dict(QuestionCorrectionRequest.FIELD_CHOICES):
        return 'invalid_field'
    proposed_value = (proposed_value or '').strip()
    reason = (reason or '').strip()
    if not proposed_value or not reason:
        return 'missing_data'
    if QuestionCorrectionRequest.objects.filter(
        question=question, student=student, field_name=field_name, status='PENDING'
    ).exists():
        return 'duplicate'
    if QuestionCorrectionRequest.objects.filter(
        student=student, status='PENDING'
    ).count() >= 10:
        return 'limit'
    current = getattr(question, field_name, '') or ''
    if str(current).strip() == proposed_value:
        return 'unchanged'
    QuestionCorrectionRequest.objects.create(
        question=question, student=student, field_name=field_name,
        current_value=str(current), proposed_value=proposed_value, reason=reason,
    )
    return 'created'


@login_required
def portal_edit_question_v3(request, qid):
    if request.user.is_superuser:
        from exams.models import ModelPaper as _MP_su
        _allowed_classes = list(_MP_su.objects.values_list('student_class', flat=True).distinct())
    else:
        _allowed_classes = _acc_for(_current_student(request))

    if request.method == 'POST':
        student = _current_student(request)
        if not student:
            return redirect('portal-dashboard')

        # Preserve the existing question access restrictions.
        if request.user.is_superuser:
            q = get_object_or_404(
                ModelQuestion, id=qid, paper__student_class__in=_allowed_classes
            )
        else:
            from django.db.models import Q as _Q
            _std = (
                ~_Q(paper__code__startswith='SELF-')
                & ~_Q(paper__code__startswith='CUSTOM-')
                & _Q(paper__student_class__in=_allowed_classes)
            )
            _own_self = _Q(paper__code__startswith=f'SELF-{student.code}')
            _own_custom = _Q(paper__code__startswith=f'CUSTOM-{student.code}')
            q = get_object_or_404(ModelQuestion.objects.filter(
                _std | _own_self | _own_custom
            ), id=qid)

        new_text = (request.POST.get('question_text') or '').strip()
        new_ans = (request.POST.get('model_answer') or '').strip()

        # Content Gaps submits model_answer only; the full editor requires confirmation.
        if new_text and not request.POST.get('confirm_edit'):
            messages.error(request, 'You must tick the confirmation box.')
        elif not new_text and not new_ans:
            messages.error(request, 'Please provide a question or model-answer correction.')
        else:
            reason = (request.POST.get('reason') or
                      'Student requested a correction using the question editor.').strip()
            results = []
            if new_text and new_text != q.question_text:
                results.append(_queue_question_correction(
                    student, q, 'question_text', new_text, reason
                ))
            if new_ans and new_ans != q.model_answer:
                results.append(_queue_question_correction(
                    student, q, 'model_answer', new_ans, reason
                ))

            created = results.count('created')
            if created:
                messages.success(request, f'{created} correction(s) sent to the teacher for review.')
            elif results and all(x == 'unchanged' for x in results):
                messages.info(request, 'No changes detected; submitted values match the current content.')
            elif 'limit' in results:
                messages.error(request, 'You already have 10 pending correction requests. Please wait for teacher review.')
            elif 'duplicate' in results:
                messages.warning(request, 'A correction request for one or more fields is already pending.')
            else:
                messages.info(request, 'There were no new corrections to submit.')

    from django.utils.http import url_has_allowed_host_and_scheme
    referer = request.META.get('HTTP_REFERER', '')
    if referer and url_has_allowed_host_and_scheme(
        referer, allowed_hosts={request.get_host()}, require_https=request.is_secure()
    ):
        return redirect(referer)
    return redirect('portal-daily-mission-v3')

@login_required
def heal_story_v3(request, kc_code):
    if request.method != 'POST':
        return redirect('portal-daily-mission-v3')
    student = _current_student(request)
    if not student:
        return redirect('portal-dashboard')
    kc = get_object_or_404(KnowledgeComponent, code=kc_code)
    raw = _strip_md_fences(request.POST.get('story_json', ''))
    try:
        
        data = json.loads(raw)

        story = data.get('story')
        if isinstance(story, str):
            story = [p.strip() for p in story.split('\n\n') if p.strip()]
        if not isinstance(story, list) or not story:
            raise ValueError('story must be a non-empty list or string')
    except Exception as e:
        messages.error(request, f'Invalid JSON: {e}')
        return redirect('portal-daily-mission-v3')
    from django.db import transaction as _tx4
    with _tx4.atomic():
        StoryHealRequest.objects.create(student=student, kc=kc, new_story=story)
        from hashlib import sha256 as _sha256
        _story_hash = _sha256('\n'.join(story).encode()).hexdigest()
        points_ledger.award(
            student=student, points=1,
            reason=f'Self-healed story for {kc.code}',
            code='STORY_HEAL',
            evidence={'kc_code': kc.code, 'story_hash': _story_hash},
            source='AUTO',
        )
    _bal = _current_balance(student)
    messages.success(request, f'Story for {kc.code} submitted. +1 point earned (balance: {_bal}).')
    return redirect('portal-daily-mission-v3')


@login_required
def teacher_approve_edits(request):
    if not (request.user.is_staff or request.user.is_superuser):
        return redirect('portal-dashboard')

    from exams.models import ModelQuestion, Student, StudentQuestionLock, EngineState
    from exams.models_day_mission import StudentDayMission

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

        # Handle Custom New Questions
        if new_q_id and action in ['approve', 'reject']:
            q = get_object_or_404(ModelQuestion, id=new_q_id)
            if action == 'approve':
                q.needs_teacher_review = False
                q.save(update_fields=['needs_teacher_review'])

                # Parse student code from paper code (SELF-{code}-{uuid})
                try:
                    student_code = q.paper.code.replace('SELF-', '').rsplit('-', 1)[0]
                    student = Student.objects.filter(code=student_code, is_active=True).first()
                    if student:
                        StudentQuestionLock.objects.get_or_create(student=student, question=q, defaults={'is_active': True})
                        engine = EngineState.objects.filter(id=1).first()
                        current_day = engine.get_current_day() if engine and engine.has_started else 1
                        StudentDayMission.objects.get_or_create(
                            student=student, day_number=current_day, question=q, defaults={'subject': q.paper.subject}
                        )
                except Exception:
                    pass

                messages.success(request, 'Approved new custom question and added to student mission.')
            else:
                q.delete()
                messages.warning(request, 'Rejected and deleted custom question.')
            return redirect('teacher-approve-edits')

        return redirect('teacher-approve-edits')

    pending_new_qs = ModelQuestion.objects.filter(
        needs_teacher_review=True,
        paper__code__startswith='SELF-'
    ).select_related('paper')
    page_obj = paginate(request, pending_new_qs)
    pending_new_qs = page_obj.object_list

    return render(
        request,
        'exams/teacher_approve_edits.html',
        {'pending_new_qs': pending_new_qs, 'page_obj': page_obj}
    )

@login_required
def teacher_approve_stories(request):
    if not (request.user.is_staff or request.user.is_superuser):
        return redirect('portal-dashboard')
    if request.method == 'POST':
        pending = StoryHealRequest.objects.filter(status='PENDING')
        count = pending.count()
        for req_obj in pending:
            kc = req_obj.kc
            kc.story = req_obj.new_story
            kc.story_status = 'PANEL_PASSED'
            kc.save()
            req_obj.status = 'APPROVED'
            req_obj.save()
        messages.success(request, f'Approved {count} stories.')
        return redirect('teacher-approve-stories')
    stories = StoryHealRequest.objects.filter(status='PENDING').select_related('kc', 'student')
    page_obj = paginate(request, stories)
    stories = page_obj.object_list
    return render(request, 'exams/teacher_approve_stories.html', {'stories': stories, 'page_obj': page_obj})


# ═══════════════════════════════════════════════════════════
# Discipline / attendance
# ═══════════════════════════════════════════════════════════

@login_required
def discipline_dashboard(request):
    student = _current_student(request)
    if not student:
        return redirect('portal-dashboard')
    balance = _current_balance(student)
    records = Attendance.objects.filter(student=student).exclude(state='PRESENT').order_by('-date')[:30]
    return render(request, 'exams/discipline_dashboard.html', {
        'student': student, 'balance': balance, 'records': records,
    })


@login_required
def redeem_attendance(request, attendance_id):
    if request.method != 'POST':
        return redirect('discipline-dashboard')
    student = _current_student(request)
    if not student:
        return redirect('portal-dashboard')
    att = get_object_or_404(Attendance, id=attendance_id, student=student)
    if att.state not in ('LATE', 'ABSENT'):
        messages.error(request, 'Only LATE or ABSENT can be excused.')
        return redirect('discipline-dashboard')
    balance = _current_balance(student)
    if balance < 1:
        messages.error(request, 'Need 1 point to redeem.')
        return redirect('discipline-dashboard')
    points_ledger.penalize(
        student=student, points=1,
        reason=f'Redeemed {att.state} on {att.date}',
        code='ATTENDANCE_REDEEM',
        evidence={'attendance_id': att.id},
        source='AUTO',
    )
    att.state = 'EXCUSED'
    att.reason = (att.reason + ' | Redeemed with points').strip(' |')
    att.save()
    messages.success(request, f'{att.date} excused.')
    return redirect('discipline-dashboard')


# ═══════════════════════════════════════════════════════════
# Pipeline actions
# ═══════════════════════════════════════════════════════════

@login_required
def auto_assign_v3(request):
    from exams.models import Student, EngineState, StudentQuestionLock
    student = Student.objects.filter(student_user=request.user, is_active=True).first()
    if not student and request.user.is_superuser:
        student = Student.objects.filter(is_active=True).first()
    if not student:
        return redirect('portal-dashboard')

    books = get_student_books(student)
    if not books:
        books = get_available_subjects()

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

    mission = get_daily_mission_questions(student, curriculum_day=day)

    created, total = 0, 0
    for book, qids in mission.items():
        for qid in qids:
            total += 1
            _, made = StudentQuestionLock.objects.get_or_create(
                student=student, question_id=qid,
                defaults={'is_active': True},
            )
            if made:
                created += 1

    request.session['mission_data'] = mission
    request.session['mission_day'] = day

    if total == 0:
        messages.error(request, 'No questions available. Ask teacher to add questions.')
    else:
        messages.success(request, f'{created} new questions assigned, {total} in mission.')
    return redirect('portal-daily-mission-v3')


@login_required
def skip_stage_view(request, qid, stage):
    from exams.services.stage_controls import skip_stage
    from exams.services.points_ledger import get_balance
    if request.user.is_superuser:
        from exams.models import ModelPaper as _MP_su
        _allowed_classes = list(_MP_su.objects.values_list('student_class', flat=True).distinct())
    else:
        _allowed_classes = _acc_for(_current_student(request))
    if request.method != 'POST':
        return redirect('portal-daily-mission-v3')
    student = _current_student(request)
    if not student:
        return redirect('portal-dashboard')
    # IDOR FIX: require student's own active lock
    from exams.models import StudentQuestionLock as _SQL_skip
    if not request.user.is_superuser:
        if not _SQL_skip.objects.filter(student=student, question_id=qid, is_active=True).exists():
            messages.error(request, 'Question not assigned to you.')
            return redirect('portal-daily-mission-v3')
    question = get_object_or_404(ModelQuestion, id=qid, paper__student_class__in=_allowed_classes)
    if not request.user.is_superuser and question is not None and question.paper:
        _pc_guard = question.paper.code or ''
        if _pc_guard.startswith(('SELF-', 'CUSTOM-')):
            _me_guard = _current_student(request)
            if not _me_guard or not (_pc_guard.startswith(f'SELF-{_me_guard.code}') or _pc_guard.startswith(f'CUSTOM-{_me_guard.code}')):
                from django.http import Http404
                raise Http404('Not found')
    try:
        skip_stage(student, question, stage.upper())
        _cost = get_skip_cost(stage.upper())
        messages.success(request, f'Skipped {stage}. -{_cost} points (balance: {get_balance(student)}).')

        # Award SAFAR completion points
        from exams.services.pipeline_state import get_question_stage, award_safar_points
        if get_question_stage(student, question)['current_stage'] == 'SAFAR':
            if award_safar_points(student, question):
                messages.success(request, '🎉 Question Complete! +5 points awarded.')
    except ValueError as e:
        messages.error(request, str(e))
        return redirect(f'/api/portal/daily-mission-v3/?stage={stage.upper()}')
    try:
        book = question.paper.subject if question.paper else None
        if book:
            check_and_award_for_book(student, book)
    except Exception:
        pass
    return redirect(f'/api/portal/daily-mission-v3/?stage={stage.upper()}')


@login_required
def request_ungate_view(request, qid, stage):
    from exams.services.stage_controls import request_ungate
    if request.user.is_superuser:
        from exams.models import ModelPaper as _MP_su
        _allowed_classes = list(_MP_su.objects.values_list('student_class', flat=True).distinct())
    else:
        _allowed_classes = _acc_for(_current_student(request))
    if request.method != 'POST':
        return redirect('portal-daily-mission-v3')
    student = _current_student(request)
    if not student:
        return redirect('portal-dashboard')
    # IDOR FIX: require own lock if qid provided
    if qid and not request.user.is_superuser:
        from exams.models import StudentQuestionLock as _SQL_ug
        if not _SQL_ug.objects.filter(student=student, question_id=qid, is_active=True).exists():
            messages.error(request, 'Question not assigned to you.')
            return redirect('portal-daily-mission-v3')
    question = get_object_or_404(ModelQuestion, id=qid, paper__student_class__in=_allowed_classes) if qid else None
    if not request.user.is_superuser and question is not None and question.paper:
        _pc_guard = question.paper.code or ''
        if _pc_guard.startswith(('SELF-', 'CUSTOM-')):
            _me_guard = _current_student(request)
            if not _me_guard or not (_pc_guard.startswith(f'SELF-{_me_guard.code}') or _pc_guard.startswith(f'CUSTOM-{_me_guard.code}')):
                from django.http import Http404
                raise Http404('Not found')
    note = request.POST.get('note', '').strip()
    request_ungate(student, stage.upper(), question=question, note=note)
    title = STAGE_TITLES.get(stage.upper(), stage)
    messages.success(request, f'Ungate request sent for {title}. Teacher will review.')
    return redirect('portal-daily-mission-v3')


@login_required
def submit_daily_code_view(request, qid):
    from exams.services.daily_code import verify_code
    if request.user.is_superuser:
        from exams.models import ModelPaper as _MP_su
        _allowed_classes = list(_MP_su.objects.values_list('student_class', flat=True).distinct())
    else:
        _allowed_classes = _acc_for(_current_student(request))
    if request.method != 'POST':
        return redirect('portal-daily-mission-v3')
    student = _current_student(request)
    if not student:
        return redirect('portal-dashboard')

    # ── UPLOAD KEY GATE (teacher must grant QUESTION_UPLOAD or PAPER_UPLOAD) ──
    from exams.models_delegation import TaskDelegation
    from django.utils import timezone as _tz_now
    has_active_upload_key = TaskDelegation.objects.filter(
        assignee=request.user,
        task_type__in=['QUESTION_UPLOAD', 'PAPER_UPLOAD'],
        expires_at__gt=_tz_now.now(),
    ).exists()
    if not (has_active_upload_key or request.user.is_staff or request.user.is_superuser):
        messages.error(request, '🔑 Upload key nahi hai. Teacher se request karein.')
        return redirect('portal-exam-token-status')

    # IDOR FIX: scope qid to standard + own SELF-/CUSTOM-
    if not request.user.is_superuser:
        from django.db.models import Q as _Q
        _allowed = ModelQuestion.objects.filter(
            (~_Q(paper__code__startswith='SELF-') & ~_Q(paper__code__startswith='CUSTOM-'))
            | _Q(paper__code__startswith=f'SELF-{student.code}')
            | _Q(paper__code__startswith=f'CUSTOM-{student.code}')
        )
        question = get_object_or_404(_allowed, id=qid)
    else:
        from exams.models import ModelPaper as _MP_su
        _allowed_classes = list(_MP_su.objects.values_list('student_class', flat=True).distinct())
        question = get_object_or_404(ModelQuestion, id=qid, paper__student_class__in=_allowed_classes)
        if not request.user.is_superuser and question is not None and question.paper:
            _pc_guard = question.paper.code or ''
            if _pc_guard.startswith(('SELF-', 'CUSTOM-')):
                _me_guard = _current_student(request)
                if not _me_guard or not (_pc_guard.startswith(f'SELF-{_me_guard.code}') or _pc_guard.startswith(f'CUSTOM-{_me_guard.code}')):
                    from django.http import Http404
                    raise Http404('Not found')
    subject = question.paper.subject if question.paper else ''
    submitted = request.POST.get('daily_code', '').strip()
    _valid, _msg = verify_code(student, subject, submitted)
    if _valid:
        request.session[f'code_ok_{qid}'] = True
        messages.success(request, 'Code verified.')
    else:
        messages.error(request, f'Invalid code: {_msg}')
    return redirect('portal-daily-mission-v3')





def recalculate_subject_trophies(student, day, subject):
    """DEPRECATED shim — delegates to exams.services.trophy_service."""
    from exams.services.trophy_service import recompute_subject_trophies
    return recompute_subject_trophies(student, day, subject)


def upload_physical_test(request, qid):


    from exams.services.daily_code import verify_code, parse_code
    from exams.models_delegation import TaskDelegation
    from exams.services import exam_queue as _eq
    from django.utils import timezone as _tz_now
    from django.contrib import messages
    from exams.models import ModelQuestion, AttemptLog, RPSItem, StudentQuestionLock
    from pathlib import Path as _Path

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

    # ENFORCE MASTER REGISTER: Check if this qid is assigned to the student today
    from exams.models_day_mission import StudentDayMission
    from exams.models import EngineState
    _eng = EngineState.objects.filter(id=1).first()
    _today_day = _eng.get_current_day() if (_eng and _eng.has_started) else 1

    # Allow uploads of questions from ANY day the student has SDM for.
    # This enables past-day retakes (e.g., Aiman retaking Day 1 Biology on Day 13).
    # The retake gate below enforces 24h cooldown + teacher approval per question.
    is_assigned = StudentDayMission.objects.filter(
        student=student, question_id=qid
    ).exists()

    if not is_assigned and not (request.user.is_staff or request.user.is_superuser):
        messages.error(request, 'Yeh sawal aap ke kisi bhi mission mein shamil nahi hai.')
        return redirect('portal-upload-center')

    # ── SHIFT LOCK GATE: Block GET if the shift is locked ──
    if not (request.user.is_staff or request.user.is_superuser):
        _gate_sdm_get = StudentDayMission.objects.filter(student=student, question_id=qid).first()
        if _gate_sdm_get:
            from exams.models_day_mission import DailyCodeVisibility
            from exams.services.daily_code import SUBJECT_SESSION
            from datetime import timedelta
            _eng_get = EngineState.objects.filter(id=1).first()
            _target_date_get = (_eng_get.start_date + timedelta(days=_gate_sdm_get.day_number - 1)) if (_eng_get and _eng_get.start_date) else timezone.localdate()
            
            _vis_get = DailyCodeVisibility.objects.filter(date=_target_date_get, target_student=student).first()
            if not _vis_get:
                _s_class_get = (student.student_class or '').strip()
                _vis_get = DailyCodeVisibility.objects.filter(date=_target_date_get, target_class=_s_class_get).first()
            if not _vis_get:
                _vis_get = DailyCodeVisibility.objects.filter(date=_target_date_get, target_student__isnull=True, target_class='').first()
            
            if _vis_get:
                _sess_get = SUBJECT_SESSION.get(_gate_sdm_get.subject, 'morning')
                _is_vis_get = False
                if _sess_get == 'morning':
                    _is_vis_get = getattr(_vis_get, 'morning_visible', False)
                else:
                    _is_vis_get = getattr(_vis_get, 'evening_visible', False)
                
                if not _is_vis_get:
                    messages.error(request, f'The {_sess_get.capitalize()} shift is currently locked by the teacher.')
                    return redirect('portal-upload-center')

    # ── RETAKE GATE: Global Policy + Per-subject Approval ──
    if not (request.user.is_staff or request.user.is_superuser):
        from exams.models import RetakeRequest
        from exams.models_day_mission import DayAttemptPolicy as _DayPolicy
        
        _today = _tz_now.localdate()
        
        # Identify which SDM day this question belongs to (may be a past day)
        _gate_sdm = StudentDayMission.objects.filter(
            student=student, question_id=qid
        ).order_by('-day_number').first()
        _gate_day = _gate_sdm.day_number if _gate_sdm else _today_day
        _gate_subject = (_gate_sdm.subject if _gate_sdm else '') or ''

        # ENFORCE PUBLICATION: Block upload if the paper is globally unpublished (superseded)
        _gate_paper = getattr(getattr(_gate_sdm, 'question', None), 'paper', None) if _gate_sdm else None
        if _gate_paper is not None and _gate_paper.superseded_at is not None:
            messages.error(request, 'This paper is no longer available for uploads.')
            return redirect('portal-upload-center')

        # ENFORCE SHIFT VISIBILITY (with student overrides)
        if _gate_sdm and not (request.user.is_staff or request.user.is_superuser):
            from exams.models_day_mission import DailyCodeVisibility
            from exams.services.daily_code import SUBJECT_SESSION
            from datetime import timedelta
            
            _eng_shift = EngineState.objects.filter(id=1).first()
            _shift_target_date = (_eng_shift.start_date + timedelta(days=_gate_sdm.day_number - 1)) if (_eng_shift and _eng_shift.start_date) else timezone.localdate()
            _sess = SUBJECT_SESSION.get(_gate_subject, 'morning')
            # 11/12 UPLOAD OVERRIDE: English is a morning subject for 11/12 ONLY
            if _gate_subject == 'English':
                _cls_up = (student.student_class or '').strip().lower()
                if _cls_up.startswith('11') or _cls_up.startswith('12'):
                    _sess = 'morning'
            
            _vis = DailyCodeVisibility.objects.filter(date=_shift_target_date, target_student=student).first()
            if not _vis:
                _s_class = (student.student_class or '').strip()
                _vis = DailyCodeVisibility.objects.filter(date=_shift_target_date, target_class=_s_class).first()
            if not _vis:
                _vis = DailyCodeVisibility.objects.filter(date=_shift_target_date, target_student__isnull=True, target_class='').first()
                
            _is_vis = False
            if _vis:
                if _sess == 'morning':
                    _is_vis = _vis.morning_visible
                else:
                    _is_vis = _vis.evening_visible
                    
            if not _is_vis:
                messages.error(request, f'The {_sess.capitalize()} shift is currently locked by the teacher.')
                return redirect('portal-upload-center')

        # ENFORCE SHIFT VISIBILITY: Block upload if the subject's shift is hidden
        if _gate_sdm and not (request.user.is_staff or request.user.is_superuser):
            from exams.models_day_mission import DailyCodeVisibility
            from exams.services.daily_code import SUBJECT_SESSION
            from datetime import timedelta
            
            _eng_shift = EngineState.objects.filter(id=1).first()
            _shift_target_date = (_eng_shift.start_date + timedelta(days=_gate_sdm.day_number - 1)) if (_eng_shift and _eng_shift.start_date) else timezone.localdate()
            _shift_vis = DailyCodeVisibility.objects.filter(date=_shift_target_date).first()
            _morning_vis = getattr(_shift_vis, 'morning_visible', False) if _shift_vis else False
            _evening_vis = getattr(_shift_vis, 'evening_visible', False) if _shift_vis else False
            
            _sess = SUBJECT_SESSION.get(_gate_subject, 'morning')
            if _sess == 'morning' and not _morning_vis:
                messages.error(request, 'The Morning shift is currently locked by the teacher.')
                return redirect('portal-upload-center')
            if _sess == 'evening' and not _evening_vis:
                messages.error(request, 'The Evening shift is currently locked by the teacher.')
                return redirect('portal-upload-center')


        # ── FRAUD CANCELLATION GUARD (D3, added 2026-11-16) ──
        from exams.models import FraudCancellation
        from django.db.models import Q
        from django.http import HttpResponseForbidden

        _fraud_blocked = FraudCancellation.objects.filter(student=student, is_reversed=False).filter(
            Q(day_from__lte=_gate_day, day_to__gte=_gate_day)
        ).filter(
            Q(subject_filter='') | Q(subject_filter=_gate_subject)
        ).exists()

        if _fraud_blocked:
            return HttpResponseForbidden("Aap ka ye paper fraud review mein hai. Behas ke liye apne teacher se rabta karein.")
        # ──────────────────────────────────────────────────────
        
        # Approved retake request for this exact (day, subject)
        _retake_req = RetakeRequest.objects.filter(
            student=student,
            day_number=_gate_day,
            subject=_gate_subject,
            status='APPROVED',
        ).order_by('-processed_at').first()
        
        # Active IN_PROGRESS token (teacher called them today)
        from exams.models import ExamToken as _ExamToken
        _has_token = _ExamToken.objects.filter(
            student=student, date=_today, status='IN_PROGRESS',
            uses_remaining__gt=0,
        ).exists()
        
        _policy = _DayPolicy.objects.filter(date=_today).first()
        _policy_ok = bool(_policy) and _policy.status in ('OPEN', 'PAST_REATTEMPT')
        
        # Allow if approved retake OR active token OR policy open
        if not (_policy_ok or _retake_req or _has_token):
            messages.error(request, 'Retakes for today are disabled by the teacher.')
            return redirect('portal-upload-center')
        
        _penalty = float(_policy.late_penalty_pct) if _policy else 10.0
        
        _max_allowed = (1 + _retake_req.attempts_granted) if _retake_req else 1

        # Past-day upload with no approved request → block immediately
        if _gate_day != _today_day and not _retake_req:
            messages.error(
                request,
                f'Day {_gate_day} ka sawal hai (aaj Day {_today_day} hai). '
                f'Purane din ke sawal ke liye "Request Retake" button dabayein aur '
                f'teacher ki approval ka intezar karein.'
            )
            return redirect('portal-upload-center')

        # Count current physical attempts for this SDM day
        _current_count = AttemptLog.objects.filter(
            student=student, question_id=qid, is_physical=True,
            target_day_number=_gate_day, cancelled_at__isnull=True,
        ).count()

        if _current_count >= _max_allowed:
            if _retake_req:
                messages.error(
                    request,
                    f'Aap ne {_current_count} attempts use kar liye hain (max {_max_allowed}). '
                    f'Aur retake ke liye dobara "Request Retake" karein.'
                )
            else:
                messages.error(
                    request,
                    'Is sawal ka aap ne pehle attempt kar diya hai. '
                    'Dubara upload karne ke liye "Request Retake" button dabayein.'
                )
            return redirect('portal-upload-center')

    _dels = TaskDelegation.objects.filter(
        assignee=request.user,
        task_type__in=['QUESTION_UPLOAD', 'PAPER_UPLOAD'],
        expires_at__gt=_tz_now.now(),
        uses_remaining__gt=0,
    )
    # Prioritize CHOICE key if student has both Individual and Choice active
    _del = _dels.filter(delegation_mode='CHOICE').first() or _dels.first()
    has_active_upload_key = _del is not None
    is_choice_test = _del is not None and getattr(_del, 'delegation_mode', None) == 'CHOICE'
    
    if not (has_active_upload_key or request.user.is_staff or request.user.is_superuser):
        messages.error(request, '🔑 Upload key nahi hai. Teacher se request karein.')
        return redirect('portal-exam-token-status')

    gate_token = None
    if not (request.user.is_staff or request.user.is_superuser):
        gate_allowed, gate_token, gate_reason = _eq.check_anti_cheat_gate(student)
        if not gate_allowed:
            messages.error(request, f'🎫 {gate_reason}')
            return redirect('portal-exam-token-status')

    if not request.user.is_superuser:
        from django.db.models import Q as _Q
        _cls = (student.student_class or '').strip().lower()
        from exams.utils_class import allowed_classes_for
        _allowed_classes = allowed_classes_for(_cls) or ([_cls] if _cls else [])
        
        _allowed = ModelQuestion.objects.filter(
            (_Q(paper__student_class__in=_allowed_classes) & ~_Q(paper__code__startswith='SELF-') & ~_Q(paper__code__startswith='CUSTOM-'))
            | _Q(paper__code__startswith=f'SELF-{student.code}')
            | _Q(paper__code__startswith=f'CUSTOM-{student.code}')
        )
        question = get_object_or_404(_allowed, id=qid)
    else:
        from exams.models import ModelPaper as _MP_su
        _allowed_classes = list(_MP_su.objects.values_list('student_class', flat=True).distinct())
        question = get_object_or_404(ModelQuestion, id=qid, paper__student_class__in=_allowed_classes)
        if not request.user.is_superuser and question is not None and question.paper:
            _pc_guard = question.paper.code or ''
            if _pc_guard.startswith(('SELF-', 'CUSTOM-')):
                _me_guard = _current_student(request)
                if not _me_guard or not (_pc_guard.startswith(f'SELF-{_me_guard.code}') or _pc_guard.startswith(f'CUSTOM-{_me_guard.code}')):
                    from django.http import Http404
                    raise Http404('Not found')

    subject = question.paper.subject if question.paper else ''
    code_verified = 'validated_upload_code' in request.session
    
    if request.method == 'POST':
        daily_code = request.POST.get('daily_code', '').strip()
        if not daily_code:
            daily_code = request.session.pop('validated_upload_code', '')
        code_verified = bool(daily_code)

        # PHASE 4b-3: Policy gate FIRST
        from exams.services.attempt_policy import resolve_attempt_context as _rac
        _ctx = _rac(student, question)
        if _ctx['error']:
            messages.error(request, f'❌ {_ctx["error"]}')
            return redirect(f'/api/portal/upload-physical/{qid}/')
        # ALWAYS enforce SDM membership (choice-mode bypass closed).
        # Own SELF-/CUSTOM- papers are still allowed (may not be materialized
        # to SDM yet — student just wrote them).
        _gate_day = _ctx.get('target_day')
        if _gate_day is None:
            from exams.models import EngineState as _ES_gate
            _eg = _ES_gate.objects.filter(id=1).first()
            _gate_day = _eg.get_current_day() if (_eg and _eg.has_started) else 1
        from exams.models_day_mission import StudentDayMission as _SDM_gate
        _is_in_sdm = _SDM_gate.objects.filter(
            student=student, day_number=_gate_day, question=question
        ).exists()
        _paper_code = (question.paper.code if question.paper else '') or ''
        _is_own_custom = (
            _paper_code.startswith(f'SELF-{student.code}')
            or _paper_code.startswith(f'CUSTOM-{student.code}')
        )
        if not (_is_in_sdm or _is_own_custom):
            messages.error(request, f'❌ This question is not in Day {_gate_day} mission. Please use the Upload Center.')
            return redirect('portal-upload-center')



        # PHASE 9: Code-existence gate (compulsory — teacher must set codes first)
        from exams.models import StudentDailyCode as _SDC9, EngineState as _ES9
        from datetime import timedelta as _td9
        _eng9 = _ES9.objects.filter(id=1).first()
        if _eng9 and _eng9.start_date and _ctx['target_day']:
            _target_date9 = _eng9.start_date + _td9(days=_ctx['target_day'] - 1)
            _day_codes9 = _SDC9.objects.filter(student=student, date=_target_date9).first()
            _has_codes9 = bool(_day_codes9 and (
                (_day_codes9.per_book_codes or {}).get('morning') or
                (_day_codes9.per_book_codes or {}).get('evening')
            ))
            if not _has_codes9:
                # AUTO-GENERATE: Never block the student. Generate codes on the fly.
                from exams.management.commands.assign_daily_codes import build_per_book_codes, ALL_SUBJECTS
                import random as _rand_auto
                _pace = student.daily_question_count or 1
                _subj_codes = {subj: _rand_auto.randint(1, _pace) for subj in ALL_SUBJECTS}
                _pbc = build_per_book_codes(student, _subj_codes)
                if not _day_codes9:
                    _day_codes9 = _SDC9.objects.create(
                        student=student, date=_target_date9,
                        code=_rand_auto.randint(1, _pace), per_book_codes=_pbc
                    )
                else:
                    if not (_day_codes9.per_book_codes or {}).get('morning') and not (_day_codes9.per_book_codes or {}).get('evening'):
                        _day_codes9.per_book_codes = _pbc
                        _day_codes9.save(update_fields=['per_book_codes'])
                _has_codes9 = True

            # PHASE 10: Visibility gate — scoped resolution (most specific wins)
            from exams.models_day_mission import DailyCodeVisibility as _DCV10

            # Scope resolution helper (mirrors retake policy order)
            def _resolve_code_visibility(date, student):
                s_class = (student.student_class or '').strip()
                s_shift = (student.shift or '').strip().lower()
                # 1. Student
                v = _DCV10.objects.filter(date=date, target_student=student).first()
                if v: return v, 'student'
                # 2. Class+Shift
                if s_class and s_shift:
                    v = _DCV10.objects.filter(date=date, target_student__isnull=True, target_class=s_class, target_shift=s_shift).first()
                    if v: return v, 'class_shift'
                # 3. Class
                if s_class:
                    v = _DCV10.objects.filter(date=date, target_student__isnull=True, target_class=s_class, target_shift='').first()
                    if v: return v, 'class'
                # 4. Shift
                if s_shift:
                    v = _DCV10.objects.filter(date=date, target_student__isnull=True, target_class='', target_shift=s_shift).first()
                    if v: return v, 'shift'
                # 5. Global
                v = _DCV10.objects.filter(date=date, target_student__isnull=True, target_class='', target_shift='').first()
                return v, 'global' if v else None

            _vis10, _vis_scope = _resolve_code_visibility(_target_date9, student)
            _is_per_student_override = (_vis_scope == 'student')

            if not _vis10:
                messages.error(request, f'🔒 Day {_ctx["target_day"]} codes are hidden by your teacher.')
                return redirect(f'/api/portal/upload-physical/{qid}/')

            # Shift gate ONLY applies when using global visibility
            if not _is_per_student_override:
                BOOK_ABBR_GATE = {'Urdu': 'UR', 'English': 'EN', 'Islamiyat': 'IS', 'Mathematics': 'MA', 'Chemistry': 'CH', 'Physics': 'PH', 'Tarjumatul Quran': 'TQ', 'Computer Science': 'CS', 'Biology': 'BI', 'Bio': 'BI', 'Computer': 'CS'}
                _abbr_g = BOOK_ABBR_GATE.get(subject)
                _is_morn_g = _abbr_g in ['PH', 'CH', 'BI', 'TQ', 'CS']
                _is_eve_g = _abbr_g in ['MA', 'EN', 'UR', 'IS']
                _m_vis_g = getattr(_vis10, 'morning_visible', _vis10.is_visible)
                _e_vis_g = getattr(_vis10, 'evening_visible', _vis10.is_visible)
                if (_is_morn_g and not _m_vis_g) or (_is_eve_g and not _e_vis_g):
                    messages.error(request, f'🔒 {subject} codes for Day {_ctx["target_day"]} are hidden by your teacher.')
                    return redirect(f'/api/portal/upload-physical/{qid}/')

        from exams.models import EngineState as _ES_cur
        _eng_cur = _ES_cur.objects.filter(id=1).first()
        _cur_day = _eng_cur.get_current_day() if (_eng_cur and _eng_cur.has_started) else 1
        _is_current_day = (_ctx['target_day'] is None or _ctx['target_day'] == _cur_day)

        if False and not is_choice_test and _is_current_day:  # DISABLED Cmd 163
            from exams.services.daily_code import verify_code_with_session as _vcs
            _valid, _err = _vcs(student, subject, daily_code)
            if not _valid:
                messages.error(request, f'❌ {_err}')
                return redirect(f'/api/portal/upload-physical/{qid}/')

            expected_pos = parse_code(daily_code)
            if expected_pos is not None:
                from exams.models_day_mission import StudentDayMission
                from exams.models import EngineState
                e = EngineState.objects.filter(id=1).first()
                d = e.get_current_day() if (e and e.has_started) else 1
                mission = StudentDayMission.objects.filter(student=student, day_number=d, subject=subject, position=expected_pos).first()
                if mission and mission.question.id != question.id:
                    messages.error(request, f'❌ Code {daily_code} is for a different question. Please use the Upload Center.')
                    return redirect(f'/api/portal/upload-physical/{qid}/')

        payload = request.POST.get('payload', '').strip()
        if not payload:
            messages.error(request, 'Paste the JSON first.')
            return redirect(f'/api/portal/upload-physical/{qid}/')

        story_payload = request.POST.get('story_payload', '').strip()
        if not story_payload:
            messages.error(request, 'Story JSON paste karein.')
            return redirect(f'/api/portal/upload-physical/{qid}/')

        try:
            from exams.parsing import extract_json as _extract_story
            _story_data = _extract_story(story_payload)
            if 'story' not in _story_data or len(_story_data['story']) < 50:
                raise ValueError('Story text missing or too short.')
        except Exception as _e:
            messages.error(request, f'Story JSON Error: {_e}')
            return redirect(f'/api/portal/upload-physical/{qid}/')

        try:
            from exams.parsing import extract_json
            data = extract_json(payload)

            # Validate that the AI did not get cut off
            if 'students' not in data or not data['students']:
                raise ValueError("AI response was cut off. Please generate again.")
            if 'chief_examiner' not in data['students'][0]:
                raise ValueError("AI response was cut off before generating the Chief Examiner. Please generate again.")
        except Exception as e:
            import logging as _lg
            _lg.getLogger('exams.upload').error(
                "UPLOAD JSON FAIL student=%s qid=%s err=%s payload=%r",
                student.code if student else '?', qid, str(e), payload[:1500]
            )
            messages.error(request, f'Invalid JSON: {e}')
            return redirect(f'/api/portal/upload-physical/{qid}/')

        warnings = data.get('warnings', [])
        
        # ── SECRET SPY CROSS-VERIFICATION (The Trap) ──
        try:
            # 1. Extract the main Grading Score (from grading prompt JSON)
            _student_data = data['students'][0]
            _grading_score = 0.0
            if 'questions' in _student_data and len(_student_data['questions']) > 0:
                _grading_score = float(_student_data['questions'][0].get('score', 0))
            elif 'score' in _student_data:
                _grading_score = float(_student_data.get('score', 0))

            # 2. Extract the Secret Story Score (from story prompt JSON)
            _spy_score = None
            _spy_key = request.session.get('spy_key', 'spy_score')
            if _spy_key in _story_data:
                _spy_score = float(_story_data[_spy_key])
            elif 'spy_score' in _story_data: # Fallback for old sessions
                _spy_score = float(_story_data['spy_score'])

            # 3. PHASE 3: Compare on 5-stage scale (apples to apples)
            _real_max = float(question.marks or 2) or 2.0
            _grading_stages = int(round((float(_grading_score) / _real_max) * 5)) if _real_max else 0
            if _spy_score is not None:
                _spy_stages = int(_spy_score)
                if _grading_stages != _spy_stages:
                    warnings.append(f"Stage mismatch: grader={_grading_stages}/5, spy={_spy_stages}/5. Flagged for teacher review.")
                    print(f"[SPY WARN] Stages differ: grader={_grading_stages} spy={_spy_stages}")
                else:
                    print(f"[SPY OK] Stages match: {_grading_stages}/5")
            else:
                print("[SPY WARNING] Story JSON did not contain 'spy_score'.")
                
        except Exception as _spy_err:
            print(f"[SPY WARNING] Could not cross-verify scores: {_spy_err}")

        # Ensure is_tampered is defined
        if 'is_tampered' not in locals():
            is_tampered = False


        # ANTI-FALSE-ALARM: We only flag if image is genuinely missing.
        # No more canary checks. No more blocking students for AI glitches.
        # Policy: notify the teacher, never roadblock the student.
        # PHASE 3: Images come from external AI (never browser file upload).
        # Trust AI's security_gatekeeper report instead of the file check.
        is_tampered = False
        try:
            _gate = (data.get('students', [{}])[0].get('security_gatekeeper') or {})
        except Exception:
            _gate = {}
        if _gate.get('image_provided') is False:
            warnings.append("Security Notice: External AI reported no image. Teacher review recommended.")

        # Notify teacher via message instead of blocking student
        if is_tampered:
            messages.warning(request, '⚠️ Teacher Notice: Image missing. Grading continues — teacher will verify.')

        try:
            student_data = data['students'][0]
            
            # ── Support BOTH old and new JSON schemas ──
            _has_flat_chief = isinstance(student_data.get('chief_examiner'), dict) and bool(student_data.get('chief_examiner'))
            if not _has_flat_chief and 'questions' in student_data and isinstance(student_data['questions'], list) and len(student_data['questions']) > 0:
                q_data = student_data['questions'][0]
                ai_score = float(q_data.get('score', 0))
                ai_max = float(q_data.get('max_marks', 5))
                band = q_data.get('band', 'Wrong')
                ocr_text = q_data.get('student_answer_transcribed', '')
                panel = q_data.get('panel_diagnosis', {})
                chief = q_data.get('chief_examiner', {})
                summary = panel.get('summary', '')
                root_cause = panel.get('root_cause', '')
                echo_q = chief.get('graded_question_text', '')
            else:
                # NEW 5-EXPERT SCHEMA (flat)
                q_data = {} 
                chief = student_data.get('chief_examiner', {})
                panel = student_data.get('panel_diagnosis', {})
                ai_score = float(chief.get('final_score', 0))
                ai_max = float(question.marks or 2)
                band = chief.get('band', 'Wrong')
                ocr_text = student_data.get('student_answer_transcribed', 'Uploaded via AI Panel')
                summary = chief.get('summary', '')
                root_cause = panel.get('subject_specialist', {}).get('conceptual_gap', '')
                echo_q = chief.get('graded_question_text', '')

            # ── PHASE 3b: EXTRACT 5-STAGE LADDER ──
            _stages_passed = None
            _stages_raw = student_data.get('stages_passed') if isinstance(student_data, dict) else None
            if _stages_raw is None and isinstance(chief, dict):
                _stages_raw = chief.get('stages_passed')
            try:
                _stages_passed = int(_stages_raw) if _stages_raw is not None else None
                if _stages_passed is not None:
                    _stages_passed = max(0, min(5, _stages_passed))
            except (ValueError, TypeError):
                _stages_passed = None

            # ── SECURITY CHECK: Verify the question wasn't altered ──
            if not is_tampered:
                real_q = (question.question_text or '').strip()
                if echo_q and real_q:
                    import re
                    clean_echo = re.sub(r'[^a-zA-Z0-9]', '', echo_q.lower())
                    clean_real = re.sub(r'[^a-zA-Z0-9]', '', real_q.lower())
                    if clean_echo and clean_real:
                        # If they share less than 80% of the string sequence, it's a fake prompt
                        if clean_real not in clean_echo and clean_echo not in clean_real and len(clean_real) > 10:
                            is_tampered = True
                            summary = '⚠️ SECURITY ALERT: QUESTION ALTERED IN PROMPT. ' + str(summary)


            # ══════════════════════════════════════════════════════
            # DATA SANITIZER (Fail-safe for empty AI fields)
            # ══════════════════════════════════════════════════════
            real_model_answer = (question.model_answer or "Please refer to the textbook for the correct answer.").strip()
            
            # ── SCRIPT TRANSLITERATION GUARD ──
            # Rule: Nastaliq → Roman Urdu. English stays English.
            from exams.parsing import romanize_urdu as _romanize, has_arabic_script as _has_arabic
            
            # Transliterate student answer if in Nastaliq
            _stud_ans = student_data.get('student_answer_transcribed') or ''
            if _has_arabic(_stud_ans):
                student_data['student_answer_transcribed'] = _romanize(_stud_ans)
            
            # Transliterate AI ideal answer if in Nastaliq
            _ideal = chief.get('ideal_answer') or ''
            if _has_arabic(_ideal):
                chief['ideal_answer'] = _romanize(_ideal)
            
            # Also transliterate real_model_answer if the question is Urdu
            if _has_arabic(real_model_answer):
                real_model_answer = _romanize(real_model_answer)

            

            # 1. Ensure Ideal Answer is not empty
            if not chief.get('ideal_answer') or chief['ideal_answer'] in ['...', 'N/A', '']:
                chief['ideal_answer'] = real_model_answer

            # 2. Ensure Topper Answers exist
            if not chief.get('topper_answers') or len(chief['topper_answers']) == 0:
                chief['topper_answers'] = [{
                    'technique': 'Technique A: Model Answer',
                    'answer_text': real_model_answer,
                    'why_it_scores': 'This directly answers the prompt using the expected terminology.'
                }]

            # 3. Ensure Missing Points exist
            if not chief.get('three_missing_points') or len(chief['three_missing_points']) == 0:
                chief['three_missing_points'] = ["Review the core concepts of this topic carefully."]

            # 4. Ensure Expert Suggestions exist
            if not chief.get('expert_suggestions') or len(chief['expert_suggestions']) == 0:
                chief['expert_suggestions'] = [
                    "Read the question carefully before answering.",
                    "Use the exact keywords from the textbook.",
                    "Structure your answer with a clear conclusion.",
                    "Practice writing this answer from memory.",
                    "Review the model answer provided."
                ]

            # 5. Ensure Treatment Plan exists
            if not chief.get('treatment_plan'):
                chief['treatment_plan'] = {}
            tp = chief['treatment_plan']
            if not tp.get('teacher_action') or tp['teacher_action'] in ['...', 'N/A']: tp['teacher_action'] = "Re-teach the core concept of this topic."
            if not tp.get('home_practice') or tp['home_practice'] in ['...', 'N/A']: tp['home_practice'] = "Read the relevant chapter and make notes."
            if not tp.get('classroom_accommodation') or tp['classroom_accommodation'] in ['...', 'N/A']: tp['classroom_accommodation'] = "Provide a keyword sheet for exam preparation."

            # 6. Ensure Match Reason exists
            if not chief.get('match_failure_reason'):
                chief['match_failure_reason'] = "The answer does not match the question."

            # ══════════════════════════════════════════════════════
            # RELEVANCE GATEKEEPER (Highest Priority)
            # If the AI determines the answer doesn't match the question,
            # we force score to 0 regardless of what the AI said.
            # ══════════════════════════════════════════════════════
            _is_match = chief.get('is_match', True)
            if _is_match is False or str(_is_match).lower() == 'false':
                _match_reason = chief.get('match_failure_reason', 'Answer does not address the question asked.')
                ai_score = 0
                band = 'Wrong'
                summary = f"⚠️ RELEVANCE FAILURE: {_match_reason}"
                root_cause = f"Student answered about a completely different topic. {_match_reason}"
                # 🔑 CRITICAL: Override chief dict so template + saved JSON see the change
                chief['band'] = 'Wrong'
                chief['summary'] = summary
                chief['final_score'] = 0
                chief['is_match'] = False
                # Override panel diagnosis
                if isinstance(panel, dict):
                    _spec = panel.get('subject_specialist') or {}
                    _spec['score'] = 0
                    _spec['conceptual_gap'] = _match_reason
                    panel['subject_specialist'] = _spec
                # Zero all expert scores (no merit for wrong answer)
                student_data['expert_scores'] = {
                    'concept': 0, 'procedure': 0, 'cognition': 0,
                    'handwriting': 0, 'skeptic': 0
                }

            # Force max_score to match the database
            real_max = float(question.marks or 2)
            # ── PHASE 3b: PREFER 5-STAGE LADDER when AI provided stages_passed ──
            if _stages_passed is not None:
                _ladder_bands = ['Wrong', 'Poor', 'Below Average', 'Fair', 'Good', 'Excellent']
                band = _ladder_bands[_stages_passed]
                score = round((_stages_passed / 5.0) * real_max, 2)
            elif ai_max > 0:
                if str(band).lower() in ('wrong', 'poor', 'below average'):
                    score = 0
                else:
                    score = round((ai_score / ai_max) * real_max, 2)
            else:
                score = 0
            max_score = real_max

            # PHASE 4b-2: Apply late penalty if this is a PAST_REATTEMPT window
            _original_score = score
            if _ctx['is_late'] and _ctx['policy']:
                _pen_pct = float(_ctx['policy'].late_penalty_pct)
                score = round(score * (1.0 - _pen_pct / 100.0), 2)

            outcome_map = {'excellent': 'CORRECT', 'good': 'CORRECT', 'fair': 'PARTIAL', 'average': 'PARTIAL', 'below average': 'WRONG', 'poor': 'WRONG', 'wrong': 'WRONG', 'not attempted': 'WRONG'}
            outcome = outcome_map.get(str(band).lower(), 'WRONG')

            _needs_review = False
            if is_tampered:
                # FIX: Do not flag as tampered if the AI itself said the image was missing
                _summary_lower = str(summary).lower()
                if 'missing' in _summary_lower or 'blank' in _summary_lower or 'no image' in _summary_lower:
                    is_tampered = False
                    _needs_review = True
                    summary = "Image missing. Pending teacher review." 
                else:
                    summary = '⚠️ SECURITY ALERT: PROMPT TAMPERED. ' + str(summary)
                    root_cause = '⚠️ SECURITY ALERT: PROMPT TAMPERED. ' + str(root_cause)

            # ── SANITIZE CHIEF: Ensure all template-required fields exist ──
            if isinstance(chief, dict):
                if not chief.get('parent_friendly_summary'):
                    chief['parent_friendly_summary'] = chief.get('summary', '') or ''
                if 'graded_question_text' not in chief:
                    chief['graded_question_text'] = question.question_text or ''
                if 'match_failure_reason' not in chief:
                    chief['match_failure_reason'] = ''
                if 'band_urdu' not in chief:
                    _BU = {'Excellent': 'Behtareen', 'Good': 'Acha', 'Fair': 'Darmiyana', 'Poor': 'Kamzor', 'Wrong': 'Ghalat'}
                    chief['band_urdu'] = _BU.get(chief.get('band', 'Wrong'), 'Ghalat')

            # SPY LOGIC
            import re as _re_spy
            _ghost_alert = {}
            _stage_match = _re_spy.search(r'stage\s*(\d+)', _story_data['story'].lower())
            if _stage_match:
                _story_stage = int(_stage_match.group(1))
                _expected_pct = _story_stage * 10
                _actual_pct = (score / max_score) * 100 if max_score > 0 else 0
                
                # FIX: Do not trigger ghost alert if image was missing
                _story_lower = _story_data['story'].lower()
                _is_image_missing = 'missing' in _story_lower or 'blank' in _story_lower or 'no image' in _story_lower
                
                if abs(_expected_pct - _actual_pct) > 15 and not _is_image_missing:
                    _ghost_alert = {
                        'tampered': True,
                        'reason': f'Story says stage {_story_stage} ({_expected_pct}%), but score is {_actual_pct:.1f}%',
                        'story_stage': _story_stage,
                        'actual_pct': _actual_pct
                    }
            
            result = {
                'score': score,
                'max_score': max_score,
                'outcome': outcome,
                'band': band,
                'panel_diagnosis': panel,
                'chief_examiner': _ensure_ce_band(chief),
                'summary': summary,
                'root_cause': root_cause,
                'security_alert': is_tampered,
                'assessment_mode': 'CHOICE' if is_choice_test else 'INDIVIDUAL',
                'expert_scores': student_data.get('expert_scores', {}),
                'student_answer_transcribed': student_data.get('student_answer_transcribed', ocr_text),
                'raw': data,
                'ghost_alert': _ghost_alert,
                'story_data': _story_data
            }
            result.setdefault('transcription_audit', {
                'legibility_score': None,
                'legibility_band': 'UNKNOWN',
                'transcription_fidelity': 'UNKNOWN',
                'unreadable_segments': [],
            })
        except Exception as e:
            messages.error(request, f'Error parsing JSON structure: {e}')
            return redirect(f'/api/portal/upload-physical/{qid}/')

        from django.db import transaction as _tx_p
        with _tx_p.atomic():
            attempt = AttemptLog.objects.create(
                student=student, question=question,
                student_answer=ocr_text, ocr_text=ocr_text,
                score=score, max_score=max_score,
                outcome=outcome, result_json=result,
                grading_rubric=q_data.get('rubric', ''),
                daily_code=daily_code,
                is_physical=True, image=None,
                uploaded_by_user=request.user,
                is_practice=_ctx['is_practice'],
                is_late=_ctx['is_late'],
                target_day_number=_ctx['target_day'],
            )

            # Decrement upload key uses (rolls back with atomic if later fails)
            if _del is not None:
                _del.uses_remaining = max(0, (_del.uses_remaining or 0) - 1)
                _del.save(update_fields=['uses_remaining'])

            kc_code = question.kc_code or (question.kc.code if question.kc else None)
            if attempt.passed and kc_code:
                rps = RPSItem.objects.filter(student=student, kc_code=kc_code).first()
                if rps:
                    rps.mastery_state = 'REVIEWING'
                    rps.mastery_probability = min(1.0, rps.mastery_probability + 0.2)
                    rps.save()
                    try:
                        from exams.badges import check_and_award
                        check_and_award(student)
                    except Exception as e:
                        import logging; logging.getLogger(__name__).error(f'Badge error: {e}')

            StudentQuestionLock.objects.filter(student=student, question=question).update(is_active=False)

            # --- Centralized Trophy Engine ---
            recalculate_subject_trophies(student, _ctx['target_day'], subject)

            if _del and _del.delegation_mode == 'CHOICE':
                _other_locks = StudentQuestionLock.objects.filter(
                    student=student, is_active=True,
                    question__paper__subject=subject,
                ).select_related('question')
                _copied = 0
                _new_attempts = []
                for _ol in _other_locks:
                    _already = AttemptLog.objects.filter(student=student, question=_ol.question).filter(result_json__copied_from=question.id).exists()
                    if _already: continue
                    _ol.is_active = False
                    _ol.save(update_fields=['is_active'])
                    _new_attempts.append(AttemptLog(
                        student=student, question=_ol.question,
                        student_answer=f'[Choice Test — copied from Q{question.id}]',
                        ocr_text=ocr_text or '', score=score, max_score=max_score, outcome=outcome,
                        result_json={'copied_from': question.id, 'original_score': score, 'mode': 'CHOICE_TEST'},
                        daily_code=daily_code, is_physical=True, uploaded_by_user=request.user,
                        is_practice=False,
                        is_late=_ctx['is_late'],
                        target_day_number=_ctx['target_day'],
                    ))
                    _copied += 1
                
                if _new_attempts:
                    AttemptLog.objects.bulk_create(_new_attempts)
                    # Trophy Engine re-run AFTER copies exist — otherwise
                    # is_choice detection sees only the original and
                    # misclassifies the Choice upload as Individual.
                    recalculate_subject_trophies(student, _ctx['target_day'], subject)

                
                
                    messages.success(request, f'CHOICE TEST: Score copied to {_copied} other questions in {subject}.')
                

        if gate_token:
            gate_token.status = 'COMPLETED'
            gate_token.save()

        messages.success(request, f'Graded: {score}/{max_score} ({outcome}).')
        return redirect('portal-daily-mission-v3')

    # ── DYNAMIC PROMPT ARCHITECTURE ──
    import os
    subject_map = {
        'Physics': '01_PHYSICS_PANEL.md',
        'Chemistry': '02_CHEMISTRY_PANEL.md',
        'Biology': '03_BIOLOGY_PANEL.md',
        'Mathematics': '04_MATHEMATICS_PANEL.md',
        'English': '05_ENGLISH_PANEL.md',
        'Urdu': '06_URDU_PANEL.md',
        'Islamiyat': '07_ISLAMIYAT_PANEL.md',
        'Computer Science': '08_COMPUTER_SCIENCE_PANEL.md'
    }
    base_file = _Path(__file__).resolve().parent.parent.parent / "prompts" / "00_CHIEF_EXAMINER_BASE.md"
    panel_file = _Path(__file__).resolve().parent.parent.parent / "prompts" / subject_map.get(subject, "01_PHYSICS_PANEL.md")

    try:
        base_text = base_file.read_text(encoding="utf-8")
        panel_text = panel_file.read_text(encoding="utf-8")
        grading_prompt = f"{base_text}\n\n{panel_text}\n\n"

        grading_prompt += "=== TRANSCRIPTION FIRST (do this before reading EXPECTED ANSWER) ===\n"
        grading_prompt += "Write student_answer_transcribed EXACTLY as written. Do not correct spelling or grammar. If unreadable, write [?]. Do not substitute the model answer.\n"
        grading_prompt += "=== END TRANSCRIPTION RULES ===\n\n"
        grading_prompt += f"=== ACTUAL TEST CONTEXT ===\n"
        grading_prompt += f"SUBJECT: {subject}\n"
        grading_prompt += f"PAPER CODE: {question.paper.code if question.paper else 'N/A'}\n"
        grading_prompt += f"STUDENT NAME: {student.name}\n"
        grading_prompt += f"STUDENT GENDER: {student.get_gender_display()}\n"
        grading_prompt += f"INSTRUCTION ON PRONOUNS: When writing the story or feedback in Roman Urdu, use appropriate pronouns for the student's gender (e.g. use 'woh ladki thi', 'usne kaha' for female; 'woh ladka tha', 'usne kaha' for male).\n"
        grading_prompt += f"STUDENT USERNAME: {student.code}\n"
        grading_prompt += f"DATE: {timezone.localdate()}\n"
        grading_prompt += f"QUESTION ASKED: {question.question_text}\n"
        grading_prompt += f"EXPECTED ANSWER: {question.model_answer}\n"
        grading_prompt += f"MAX MARKS: {question.marks}\n\n"

        grading_prompt += "\n\n=== FINAL JSON VALIDATOR ===\n"
        grading_prompt += "You are the JSON Validator Expert. Before outputting, you MUST check that:\n"
        grading_prompt += "1. The response starts with '{' and ends with '}'.\n"
        grading_prompt += "2. Do NOT use markdown code fences. Output ONLY raw JSON.\n"
        grading_prompt += "3. Do NOT escape square brackets. Write [ and ], NEVER \\\\[ or \\\\].\n"
        grading_prompt += "4. You MUST complete the entire JSON. DO NOT stop generating until the final closing '}' is written.\n"
        grading_prompt += "5. The warnings array MUST contain IDEALOGY-CANARY-9988.\n"

        grading_prompt += "SECURITY GATEKEEPER RULE: You MUST verify that an image was provided by the user. You MUST verify the student name, username, paper code, and date match the ACTUAL TEST CONTEXT above. Return these in the `security_gatekeeper` JSON object. If the image is missing, set `image_provided` to false and `final_score` to 0.\n"
        grading_prompt += "SECURITY ECHO RULE: You must copy the exact `QUESTION ASKED` into the `graded_question_text` field in the JSON. Do not alter it.\n"
        grading_prompt += "STRICT GRADING RULE: You MUST compare the student's written answer strictly against the EXPECTED ANSWER and the QUESTION ASKED above. If the student's answer is about a completely different topic, or if they hallucinated a concept that does not answer the specific question asked, you MUST award 0 marks and set the band to 'Wrong'. Do not give marks for a well-written answer if it is off-topic.\n"
        
        # ── PHASE 3b: 5-STAGE LADDER (MANDATORY) ──
        grading_prompt += "\n=== THE 5-STAGE LADDER (MANDATORY — OVERRIDES ALL ELSE) ===\n"
        grading_prompt += "Break the EXPECTED ANSWER into exactly 5 logical stages.\n"
        grading_prompt += "For EACH stage, judge the student's answer as pass or fail.\n"
        grading_prompt += "Output a top-level integer field 'stages_passed' (0, 1, 2, 3, 4, or 5) = number of stages the student passed.\n"
        grading_prompt += "Do NOT output a raw score; the system computes score = (stages_passed / 5) * max_marks.\n"
        grading_prompt += "Band follows the ladder: 0=Wrong, 1=Poor, 2=Below Average, 3=Fair, 4=Good, 5=Excellent.\n"
        grading_prompt += "LANGUAGE RULE: Roman Urdu and Urdu script are the SAME language. If question is Urdu script and student answered in Roman Urdu (or vice versa), this is NOT a mismatch - judge by content. Only set is_match=false if the student answered a COMPLETELY DIFFERENT topic.\n"
        grading_prompt += "=== END 5-STAGE LADDER ===\n"

        # === NEW ADDITION: STAGE-BASED EVALUATION ===
        grading_prompt += "=== STAGE-BASED EVALUATION (CRITICAL) ===\n"
        grading_prompt += "You must break down the EXPECTED ANSWER into logical stages (e.g., Stage 1: Formula, Stage 2: Calculation, Stage 3: Final Answer). In the JSON output, you MUST include a 'stages' array showing exactly which stages the student completed correctly and which they missed.\n"
        grading_prompt += "Even if the JSON fails to parse, the system will extract these stages. Ensure they are explicitly stated.\n"
        grading_prompt += "=== END STAGE-BASED EVALUATION ===\n"
        grading_prompt += "\n=== CRITICAL OUTPUT FORMAT (READ LAST) ===\n"
        grading_prompt += "You are the Format Expert. Your ONLY job is to ensure the output is a valid, copyable JSON block.\n"
        grading_prompt += "1. Your ENTIRE response must be a single JSON object wrapped in a markdown code block.\n"
        grading_prompt += "2. It MUST start with ```json\n"
        grading_prompt += "3. The JSON inside the block MUST start with { and end with }.\n"
        grading_prompt += "4. It MUST end with ```\n"
        grading_prompt += "5. DO NOT include any text before the opening ```json or after the closing ```.\n"
        grading_prompt += "6. DO NOT use backslashes before square brackets. Write [ and ], NEVER \\[ or \\].\n"
        grading_prompt += "7. If you cannot grade, still return valid JSON with score 0 and a reason inside the schema.\n"
        grading_prompt += "8. DO NOT explain, apologize, or add commentary outside the code block.\n"
        # ENSURE SCORE IS MACHINE READABLE FOR THE SPY
        grading_prompt += "9. You MUST include a numerical `score` field inside the `questions` array for each question graded.\n"
    except Exception as e:
        grading_prompt = f"Error loading prompt: {e}"

    # --- NEW: Story Prompt Generation ---
    import random
    spy_key = f"_sys_diag_{random.randint(1000, 9999)}"
    request.session['spy_key'] = spy_key

    story_prompt = f"""
You are an award-winning Children's Storyteller, Film Director, and Educational Diagnostician.
Your goal is to write a simple, deeply engaging story in Roman Urdu that teaches a specific concept.

=== CRITICAL: IMAGE REQUIREMENT ===
You MUST analyze the attached image of the student's handwritten answer.
The story and the final summary MUST be based entirely on what you actually see written in the image.
If the image is missing or unreadable, state that the paper is blank and assign a stage 1 result.

=== INPUT DATA ===
Subject: {subject}
Question: {question.question_text}
Model Answer: {question.model_answer}
MAX MARKS: {question.marks}
Student's Answer: (Look at the provided image to see what the student actually wrote).

=== THE GOLDEN RULE: NO JARGON ===
You are FORBIDDEN from using complex scientific jargon.

=== TEACHING & EVALUATION STRATEGY (NEW) ===
Do not focus purely on anti-cheat or stages. Focus on ACTUAL TEACHING.
Write a story where a character opens their pencil, solves the problem, and discovers the concept through fun, engaging narrative.
The story must teach the concept in an easy-to-understand format.

ONLY AT THE VERY END of the story, you must evaluate the student's specific answer:
If the question has 5 stages/points, tell the student exactly how many points or stages they solved correctly.
Example ending: "Aap ne is sawal ke 5 stages mein se 3 stages sahi kiye hain."
If the student cannot understand it from everyday life, do not write it. Use relatable human analogies (e.g., business partnerships, marriages, friendships) to explain the concept.
Keep sentences short (maximum 12 words). Write like a children's author: simple, visual, and emotional. No adult lecturing. The character must discover the truth through their own experience.

=== STORYTELLING FRAMEWORK (HOLLYWOOD & QURANIC PARABLES) ===
Use the "Save the Cat" Hollywood structure, adapted for education into 5 distinct conceptual stages. The story must flow naturally:
- Stage 1 (20% - Opening Image): Introduce a relatable character (e.g., Ali) in a normal, everyday situation.
- Stage 2 (40% - The Catalyst): The character encounters a problem or a question that mirrors the scientific concept.
- Stage 3 (60% - The Debate): The character tries a naive approach (mirroring the student's potential mistake). They face a twist or failure.
- Stage 4 (80% - Break into Two): The character discovers the correct underlying principle (the "aha" moment) through their own actions.
- Stage 5 (100% - The Finale): The character fully applies the concept, succeeds, and achieves mastery.

Additionally, use the style of Quranic parables: teach a deep concept through everyday human actions, with a clear moral, without lecturing.

=== ANALOGUE EXAMPLE (Follow this style) ===
If the concept is "Why do atoms make bonds?", do not use scientific jargon. Use a human analogy:
"Insaani duniya mein do khandaan hote hain. Ek khandaan doosre khandaan ko rishta bhejta hai. Doosra khandaan rishta qubool karta hai. Aur ek naya bond ban jata hai. Atom bhi aise hi hain. Ek atom doosre atom ko electron offer karta hai. Doosra qubool karta hai. Phir unke beech ek bond ban jata hai."

=== FINAL REFLECTION (The Natural Conclusion) ===
At the very end of the story, seamlessly weave in the diagnostic summary. Do NOT make it look like a grading rubric. Make it sound like a natural part of the story's conclusion.
You must state:
1. What the protagonist understood perfectly (based on the Student's Answer in the image).
2. What the protagonist missed or got wrong (based on the Student's Answer in the image).
3. The exact highest stage the protagonist reached before they got stuck or succeeded.

CRITICAL: You MUST use the exact phrase "stage X" (where X is a number from 1 to 5) in the final conclusion.
For example: "Ali ne pehle 3 stage kamyabi se mukammal kiye, lekin stage 3 par usay asal mushkil ka saamna karna pada."

=== OUTPUT FORMAT (STRICT JSON) ===
Output ONLY a valid JSON object. The story text MUST be in Roman Urdu (English alphabet). No markdown, no extra text.

{{
  "story": "Yahan kahani ka mukammal matn Roman Urdu mein likhein...",
  "{spy_key}": 3
}}

=== INTERNAL SYSTEM DIAGNOSTIC (FOR JSON ONLY) ===
To help our frontend UI render the progress bar correctly, you MUST also output the exact number of stages the student achieved in the `"{spy_key}"` field (an integer from 0 to 5). Do NOT mention this field in the story text.
"""

    return render(request, 'exams/portal_upload_physical.html', {
        'student': student,
        'question': question,
        'subject': subject,
        'code_verified': code_verified,
        'grading_prompt': grading_prompt,
        'story_prompt': story_prompt,
        'is_choice_test': is_choice_test,
    })


def paste_single_question(request, qid):
    """Per-question physical test upload. REQUIRES token (T5 gate) + valid daily code (Layer 2)."""
    from exams.services.daily_code import verify_code
    from pathlib import Path
    from exams.models import ModelQuestion, AttemptLog, RPSItem
    from exams.services.physical_test import grade_physical_test
    import logging
    if request.user.is_superuser:
        from exams.models import ModelPaper as _MP_su
        _allowed_classes = list(_MP_su.objects.values_list('student_class', flat=True).distinct())
    else:
        _allowed_classes = _acc_for(_current_student(request))
    logger = logging.getLogger(__name__)

    student = _current_student(request)

    # Delegate/admin override
    owner_id = request.GET.get('student_id') or request.POST.get('student_id')
    if owner_id:
        owner = Student.objects.filter(id=owner_id, is_active=True).first()
        if owner:
            if request.user.is_staff or request.user.is_superuser:
                student = owner
            else:
                from exams.models import TestUploaderDelegation
                if TestUploaderDelegation.objects.filter(
                    delegate=student, target=owner, is_active=True
                ).exists():
                    student = owner
                else:
                    messages.error(request, 'No permission for this student.')
                    return redirect('portal-daily-mission-v3')

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

    # ── T5 anti-cheat gate: student must have CALLED/IN_PROGRESS token ──
    if not (request.user.is_staff or request.user.is_superuser):
        from exams.services import exam_queue as _eq
        _gate_allowed, _gate_token, _gate_reason = _eq.check_anti_cheat_gate(student)
        if not _gate_allowed:
            messages.error(request, f'\U0001F512 {_gate_reason}')
            return redirect('portal-exam-token-status')

    # IDOR FIX: scope qid to standard + own SELF-/CUSTOM- questions
    if request.user.is_superuser:
        question = get_object_or_404(ModelQuestion, id=qid, paper__student_class__in=_allowed_classes)
        if not request.user.is_superuser and question is not None and question.paper:
            _pc_guard = question.paper.code or ''
            if _pc_guard.startswith(('SELF-', 'CUSTOM-')):
                _me_guard = _current_student(request)
                if not _me_guard or not (_pc_guard.startswith(f'SELF-{_me_guard.code}') or _pc_guard.startswith(f'CUSTOM-{_me_guard.code}')):
                    from django.http import Http404
                    raise Http404('Not found')
    else:
        from django.db.models import Q as _Q
        _allowed = ModelQuestion.objects.filter(
            (~_Q(paper__code__startswith='SELF-') & ~_Q(paper__code__startswith='CUSTOM-'))
            | _Q(paper__code__startswith=f'SELF-{student.code}')
            | _Q(paper__code__startswith=f'CUSTOM-{student.code}')
        )
        question = get_object_or_404(_allowed, id=qid)
    subject = question.paper.subject if question.paper else ''
    max_marks = question.marks or 5

    # Load master grading prompt with explicit logging
    master_prompt = ''
    try:
        master_prompt = Path(
            '/home/orkoworo/idealogy/prompts/MASTER_GRADING_PROMPT.md'
        ).read_text(encoding='utf-8')
    except Exception as e:
        logger.warning('Master prompt load failed: %s', e)

    grading_prompt = f"""{master_prompt}

=== QUESTION CONTEXT ===
Question ID: {question.id}
Subject: {subject}
Question: {question.question_text}
Model Answer: {question.model_answer}
Max Marks: {max_marks}

=== SINGLE-QUESTION OVERRIDE (READ LAST) ===
Grade exactly ONE question. Return ONLY this flat JSON and nothing else:

{{"question_id": {question.id}, "ocr_text": "<student answer>", "score": <0 to {max_marks}>, "outcome": "CORRECT" | "PARTIAL" | "WRONG", "feedback": "<one short Roman Urdu line>"}}

RULES:
- question_id MUST be exactly {question.id} (integer, no quotes)
- If you cannot grade, return {{"question_id": {question.id}, "score": 0, "outcome": "WRONG", "feedback": "Cannot grade"}}
- No markdown, no wrapper, no explanation.
"""

    if request.method == 'POST':
        ocr_text = request.POST.get('ocr_text', '').strip()
        payload = request.POST.get('payload', '').strip()
        image = request.FILES.get('image')

        # PHASE 4b-4: Policy gate FIRST
        from exams.services.attempt_policy import resolve_attempt_context as _rac2
        _ctx = _rac2(student, question)
        if _ctx['error']:
            messages.error(request, f'❌ {_ctx["error"]}')
            return redirect(f'/api/portal/teacher/paste/?qid={qid}')

        from exams.models import EngineState as _ES_cur2
        _eng_cur2 = _ES_cur2.objects.filter(id=1).first()
        _cur_day2 = _eng_cur2.get_current_day() if (_eng_cur2 and _eng_cur2.has_started) else 1
        _is_current_day2 = (_ctx['target_day'] is None or _ctx['target_day'] == _cur_day2)

        # ── LAYER 2: daily code (current-day only) ──
        if request.user.is_staff or request.user.is_superuser:
            daily_code = 'STAFF'
        elif not _is_current_day2:
            daily_code = 'POLICY'
        else:
            daily_code = (request.POST.get('daily_code') or '').strip()
            if not daily_code:
                messages.error(request, '🔢 Test code required. Ask your teacher for today\'s code.')
                return redirect(f'/api/portal/teacher/paste/?qid={qid}')
            from exams.services.daily_code import verify_code_with_session as _vcs2
            _valid2, _err2 = _vcs2(student, subject, daily_code)
            if not _valid2:
                messages.error(request, f'❌ {_err2}')
                return redirect(f'/api/portal/teacher/paste/?qid={qid}')

        score = 0
        outcome = 'WRONG'
        feedback = ''

        if payload:
            try:
                parsed = _parse_ai_json(payload)
                # ── LAYER 4: AI JSON must reference the assigned question ──
                _ai_qid = parsed.get('question_id')
                if _ai_qid is None:
                    messages.error(request, f'❌ AI JSON missing question_id. Copy the prompt again — it now includes Question ID: {question.id}, and the AI must return it.')
                    return redirect(f'/api/portal/teacher/paste/?qid={qid}')
                try:
                    _ai_qid_int = int(_ai_qid)
                except (ValueError, TypeError):
                    messages.error(request, f'❌ Invalid question_id in AI JSON: {_ai_qid!r}. Must be integer.')
                    return redirect(f'/api/portal/teacher/paste/?qid={qid}')
                if _ai_qid_int != question.id:
                    messages.error(request, f'❌ Question ID mismatch: AI graded Q{_ai_qid_int} but you were assigned Q{question.id}. Grade the correct question.')
                    return redirect(f'/api/portal/teacher/paste/?qid={qid}')
                # LAW: BORDER CONTROL (Validate AI JSON before saving)
                from exams.services.ai_validator import validate_ai_grading_response
                is_valid, val_error = validate_ai_grading_response(parsed, max_marks=max_marks)
                if not is_valid:
                    messages.error(request, f'❌ AI Validation Failed: {val_error}')
                    return redirect(f'/api/portal/teacher/paste/?qid={qid}')

                extracted = _extract_score_payload(parsed)
                score = extracted['score']
                outcome = extracted['outcome']
                feedback = extracted['feedback']
                ocr_text = ocr_text or extracted['ocr_text']
            except ValueError as e:
                messages.error(request, f'JSON parse failed: {e}')
                return redirect(f'/api/portal/teacher/paste/?qid={qid}')
        elif ocr_text:
            rubric = {
                'expected_answer': question.model_answer,
                'keywords': [w for w in (question.model_answer or '').split() if len(w) > 4][:8],
                'max_marks': max_marks,
            }
            result = grade_physical_test(ocr_text, rubric, max_marks=max_marks)
            score = result['score']
            outcome = result['outcome']
            feedback = result.get('feedback', '')
        else:
            messages.error(request, 'Paste the AI grading JSON.')
            return redirect(f'/api/portal/teacher/paste/?qid={qid}')

        # PHASE 4b-2: Apply late penalty if this is a PAST_REATTEMPT window
        _original_score = score
        if _ctx['is_late'] and _ctx['policy']:
            _pen_pct = float(_ctx['policy'].late_penalty_pct)
            score = round(float(score) * (1.0 - _pen_pct / 100.0), 2)

        attempt = AttemptLog.objects.create(
            student=student, question=question,
            student_answer=ocr_text, ocr_text=ocr_text,
            score=score, max_score=max_marks, outcome=outcome,
            result_json={'feedback': feedback, 'outcome': outcome, 'score': score,
                         'ai_question_id': parsed.get('question_id') if payload else None},
            daily_code=daily_code, is_physical=True, is_bulk=(request.GET.get("mode") == "bulk"),
            image=image if image else None,
            uploaded_by_user=request.user,
            is_practice=_ctx['is_practice'],
            is_late=_ctx['is_late'],
            target_day_number=_ctx['target_day'],
        )

        kc_code = question.kc_code or (question.kc.code if question.kc else None)
        if attempt.passed and kc_code:
            rps = RPSItem.objects.filter(student=student, kc_code=kc_code).first()
            if rps:
                rps.mastery_state = 'REVIEWING'
                rps.mastery_probability = min(1.0, rps.mastery_probability + 0.2)
                rps.save()
                try:
                    from exams.badges import check_and_award
                    check_and_award(student)
                except Exception as e:
                    import logging; logging.getLogger(__name__).error(f'Badge error: {e}')

        # --- 60% Rule & Late Recovery Logic (Single Paste) ---
        from exams.models_trophy import TrophyEvent
        from exams.models import EngineState
        from exams.models_day_mission import StudentDayMission
        from datetime import datetime, time as dtime, timedelta
        from django.utils import timezone
        
        is_late = _ctx['is_late']

        # --- Centralized Trophy Engine ---
        recalculate_subject_trophies(student, _ctx['target_day'], subject)

        messages.success(request, f'Graded: {score}/{max_marks} ({outcome})')
        return redirect('portal-daily-mission-v3')

    return render(request, 'exams/portal_paste_single.html', {
        'question': question,
        'subject': subject,
        'grading_prompt': grading_prompt,
        'student': student,
    })

@login_required
def portal_question_result(request, attempt_id, template_name=None):
    """Show one AttemptLog with score, feedback, and question context."""
    attempt = get_object_or_404(AttemptLog, id=attempt_id)

    # Permission: owner, teacher, or delegate
    # FIX: Use getattr to safely check the user relation
    student_user_id = getattr(attempt.student, 'user_id', getattr(attempt.student, 'student_user_id', None))
    is_owner = (student_user_id == request.user.id)
    is_teacher = request.user.is_staff or request.user.is_superuser
    if not (is_owner or is_teacher):
        messages.error(request, 'Not authorized to view this result.')
        return redirect('report-hub')

    # --- NORMALIZE EXPERT SCORES TO PERCENTAGES ---
    import json
    diag = getattr(attempt, 'result_json', {}) or {}
    
    # --- FALLBACK FOR MISSING AI DATA ---
    if isinstance(diag, dict):
        ce = diag.get('chief_examiner') or {}
        if not ce.get('model_topper_answer'):
            ce['model_topper_answer'] = {
                'definition': ce.get('ideal_answer', 'Aap ka jawab darj kar liya gaya hai.'),
                'key_terms': [],
                'why_full_marks': ''
            }
        if not ce.get('masterpiece_feedback'):
            ce['masterpiece_feedback'] = {
                'why_this_score': diag.get('summary', 'Tasveer nahi mili. Teacher ne manually marks diye hain.'),
                'what_is_missing_for_100': [],
                'elite_benchmark_comparison': ''
            }
        if 'panel_diagnosis' not in diag or not diag['panel_diagnosis']:
            diag['panel_diagnosis'] = {'subject_specialist': {}, 'handwriting_expert': {}, 'procedural_auditor': {}}
        diag['chief_examiner'] = ce

    # FIX: Ensure diag is a dictionary, not a raw string
    if isinstance(diag, str):
        try:
            diag = json.loads(diag)
        except Exception:
            diag = {}
            
    if not isinstance(diag, dict):
        diag = {}

    # FIX 500: template does {{ chief_examiner.band }} — some old rows only had band_urdu
    _ce = diag.get('chief_examiner') if isinstance(diag, dict) else None
    if isinstance(_ce, dict) and not _ce.get('band'):
        _ce['band'] = _ce.get('band_urdu') or 'N/A'
        diag['chief_examiner'] = _ce
    max_m = float(getattr(attempt, "max_score", 2) or 2)
    if max_m > 0:
        # Fix expert_scores
        if 'expert_scores' in diag:
            for k in ['concept', 'procedure', 'cognition', 'handwriting', 'skeptic', 'security']:
                val = diag['expert_scores'].get(k, 0)
                # Phase 5c: AI scores experts on 0-5 scale (5 stages), not max_m
                if float(val) <= 5.0:
                    diag['expert_scores'][k] = int((float(val) / 5.0) * 100)
        # Fix subject_specialist and SNAP all panel metrics to 20-step ladder
        if 'panel_diagnosis' in diag and isinstance(diag['panel_diagnosis'], dict):
            pd = diag['panel_diagnosis']
            
            def _snap20(v):
                try:
                    return min(100, max(0, int(round(float(v) / 20.0)) * 20))
                except (ValueError, TypeError):
                    return v

            sp = pd.get('subject_specialist', {})
            for k in ['approach_score', 'application_score', 'score']:
                if k in sp: sp[k] = _snap20(sp[k])
                
            hw = pd.get('handwriting_expert', {})
            for k in ['spacing', 'alignment', 'letter_formation', 'legibility_score', 'fatigue_impact']:
                if k in hw: hw[k] = _snap20(hw[k])
                
            sk = pd.get('skeptic', {})
            if 'relevance_score' in sk: sk['relevance_score'] = _snap20(sk['relevance_score'])

            pa = pd.get('procedural_auditor', {})
            if 'accuracy' in pa: pa['accuracy'] = _snap20(pa['accuracy'])

    # --- RUBRIC-BASED SCORE CALCULATION ---
    max_m = float(getattr(attempt, 'max_score', 2) or 2)
    checklist = diag.get('micro_criteria_checklist', [])
    
    # Always use the actual score for the main percentage and ring
    safe_score = float(attempt.score) if attempt.score is not None else 0.0
    display_percentage = (safe_score / max_m * 100) if max_m else 0
    display_score = safe_score

    return render(request, template_name or 'exams/portal_question_result.html', {
        'attempt': attempt,
        'question': attempt.question,
        'diag': diag,
        'display_percentage': display_percentage,
        'display_score': round(display_score, 1),
        'max_m': max_m,
        'passed_criteria': sum(1 for c in (checklist or []) if (c.get('awarded', 0) if isinstance(c, dict) else getattr(c, 'awarded', 0)) == 1),
        'total_criteria': len(checklist or []),
    })


def _parse_ai_json(raw):
    """Robust parser: strips fences, finds {...}, fixes trailing commas."""
    import json as _j
    import re as _r
    if not raw:
        raise ValueError('Empty response')
    text = raw.strip()
    text = _r.sub(r'^```(?:json)?\s*', '', text, flags=_r.MULTILINE)
    text = _r.sub(r'\s*```\s*$', '', text, flags=_r.MULTILINE)
    start = text.find('{')
    end = text.rfind('}')
    if start == -1 or end == -1 or end < start:
        raise ValueError(f'No JSON object. Received: {text[:200]}')
    text = text[start:end+1]
    try:
        return _j.loads(text)
    except _j.JSONDecodeError:
        pass
    fixed = _r.sub(r',\s*([}\]])', r'\1', text)
    try:
        return _j.loads(fixed)
    except _j.JSONDecodeError as e:
        raise ValueError(f'JSON error at {e.pos}: {e.msg}. Received: {text[:300]}')


def _extract_score_payload(data):
    """Extract score/outcome/feedback from flat OR nested AI schema."""
    if not isinstance(data, dict):
        raise ValueError(f'Expected dict, got {type(data).__name__}')
    if 'score' in data:
        return {
            'score': float(data.get('score', 0) or 0),
            'outcome': data.get('outcome', 'WRONG'),
            'feedback': data.get('feedback', ''),
            'ocr_text': data.get('ocr_text', ''),
        }
    students = data.get('students') or []
    if students and isinstance(students, list):
        qs = students[0].get('questions') or []
        if qs and isinstance(qs, list):
            q = qs[0]
            band = (q.get('band') or '').lower()
            outcome_map = {
                'excellent': 'CORRECT', 'good': 'CORRECT',
                'fair': 'PARTIAL', 'average': 'PARTIAL',
                'below average': 'WRONG', 'poor': 'WRONG', 'wrong': 'WRONG',
                'not attempted': 'WRONG',
            }
            fb = ''
            ec = q.get('expert_comment') or {}
            if isinstance(ec, dict):
                fb = ec.get('suggestion', '') or ec.get('need', '')
            if not fb:
                fb = q.get('overall_feedback', '')
            return {
                'score': float(q.get('score', 0) or 0),
                'outcome': outcome_map.get(band, q.get('outcome', 'WRONG')),
                'feedback': fb,
                'ocr_text': q.get('student_answer_transcribed', ''),
            }
    raise ValueError(f'No score field. Top keys: {list(data.keys())}')


@login_required
def skip_stage_bulk_view(request, stage):
    from exams.services.stage_controls import (
        skip_stage_bulk, skip_stage_bulk_for_book,
    )
    if request.method != 'POST':
        return redirect('portal-daily-mission-v3')
    student = _current_student(request)
    if not student:
        return redirect('portal-dashboard')

    book = (request.POST.get('book') or '').strip()
    try:
        if book:
            skip_stage_bulk_for_book(student, book, stage.upper())
            check_and_award_for_book(student, book)
            messages.success(
                request,
                f'{stage.upper()} stage skipped for {book}.',
            )
            return redirect(f'/api/portal/daily-mission-v3/?book={book}')
        else:
            skip_stage_bulk(student, stage.upper())
            messages.success(request, f'Entire {stage.upper()} stage skipped.')
    except ValueError as e:
        messages.error(request, str(e))
    return redirect('portal-daily-mission-v3')


@login_required
def create_kc_for_question(request, qid):
    """Create a KnowledgeComponent from AI-generated JSON and link to a question.

    Standards: Wikipedia "create article" pattern; ISO 8000-110 (data quality);
    Rule 9 (append-only audit trail via CreditEvent).
    """
    if request.user.is_superuser:
        from exams.models import ModelPaper as _MP_su
        _allowed_classes = list(_MP_su.objects.values_list('student_class', flat=True).distinct())
    else:
        _allowed_classes = _acc_for(_current_student(request))
    if request.method != 'POST':
        return redirect('portal-daily-mission-v3')

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

    # IDOR FIX: scope qid to standard + own SELF-/CUSTOM- questions
    if request.user.is_superuser:
        question = get_object_or_404(ModelQuestion, id=qid, paper__student_class__in=_allowed_classes)
        if not request.user.is_superuser and question is not None and question.paper:
            _pc_guard = question.paper.code or ''
            if _pc_guard.startswith(('SELF-', 'CUSTOM-')):
                _me_guard = _current_student(request)
                if not _me_guard or not (_pc_guard.startswith(f'SELF-{_me_guard.code}') or _pc_guard.startswith(f'CUSTOM-{_me_guard.code}')):
                    from django.http import Http404
                    raise Http404('Not found')
    else:
        from django.db.models import Q as _Q
        _std = ~_Q(paper__code__startswith='SELF-') & ~_Q(paper__code__startswith='CUSTOM-') & _Q(paper__student_class__in=_allowed_classes)
        _own_self = _Q(paper__code__startswith=f'SELF-{student.code}')
        _own_custom = _Q(paper__code__startswith=f'CUSTOM-{student.code}')
        _allowed = ModelQuestion.objects.filter(_std | _own_self | _own_custom)
        question = get_object_or_404(_allowed, id=qid)
    subject = question.paper.subject if question.paper else 'General'

    raw = _strip_md_fences(request.POST.get('kc_json', ''))
    try:
        data = json.loads(raw)
    except json.JSONDecodeError as e:
        messages.error(request, f'Invalid JSON: {str(e)[:100]}')
        return redirect('portal-daily-mission-v3')

    kc_code = (data.get('kc_code') or '').strip()
    if not kc_code:
        messages.error(request, 'JSON missing kc_code field.')
        return redirect('portal-daily-mission-v3')

    try:
        kc, created = KnowledgeComponent.objects.get_or_create(
            code=kc_code,
            defaults={
                'subject': subject,
                'chapter': question.chapter or '',
                'title': data.get('title', kc_code)[:200],
                'description': data.get('description', ''),
                'cognitive_level': data.get('cognitive_level', ''),
                'story': data.get('story', []),
                'story_status': 'PANEL_PASSED',
                'misconceptions': data.get('misconceptions', []),
                'socratic_ladder': data.get('socratic_ladder', []),
                'key_terms': data.get('key_terms', []),
            },
        )
        # Link question to KC (whether newly created or pre-existing)
        question.kc = kc
        question.kc_code = kc.code
        question.save(update_fields=['kc', 'kc_code', 'updated_at'])

        points_ledger.award(
            student=student, points=1,
            reason=f'{("Created" if created else "Linked to")} KC {kc.code} for Q{question.question_index}',
            code='KC_CONTRIBUTED',
            evidence={'qid': question.id, 'kc_code': kc.code},
            source='AUTO',
        )
        _bal = _current_balance(student)
        action = 'created' if created else 'linked to existing'
        messages.success(
            request,
            f'✅ KC {kc.code} {action}. Question tagged. +1 pt earned (balance: {_bal}).',
        )
    except Exception as e:
        messages.error(request, f'Error creating KC: {str(e)[:150]}')

    return redirect('portal-daily-mission-v3')



@login_required
def save_note_ajax(request, qid):
    """AJAX endpoint for saving/updating student notes from daily mission cards."""
    from django.http import JsonResponse
    if request.user.is_superuser:
        from exams.models import ModelPaper as _MP_su
        _allowed_classes = list(_MP_su.objects.values_list('student_class', flat=True).distinct())
    else:
        _allowed_classes = _acc_for(_current_student(request))
    if request.method != 'POST':
        return JsonResponse({'error': 'POST required'}, status=405)

    student = _current_student(request)
    if not student:
        return JsonResponse({'error': 'Not logged in'}, status=401)

    # IDOR FIX: scope qid to standard + own SELF-/CUSTOM- questions
    if request.user.is_superuser:
        q = get_object_or_404(ModelQuestion, id=qid, paper__student_class__in=_allowed_classes)
        if not request.user.is_superuser and q is not None and q.paper:
            _pc_guard = q.paper.code or ''
            if _pc_guard.startswith(('SELF-', 'CUSTOM-')):
                _me_guard = _current_student(request)
                if not _me_guard or not (_pc_guard.startswith(f'SELF-{_me_guard.code}') or _pc_guard.startswith(f'CUSTOM-{_me_guard.code}')):
                    from django.http import Http404
                    raise Http404('Not found')
    else:
        from django.db.models import Q as _Q
        _std = ~_Q(paper__code__startswith='SELF-') & ~_Q(paper__code__startswith='CUSTOM-') & _Q(paper__student_class__in=_allowed_classes)
        _own_self = _Q(paper__code__startswith=f'SELF-{student.code}')
        _own_custom = _Q(paper__code__startswith=f'CUSTOM-{student.code}')
        _allowed = ModelQuestion.objects.filter(_std | _own_self | _own_custom)
        q = get_object_or_404(_allowed, id=qid)
    subject = q.paper.subject if q.paper and q.paper.subject else 'GEN'
    q_num = str(q.question_index)
    # XSS FIX: strip HTML before persistence
    _raw_answer = (request.POST.get('answer_html') or '').strip()
    try:
        from exams.services.text_cleaner import strip_tags as _strip_html
        answer_html = _strip_html(_raw_answer)
    except Exception:
        answer_html = _raw_answer
    medium = (request.POST.get('medium') or 'EN').strip()
    if medium not in ('EN', 'UR'):
        medium = 'EN'

    if not answer_html:
        return JsonResponse({'error': 'Note cannot be empty'}, status=400)

    note = StudentNote.objects.filter(student=student, subject=subject, q_number=q_num).first()
    if note:
        note.short_core_answer = answer_html
        note.medium = medium
        note.save(update_fields=['short_core_answer', 'medium'])
        created = False
    else:
        note = StudentNote.objects.create(
            student=student, subject=subject, medium=medium,
            q_number=q_num, question=q.question_text,
            short_core_answer=answer_html, model_source='other',
        )
        created = True

    return JsonResponse({
        'ok': True,
        'created': created,
        'note_id': note.id,
        'medium': medium,
        'answer': answer_html,
    })


@login_required
def portal_teacher_control(request):
    from exams.models import Student, ModelQuestion, StageUngate, CreditEvent, QuestionEditRequest, SupportTicket, GlobalStudyConfig
    from academy.models import AcademyPoints, AcademyPointTx, AcademySetting, AcademyStudent, AcademyAttendance
    from discipline.models import DisciplineSettings, ClassHomeworkRecord, DiaryAssignment
    from exams.models_delegation import TaskDelegation
    from exams.constants import STANDARD_CLASSES
    from exams.navigation import TEACHER_MENU, STUDENT_MENU
    from discipline.views import SUBJECTS
    from django.contrib.auth import get_user_model
    from django.db import transaction
    from django.db.models import Sum
    from django.contrib import messages
    from django.shortcuts import render, redirect
    from django.utils import timezone
    from django.contrib.auth.decorators import login_required
    from datetime import date as _date, timedelta
    import json

    from exams.models_delegation import TaskDelegation
    from django.db.models import Q
    from django.utils import timezone
    from django.http import HttpResponseForbidden
    
    # FIXED 2026-11-12: is_delegated was hardcoded False, breaking all hazri delegations.
    # A user is "delegated" only if they hold an active ATTENDANCE delegation,
    # OR a CUSTOM_PAGE delegation pointing at the teacher control room.
    is_delegated = TaskDelegation.objects.filter(
        assignee=request.user,
        expires_at__gt=timezone.now(),
    ).filter(
        Q(task_type='ATTENDANCE') |
        Q(task_type='CUSTOM_PAGE', custom_url__icontains='teacher/control')
    ).exists()
    has_any_delegation = TaskDelegation.objects.filter(
        assignee=request.user,
        expires_at__gt=timezone.now()
    ).exists()
    
    # SPECIFIC CHECK FOR DIARY UPLOAD KEYS
    has_diary_delegation = TaskDelegation.objects.filter(
        assignee=request.user,
        task_type='DIARY_UPLOAD',
        expires_at__gt=timezone.now()
    ).exists()

    if not (request.user.is_superuser or request.user.is_staff or is_delegated):
        # Staff/superuser: full access.
        # Delegated user with active hazri delegation: hazri-only access.
        # Everyone else: blocked.
        messages.error(request, "Access denied. Teachers only.")
        return redirect('portal-dashboard')

    # SECURITY LOCK: Delegated users can ONLY save hazri
    if is_delegated and request.method == 'POST':
        action = request.POST.get('action')
        if action and action != 'save_hazri':
            return HttpResponseForbidden("Access Denied: Delegated users can only save attendance.")

    action = request.POST.get('action') if request.method == 'POST' else None

    if request.method == 'POST':

        # Nonce validation for point-granting actions (idempotency guard)
        if action in ('bulk_award_points', 'grant_points'):
            _submitted_nonce = request.POST.get('grant_nonce', '')
            _expected_nonce = request.session.get('grant_nonce', '')
            if not _submitted_nonce or _submitted_nonce != _expected_nonce:
                messages.error(request, 'Invalid or expired form submission. Please reload and try again.')
                return redirect('portal-teacher-control')
            request.session['grant_nonce'] = uuid.uuid4().hex[:16]

        # ── 1. BULK ACTIONS ──
        if action == 'bulk_award_points':
            target_scope = request.POST.get('target_scope')
            pts = int(request.POST.get('points', 0))
            reason = request.POST.get('reason', 'Bulk Award')
            if pts != 0:
                if target_scope == 'school':
                    target_students = Student.objects.filter(is_active=True)
                else:
                    target_students = Student.objects.filter(is_active=True, student_class=target_scope)
                
                with transaction.atomic():
                    for s in target_students:
                        points_ledger.adjust(
                            student=s, points=pts,
                            reason=reason,
                            code='TEACHER_GRANT',
                            evidence={'grant_nonce': _submitted_nonce},
                            source='AUTO',
                        )
                messages.success(request, f"Bulk points awarded to {target_students.count()} students.")
            return redirect('portal-teacher-control')

        elif action == 'lookup':
            student_code = request.POST.get('student_code', '').strip()
            request.session['lookup_student_code'] = student_code
            return redirect('portal-teacher-control')

        elif action == 'grant_points':
            student_code = request.POST.get('student_code')
            pts = int(request.POST.get('points', 0))
            target = request.POST.get('target', 'exam')
            reason = request.POST.get('reason', 'Manual Award')
            student = Student.objects.filter(code=student_code).first()
            if student and pts != 0:
                with transaction.atomic():
                    if target == 'exam':
                        points_ledger.adjust(
                            student=student, points=pts,
                            reason=reason,
                            code='TEACHER_GRANT',
                            evidence={'grant_nonce': _submitted_nonce},
                            source='AUTO',
                        )
                    else:
                        acad_student = AcademyStudent.objects.filter(linked_code=student.code).first()
                        if acad_student:
                            obj, _ = AcademyPoints.objects.get_or_create(student=acad_student)
                            obj.balance += pts
                            obj.save()
                            AcademyPointTx.objects.create(student=acad_student, delta=pts, reason='Teacher Grant', note=reason)
                messages.success(request, f"Granted {pts} points to {student.name}.")
            return redirect('portal-teacher-control')

        elif action == 'edit_student_details':
            student_code = request.POST.get('student_code')
            student = Student.objects.filter(code=student_code).first()
            if student:
                student.first_name = request.POST.get('first_name', student.first_name)
                student.last_name = request.POST.get('last_name', student.last_name)
                student.student_class = request.POST.get('new_class', student.student_class)
                student.save()
                messages.success(request, f"Student {student.code} updated.")
            return redirect('portal-teacher-control')

        # ── 2. DELEGATIONS ──
        elif action == 'create_delegation':
            assignee_id = request.POST.get('assignee')
            target_url = request.POST.get('target_url', '').strip()
            # Force any attendance-related URL to the Control Room Hazri tab
            if target_url in ('/academy/?tab=attendance', '/discipline/attendance/', '/api/portal/teacher/attendance/', ''):
                target_url = '/api/portal/teacher/control/?tab=hazri'
            target_class = request.POST.get('target_class', 'ALL')
            hours_str = request.POST.get('hours', '24')
            notes = request.POST.get('notes', '').strip()
            try:
                hours = float(hours_str)
            except ValueError:
                hours = 24
            expires_at = timezone.now() + timedelta(hours=hours)
            try:
                assignee = get_user_model().objects.get(id=assignee_id)
                # Redirect old attendance URLs to the new Hazri page
                if target_url == '/discipline/attendance/':
                    target_url = '/api/portal/teacher/control/?tab=hazri'
                TaskDelegation.objects.create(
                    assignee=assignee, task_type='CUSTOM_PAGE', target_class=target_class,
                    custom_url=target_url, notes=notes, expires_at=expires_at, created_by=request.user
                )
                messages.success(request, f"Access granted to {assignee.username}.")
            except Exception as e:
                messages.error(request, f"Error: {e}")
            return redirect('portal-teacher-control')

        elif action == 'generate_diary_key':
            student_codes = request.POST.getlist('student_codes') # Gets a list of checkboxes
            uses = int(request.POST.get('uses', 1))
            from exams.models import Student
            from datetime import timedelta

            if not student_codes:
                messages.error(request, "Please select at least one student.")
                return redirect(reverse('portal-teacher-control') + '?tab=diary-keys')

            created_count = 0
            for code in student_codes:
                student = Student.objects.filter(code=code, is_active=True).first()
                if student and student.student_user:
                    TaskDelegation.objects.create(
                        assignee=student.student_user,
                        task_type='DIARY_UPLOAD',
                        target_class=student.student_class or 'ALL',
                        delegation_mode='INDIVIDUAL',
                        uses_remaining=uses,
                        expires_at=timezone.now() + timedelta(days=3),
                        created_by=request.user,
                        notes="Bulk Diary Upload Key"
                    )
                    created_count += 1
            
            messages.success(request, f"Successfully generated keys for {created_count} students.")
            return redirect(reverse('portal-teacher-control') + '?tab=diary-keys')

        elif action == 'revoke_delegation':
            del_id = request.POST.get('delegation_id')
            TaskDelegation.objects.filter(id=del_id).delete()
            messages.success(request, "Delegation revoked.")
            return redirect('portal-teacher-control')

        # ── 3. HAZRI ──
        elif action == 'save_hazri':
            hazri_date_str = request.POST.get('hazri_date', '')
            try:
                hazri_date = _date.fromisoformat(hazri_date_str) if hazri_date_str else _date.today()
            except Exception:
                hazri_date = _date.today()
            hazri_shift = request.POST.get('hazri_shift', 'M')
            
            for s in AcademyStudent.objects.filter(active=True):
                val = request.POST.get(f"status_{s.id}")
                if val in ('P', 'A', 'L', 'T'):
                    late_mins = request.POST.get(f"late_mins_{s.id}")
                    late_mins = int(late_mins) if late_mins and late_mins.isdigit() else None
                    AcademyAttendance.objects.update_or_create(
                        student=s, date=hazri_date, shift=hazri_shift,
                        defaults={'status': val, 'late_minutes': late_mins, 'marked_by': request.user, 'locked': True}
                    )
                    # ── AUTO-FINE ENGINE ──
                    try:
                        from exams.finance_helpers import sync_auto_fines
                        sync_auto_fines(s, hazri_date, hazri_shift, val, late_mins, request.user)
                    except Exception as e:
                        print(f"Auto-fine error for {s.code}: {e}")
            messages.success(request, f"Hazri saved for {hazri_date.strftime('%d %b %Y')}.")
            return redirect(reverse('portal-teacher-control') + f"?tab=hazri&hazri_date={hazri_date.isoformat()}&hazri_shift={hazri_shift}")

        # ── 4. SETTINGS ──
        elif action == 'update_engine':
            engine_cfg = GlobalStudyConfig.objects.first() or GlobalStudyConfig.objects.create()
            engine_cfg.is_active = request.POST.get('is_active') == 'on'
            start_date_str = request.POST.get('start_date')
            if start_date_str:
                engine_cfg.start_date = _date.fromisoformat(start_date_str)
            engine_cfg.current_day = int(request.POST.get('current_day', 1))
            engine_cfg.save()
            messages.success(request, "Engine Config updated.")
            return redirect('portal-teacher-control')

        elif action == 'update_academy':
            acad = AcademySetting.load()
            acad.late_fine_per_minute = float(request.POST.get('late_fine_per_minute', 5.00))
            acad.points_per_late_minute = int(request.POST.get('points_per_late_minute', 1))
            acad.pin_required = request.POST.get('pin_required') == 'on'
            acad.portal_enabled = request.POST.get('portal_enabled') == 'on'
            acad.discipline_student_access_enabled = request.POST.get('discipline_student_access_enabled') == 'on'
            acad.discipline_delegation_max_hours = int(request.POST.get('discipline_delegation_max_hours', 168))
            acad.portal_mode = request.POST.get('portal_mode', 'AUTO')
            acad.save()
            messages.success(request, "Academy Settings updated.")
            return redirect('portal-teacher-control')

        elif action == 'update_discipline':
            disc = DisciplineSettings.load()
            disc.aesthetic_points_per_unit = int(request.POST.get('aesthetic_points_per_unit', 10))
            disc.minutes_per_unit = int(request.POST.get('minutes_per_unit', 3))
            disc.daily_point_cap = int(request.POST.get('daily_point_cap', 50))
            disc.weekly_point_cap = int(request.POST.get('weekly_point_cap', 150))
            disc.save()
            messages.success(request, "Discipline Settings updated.")
            return redirect('portal-teacher-control')

        elif action == 'approve_edit':
            req_id = request.POST.get('req_id')
            req = QuestionEditRequest.objects.filter(id=req_id).first()
            if req:
                q = req.question
                if hasattr(req, 'new_question_text') and req.new_question_text:
                    q.question_text = req.new_question_text
                if hasattr(req, 'new_model_answer') and req.new_model_answer:
                    q.model_answer = req.new_model_answer
                q.save()
                req.status = 'APPROVED'
                req.save()
                messages.success(request, f"Question Q{q.id} updated.")
            return redirect('portal-teacher-control')

    # ── FETCH DATA FOR UI ──
    lookup_student = None
    exam_balance = 0
    disc_balance = 0
    lookup_code = request.session.get('lookup_student_code')
    if lookup_code:
        lookup_student = Student.objects.filter(code=lookup_code).first()
        if lookup_student:
            exam_balance = CreditEvent.objects.filter(student=lookup_student).aggregate(total=Sum('points'))['total'] or 0
            disc_obj = AcademyPoints.objects.filter(student__linked_code=lookup_student.code).first()
            disc_balance = disc_obj.balance if disc_obj else 0

    all_students = Student.objects.filter(is_active=True).order_by('code')
    
    # --- BACKEND FILTERING ---
    filter_class = request.GET.get('filter_class', '').strip()
    if filter_class and filter_class != 'all':
        all_students = all_students.filter(student_class=filter_class)
    all_classes = Student.objects.values_list('student_class', flat=True).distinct().order_by('student_class')

    # Delegations
    delegatable_pages = []
    
    # ADD DIARY KEYS AS A DELEGATABLE PAGE
    delegatable_pages.append(('Diary System', [
        {'label': 'AI Diary Upload (Student)', 'url': '/api/portal/diary-upload/', 'desc': 'Upload AI-graded diary work'},
    ]))

    for group_name, items in (TEACHER_MENU + STUDENT_MENU):
        group_items = []
        for label, url, desc in items:
            if 'delegations' in url:
                continue
            # Map old attendance to new Hazri
            if url == '/discipline/attendance/':
                url = '/api/portal/teacher/control/?tab=hazri'
                label = label.replace('Attendance', 'Hazri') if 'Attendance' in label else label
            group_items.append({'label': label, 'url': url, 'desc': desc})
        if group_items:
            delegatable_pages.append((group_name, group_items))
    student_user_ids = Student.objects.filter(is_active=True, student_user__isnull=False).values_list('student_user_id', flat=True)
    delegation_users = get_user_model().objects.filter(id__in=student_user_ids).order_by('first_name', 'username')
    active_delegations = TaskDelegation.objects.filter(expires_at__gt=timezone.now()).select_related('assignee').order_by('-created_at')

    # Hazri
    hazri_date_str = request.GET.get('hazri_date', '')
    try:
        hazri_date = _date.fromisoformat(hazri_date_str) if hazri_date_str else _date.today()
    except Exception:
        hazri_date = _date.today()
    hazri_shift = request.GET.get('hazri_shift', 'M')
    hazri_students = AcademyStudent.objects.filter(active=True).order_by('grade', 'code')
    existing_att = {a.student_id: a for a in AcademyAttendance.objects.filter(date=hazri_date, shift=hazri_shift, student__in=hazri_students)}
    hazri_rows = []
    for s in hazri_students:
        rec = existing_att.get(s.id)
        hazri_rows.append({'student': s, 'status': rec.status if rec else 'P', 'late_minutes': rec.late_minutes if rec else '', 'locked': rec.locked if rec else False})

    # Matrix
    matrix_date_str = request.GET.get('date', '')
    try:
        matrix_date = _date.fromisoformat(matrix_date_str) if matrix_date_str else _date.today()
    except Exception:
        matrix_date = _date.today()
    if 'subjects_submitted' in request.GET:
        request.session['chw_active_subjects'] = request.GET.getlist('subjects')
    active_subjects = request.session.get('chw_active_subjects') or [s[0] for s in SUBJECTS]
    active_subject_objs = [s for s in SUBJECTS if s[0] in active_subjects] or SUBJECTS[:1]
    active_subjects = [s[0] for s in active_subject_objs]

    matrix_students = AcademyStudent.objects.filter(active=True).order_by("grade", "code")
    existing_hw = {}
    for r in ClassHomeworkRecord.objects.filter(date=matrix_date, student__in=matrix_students, subject__in=active_subjects):
        existing_hw.setdefault(r.student_id, {})[r.subject] = r
    matrix_rows = []
    for s in matrix_students:
        student_recs = existing_hw.get(s.id, {})
        row_data = {"student": s, "records": {}}
        row_points = 0
        for subj in active_subjects:
            rec = student_recs.get(subj)
            row_data["records"][subj] = {
                "star": rec.star_rating if rec else 0, 
                "handwriting": rec.handwriting_done if rec else False,
                "memorization": rec.memorization_done if rec else False, 
                "understanding": rec.understanding_done if rec else False, 
                "homework": rec.homework_done if rec else False,
                "classwork": rec.classwork_done if rec else False, 
                "points": rec.points if rec else 0, 
                "saved": rec is not None,
            }
            row_points += (rec.points if rec else 0)
        row_data["total_points"] = row_points
        matrix_rows.append(row_data)
    assignments = DiaryAssignment.objects.filter(date=matrix_date, student__in=matrix_students)
    assignments_by_student = {}
    for a in assignments:
        assignments_by_student.setdefault(a.student_id, []).append(a)

    # Settings & Misc
    engine_cfg = GlobalStudyConfig.objects.first()
    acad_cfg = AcademySetting.load()
    disc_cfg = DisciplineSettings.load()
    open_tickets = SupportTicket.objects.filter(status__in=['OPEN', 'STUDENT_RESPONDED']).order_by('-created_at')[:5] if hasattr(SupportTicket, 'objects') else []

    if 'grant_nonce' not in request.session:
        request.session['grant_nonce'] = uuid.uuid4().hex[:16]

    return render(request, 'exams/portal_teacher_control.html', {
        'grant_nonce': request.session['grant_nonce'],
        'all_students': all_students,
        'all_classes': all_classes,
        'lookup_student': lookup_student,
        'exam_balance': exam_balance,
        'disc_balance': disc_balance,
        'delegation_users': delegation_users,
        'is_delegated': is_delegated,
        'has_diary_delegation': has_diary_delegation,
        'default_tab': 'hazri' if is_delegated else request.GET.get('tab', 'bulk'),
        'delegatable_pages': delegatable_pages,
        'delegation_classes': STANDARD_CLASSES,
        'active_delegations': active_delegations,
        'hazri_rows': hazri_rows,
        'hazri_date': hazri_date,
        'hazri_shift': hazri_shift,
        'matrix_rows': matrix_rows,
        'matrix_date': matrix_date,
        'all_subjects': SUBJECTS,
        'active_subjects': active_subjects,
        'active_subject_objs': active_subject_objs,
        'assignments_by_student': assignments_by_student,
        'engine_cfg': engine_cfg,
        'acad_cfg': acad_cfg,
        'disc_cfg': disc_cfg,
        'open_tickets': open_tickets,
    })

@login_required
def get_student_questions(request):
    from exams.models import Student, StudentQuestionLock
    from django.http import JsonResponse
    code = request.GET.get('student_code')
    # IDOR FIX: staff/superuser OR self only
    if request.user.is_staff or request.user.is_superuser:
        student = Student.objects.filter(code=code).first()
    else:
        student = Student.objects.filter(code=code, student_user=request.user).first()
    if not student:
        return JsonResponse({'questions': []})
    
    from exams.services.pipeline_state import get_question_stage
    locks = StudentQuestionLock.objects.filter(student=student, is_active=True).select_related('question')
    q_data = []
    for lock in locks:
        try:
            stage = get_question_stage(student, lock.question)['current_stage']
        except Exception:
            stage = 'UNKNOWN'
        q_data.append({
            'id': lock.question.id, 
            'text': lock.question.question_text[:40],
            'stage': stage
        })
    return JsonResponse({'questions': q_data})


@login_required
def next_day_v3(request):
    """Switch to tomorrow's mission (additive — today's locks stay active).

    Calls get_daily_mission_questions() to materialise the target day's
    StudentQuestionLock rows (is_active=True). Without this, the daily view
    — which reads ONLY active locks — can never surface the next day's work.
    """
    if request.method != 'POST':
        return redirect('portal-daily-mission-v3')
    student = _current_student(request)
    if not student:
        return redirect('portal-dashboard')

    current = request.session.get('mission_override', 0)

    # Base day from the engine clock (fallback 1 if engine not started)
    from exams.models import EngineState
    engine = EngineState.objects.filter(id=1).first()
    try:
        base_day = engine.get_current_day() if (engine and engine.has_started) else 1
    except Exception:
        base_day = 1
    target_day = base_day + current + 1

    # Materialise the target day's mission (idempotent create of active locks)
    created = 0
    try:
        mission = get_daily_mission_questions(
            student, pace_per_book=3, curriculum_day=target_day)
        for _book, qids in mission.items():
            created += len(qids)
    except Exception as e:
        messages.error(request, f'Could not load Day {target_day}: {e}')
        return redirect('portal-daily-mission-v3')

    # Anchor the override to this base day so the daily view does not reset it
    request.session['mission_base_day'] = base_day
    request.session['mission_override'] = current + 1
    request.session.pop('mission_data', None)
    request.session.pop('mission_day', None)

    messages.success(
        request,
        f'📅 Switched to Day {target_day}. {created} new questions added. '
        f"Today's work stays available."
    )
    return redirect('portal-daily-mission-v3')


@login_required
def reset_day_v3(request):
    """Return to today's mission."""
    if request.method != 'POST':
        return redirect('portal-daily-mission-v3')
    student = _current_student(request)
    if not student:
        return redirect('portal-dashboard')
    request.session['mission_override'] = 0
    request.session.pop('mission_data', None)
    request.session.pop('mission_day', None)
    messages.success(request, '← Back to today.')
    return redirect('portal-daily-mission-v3')


# ═══════════════════════════════════════════════════════════
# 180-Day Reading Calendar
# Standards: W3C HTML5 table, WAI-ARIA Grid, ISO 8601,
#            progressive enhancement (form POST), Bootstrap 4
# ═══════════════════════════════════════════════════════════

COURSE_TOTAL_DAYS = 180


@login_required

def portal_diary_calendar(request):
    """150-day diary calendar with selected day task view."""
    from datetime import date, timedelta
    from calendar import month_name, monthrange
    from django.utils import timezone
    from exams.models import EngineState
    from discipline.models import ClassHomeworkRecord, DiaryAssignment
    from academy.models import AcademyStudent
    from django.db.models import Q

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

    acad = AcademyStudent.objects.filter(linked_code=student.code, active=True).first()

    engine = EngineState.objects.filter(id=1).first()
    try:
        current_day = engine.get_current_day() if (engine and engine.has_started) else 1
    except Exception:
        current_day = 1
    current_day = max(1, min(COURSE_TOTAL_DAYS, current_day))

    today = timezone.localdate()
    day_1_date = today - timedelta(days=current_day - 1)

    # 1. Fetch days that have tasks
    diary_dates = set()
    if acad:
        # Old grid records
        recs = ClassHomeworkRecord.objects.filter(student=acad).filter(
            Q(star_rating__gt=0) | ~Q(diary_text='')
        ).values_list('date', flat=True).distinct()
        
        # New Master Paste assignments
        assigns = DiaryAssignment.objects.filter(
            student=acad
        ).values_list('date', flat=True).distinct()

        diary_dates.update(recs)
        diary_dates.update(assigns)

    # 2. Handle Selected Date
    selected_date_str = request.GET.get('date')
    selected_date = None
    selected_tasks = []
    legacy_records = []

    if selected_date_str:
        try:
            selected_date = date.fromisoformat(selected_date_str)
            
            # Fetch exact questions from Master Paste
            selected_tasks = DiaryAssignment.objects.filter(
                student__linked_code=student.code, date=selected_date
            ).order_by('subject')
            
            # Fetch legacy handwritten notes
            if acad:
                legacy_records = ClassHomeworkRecord.objects.filter(
                    student=acad, date=selected_date, diary_visible=True
                ).exclude(diary_text='')

        except ValueError:
            pass

    day_records = {}
    completed_count = 0
    for n in range(1, COURSE_TOTAL_DAYS + 1):
        d = day_1_date + timedelta(days=n - 1)
        if d in diary_dates:
            status = 'completed'
            completed_count += 1
        elif n < current_day:
            status = 'missed'
        elif n == current_day:
            status = 'today'
        else:
            status = 'upcoming'
        
        day_records[d] = {
            'day': n, 'date': d, 'status': status,
        }

    first_date = day_1_date
    last_date = day_1_date + timedelta(days=COURSE_TOTAL_DAYS - 1)
    months = []
    y, m = first_date.year, first_date.month
    end_y, end_m = last_date.year, last_date.month
    while (y, m) <= (end_y, end_m):
        first_of_month = date(y, m, 1)
        num_days = monthrange(y, m)[1]
        
        # Build weeks (Sunday first)
        first_weekday = (first_of_month.weekday() + 1) % 7
        weeks = []
        week = [None] * first_weekday
        
        for day_num in range(1, num_days + 1):
            d = date(y, m, day_num)
            cell = day_records.get(d)
            week.append(cell)
            if len(week) == 7:
                weeks.append(week)
                week = []
        if week:
            week.extend([None] * (7 - len(week)))
            weeks.append(week)
            
        months.append({
            'name': month_name[m],
            'year': y,
            'weeks': weeks
        })
        
        if m == 12:
            y, m = y + 1, 1
        else:
            m += 1

    return render(request, 'exams/portal_diary_calendar.html', {
        'student': student,
        'total_days': COURSE_TOTAL_DAYS,
        'day_1_date': day_1_date,
        'current_day': current_day,
        'completed_count': completed_count,
        'past_days': current_day - 1,
        'months': months,
        'selected_date': selected_date,
        'selected_tasks': selected_tasks,
        'legacy_records': legacy_records,
    })

@login_required
def portal_mission_calendar(request):
    """180-day reading calendar — maps each curriculum day to a real date.

    Anchor: EngineState.get_current_day() is the single source of truth.
    If today is Day N, then Day 1 was (N-1) days ago; Day K is on
    (K-1) days after Day 1.
    """
    from datetime import date, timedelta
    from calendar import month_name, monthrange
    from django.utils import timezone
    from exams.models import EngineState
    from exams.models_day_mission import StudentDayMission

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

    engine = EngineState.objects.filter(id=1).first()
    try:
        current_day = engine.get_current_day() if (engine and engine.has_started) else 1
    except Exception:
        current_day = 1
    current_day = max(1, min(COURSE_TOTAL_DAYS, current_day))

    today = timezone.localdate()
    day_1_date = today - timedelta(days=current_day - 1)

    mission_days = set(
        StudentDayMission.objects.filter(student=student)
        .values_list('day_number', flat=True).distinct()
    )
    override = request.session.get('mission_override', 0)
    viewing_day = current_day + override

    # Build date -> day record map
    day_records = {}
    completed_count = 0
    for n in range(1, COURSE_TOTAL_DAYS + 1):
        d = day_1_date + timedelta(days=n - 1)
        if n < current_day:
            status = 'completed' if n in mission_days else 'missed'
            if status == 'completed':
                completed_count += 1
        elif n == current_day:
            status = 'today'
        else:
            status = 'upcoming'
        day_records[d] = {
            'day': n, 'date': d, 'status': status,
            'viewing': (n == viewing_day),
        }

    # Build month-by-month grids (Sunday-first, W3C/WAI standard)
    first_date = day_1_date
    last_date = day_1_date + timedelta(days=COURSE_TOTAL_DAYS - 1)
    months = []
    y, m = first_date.year, first_date.month
    end_y, end_m = last_date.year, last_date.month
    while (y, m) <= (end_y, end_m):
        first_of_month = date(y, m, 1)
        num_days = monthrange(y, m)[1]
        first_weekday_sun = (first_of_month.weekday() + 1) % 7  # Sunday = 0
        cells = [None] * first_weekday_sun
        for dn in range(1, num_days + 1):
            cells.append(day_records.get(date(y, m, dn)))
        while len(cells) % 7 != 0:
            cells.append(None)
        weeks = [cells[i:i + 7] for i in range(0, len(cells), 7)]
        months.append({'year': y, 'month': m, 'name': month_name[m], 'weeks': weeks})
        if m == 12:
            y, m = y + 1, 1
        else:
            m += 1

    # ─── PHASE 2: Fetch daily codes per day ───
    from exams.models import StudentDailyCode
    from exams.models_day_mission import StudentDayMission
    from exams.models import EngineState as _ES_cal
    
    _engine_cal = _ES_cal.objects.filter(id=1).first()
    codes_by_day = {}
    submitted_by_day = {}
    if _engine_cal and _engine_cal.start_date:
        # Fetch all daily codes for this student
        all_codes = StudentDailyCode.objects.filter(student=student)
        for row in all_codes:
            day_num = (row.date - _engine_cal.start_date).days + 1
            if day_num < 1:
                continue
            payload = row.per_book_codes or {}
            
            # PHASE 2d: Determine visibility for this day
            # Rule: explicit teacher choice > default past=visible, today/future=hidden
            from exams.models_day_mission import DailyCodeVisibility as _DCV2
            from datetime import timedelta as _td2
            _day_date = _engine_cal.start_date + _td2(days=day_num - 1)
            _vis_row = _DCV2.objects.filter(date=_day_date).first()
            _is_visible = bool(_vis_row and _vis_row.is_visible)
            
            _m_vis = bool(_vis_row and getattr(_vis_row, 'morning_visible', _vis_row.is_visible if _vis_row else False))
            _e_vis = bool(_vis_row and getattr(_vis_row, 'evening_visible', _vis_row.is_visible if _vis_row else False))
            codes_by_day[day_num] = {
                'morning': payload.get('morning', {}) if _m_vis else {},
                'evening': payload.get('evening', {}) if _e_vis else {},
                'is_visible': (_m_vis or _e_vis),
            }
        
        # Fetch submission status per day (to show if locked)
        from exams.models import AttemptLog
        sdm_by_day = {}
        for sdm in StudentDayMission.objects.filter(student=student):
            sdm_by_day.setdefault(sdm.day_number, []).append(sdm.question_id)
        
        for day_num, qids in sdm_by_day.items():
            attempted_count = AttemptLog.objects.filter(
                student=student, question_id__in=qids, cancelled_at__isnull=True
            ).count()
            submitted_by_day[day_num] = attempted_count
    
    # ─── END PHASE 2 ───

    # PHASE 4d: Fetch day attempt policies for badge display
    from exams.models_day_mission import DayAttemptPolicy as _DAP4
    policy_by_day = {}
    for pol in _DAP4.objects.all():
        if pol.status != 'LOCKED':
            _dn = (pol.date - _engine_cal.start_date).days + 1 if _engine_cal and _engine_cal.start_date else None
            if _dn and _dn > 0:
                policy_by_day[_dn] = pol.status

    return render(request, 'exams/portal_mission_calendar.html', {
        'codes_by_day': codes_by_day,
        'submitted_by_day': submitted_by_day,
        'policy_by_day': policy_by_day,
        'student': student,
        'current_day': current_day,
        'total_days': COURSE_TOTAL_DAYS,
        'day_1_date': day_1_date,
        'today': today,
        'months': months,
        'viewing_day': viewing_day,
        'completed_count': completed_count,
        'past_days': max(0, current_day - 1),
        'points_balance': _current_balance(student),
    })


@login_required
def select_mission_day(request, day):
    """POST: jump to any curriculum day and activate its locks (idempotent)."""
    if request.method != 'POST':
        return redirect('portal-mission-calendar')
    student = _current_student(request)
    if not student:
        return redirect('portal-dashboard')

    from exams.models import EngineState
    from exams.services.daily_mission_engine import get_daily_mission_questions

    if day < 1 or day > COURSE_TOTAL_DAYS:
        messages.error(request, f'Day must be between 1 and {COURSE_TOTAL_DAYS}.')
        return redirect('portal-mission-calendar')

    engine = EngineState.objects.filter(id=1).first()
    try:
        base_day = engine.get_current_day() if (engine and engine.has_started) else 1
    except Exception:
        base_day = 1

    created = 0
    try:
        mission = get_daily_mission_questions(student, curriculum_day=day)
        for _book, qids in mission.items():
            created += len(qids)
    except Exception as e:
        messages.error(request, f'Could not load Day {day}: {e}')
        return redirect('portal-mission-calendar')

    request.session['mission_base_day'] = base_day
    request.session['mission_override'] = day - base_day
    request.session.pop('mission_data', None)
    request.session.pop('mission_day', None)

    messages.success(request, f'📅 Day {day} loaded. {created} new questions added.')
    return redirect('portal-daily-mission-v3')


@login_required
def completion_calendar(request):
    """180-day dual-timeline calendar: projected date vs actual completion date.

    Projected: Day 1 = today - (current_day - 1), then walk teaching days
               only (skip NonTeachingDay).
    Actual:    StudentDayCompletion.completed_at per day.
    """
    from datetime import date, timedelta
    from calendar import month_name, monthrange
    from django.utils import timezone
    from exams.models import EngineState, NonTeachingDay, StudentDayCompletion
    from exams.models_day_mission import StudentDayMission

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

    engine = EngineState.objects.filter(id=1).first()
    try:
        current_day = engine.get_current_day() if (engine and engine.has_started) else 1
    except Exception:
        current_day = 1
    current_day = max(1, min(COURSE_TOTAL_DAYS, current_day))

    today = timezone.localdate()
    day_1_date = today - timedelta(days=current_day - 1)

    # Non-teaching days (holidays, exam weeks, sick days recorded school-wide)
    nt_dates = set(NonTeachingDay.objects.values_list('date', flat=True))

    # Projection: Day N = the N-th *teaching* day starting from day_1_date
    projected = {}
    cursor = day_1_date
    n = 1
    while n <= COURSE_TOTAL_DAYS:
        if cursor not in nt_dates:
            projected[n] = cursor
            n += 1
        cursor += timedelta(days=1)

    completions = {r.day_number: r for r in
                   StudentDayCompletion.objects.filter(student=student)}
    mission_days = set(StudentDayMission.objects.filter(student=student)
                       .order_by().values_list('day_number', flat=True).distinct())

    # Build per-projected-date cell record
    records = {}
    completed_count = 0
    missed_count = 0
    latest_completion = None  # (day_number, date)
    for n in range(1, COURSE_TOTAL_DAYS + 1):
        pd = projected[n]
        comp = completions.get(n)
        actual_date = comp.completed_at.date() if (comp and comp.completed_at) else None
        if actual_date and (latest_completion is None
                            or actual_date > latest_completion[1]):
            latest_completion = (n, actual_date)

        if comp and comp.status == 'COMPLETED':
            status = 'completed'
            completed_count += 1
        elif pd < today and n in mission_days:
            status = 'missed'
            missed_count += 1
        elif pd < today and n not in mission_days:
            status = 'not_started'
        elif pd == today:
            status = 'today'
        else:
            status = 'upcoming'

        records[pd] = {
            'day': n,
            'proj_date': pd,
            'actual_date': actual_date,
            'status': status,
            'is_today': (pd == today),
            'lag_days': (actual_date - pd).days if actual_date else None,
            'is_holiday': pd in nt_dates,
        }

    # Month grids
    first_date = day_1_date
    last_date = projected[COURSE_TOTAL_DAYS]
    months = []
    y, m = first_date.year, first_date.month
    end_y, end_m = last_date.year, last_date.month
    while (y, m) <= (end_y, end_m):
        first_of_month = date(y, m, 1)
        num_days = monthrange(y, m)[1]
        first_weekday_sun = (first_of_month.weekday() + 1) % 7
        cells = [None] * first_weekday_sun
        for dn in range(1, num_days + 1):
            cells.append(records.get(date(y, m, dn)))
        while len(cells) % 7 != 0:
            cells.append(None)
        weeks = [cells[i:i + 7] for i in range(0, len(cells), 7)]
        months.append({'year': y, 'month': m, 'name': month_name[m], 'weeks': weeks})
        if m == 12:
            y, m = y + 1, 1
        else:
            m += 1

    return render(request, 'exams/completion_calendar.html', {
        'student': student,
        'current_day': current_day,
        'total_days': COURSE_TOTAL_DAYS,
        'day_1_date': day_1_date,
        'today': today,
        'months': months,
        'completed_count': completed_count,
        'missed_count': missed_count,
        'latest_completion': latest_completion,
        'points_balance': _current_balance(student),
    })



# ═══════════════════════════════════════════════════════════
# Teacher Completion Matrix — all students × all days in one grid
# Read-only. Access: is_staff or is_superuser only.
# ═══════════════════════════════════════════════════════════

@login_required
def teacher_completion_matrix(request):
    """Attendance-register-style view: rows = students, cols = curriculum days.

    Each cell state:
      done   = StudentDayCompletion.status=COMPLETED
      missed = day has StudentDayMission rows but no completion, and projected date is past
      future = projected date is today or later
      na     = no mission rows for that day
    """
    from datetime import timedelta
    from django.utils import timezone
    from exams.models import (
        Student, EngineState, NonTeachingDay, StudentDayCompletion,
    )
    from exams.models_day_mission import StudentDayMission
    from django.db.models import Max

    if not (request.user.is_staff or request.user.is_superuser):
        return redirect('portal-dashboard')

    # Class filter
    all_classes = list(
        Student.objects.filter(is_active=True)
        .values_list('student_class', flat=True).distinct().order_by('student_class')
    )
    selected_class = request.GET.get('class', '9')
    if selected_class not in all_classes and all_classes:
        selected_class = all_classes[0]

    students = Student.objects.filter(
        is_active=True, student_class=selected_class,
    ).order_by('code')

    # Determine day range
    max_day_data = (
        StudentDayMission.objects
        .filter(student__in=students)
        .aggregate(m=Max('day_number'))['m'] or 0
    )
    engine = EngineState.objects.filter(id=1).first()
    try:
        current_day = engine.get_current_day() if (engine and engine.has_started) else 1
    except Exception:
        current_day = 1
    display_days = min(180, max(current_day + 10, max_day_data, 10))
    days = list(range(1, display_days + 1))

    # Projected date per curriculum day (skips NonTeachingDay)
    today = timezone.localdate()
    nt_dates = set(NonTeachingDay.objects.values_list('date', flat=True))
    day_1_date = today - timedelta(days=current_day - 1)
    projected = {}
    cursor = day_1_date
    n = 1
    while n <= display_days:
        if cursor not in nt_dates:
            projected[n] = cursor
            n += 1
        cursor += timedelta(days=1)

    # Load completions + mission-days in bulk
    completions = {}
    for row in StudentDayCompletion.objects.filter(
        student__in=students, status='COMPLETED'
    ).values_list('student_id', 'day_number'):
        completions.setdefault(row[0], set()).add(row[1])

    mission_days = {}
    for s_id, d in StudentDayMission.objects.filter(
        student__in=students
    ).values('student_id', 'day_number').distinct().values_list('student_id', 'day_number'):
        mission_days.setdefault(s_id, set()).add(d)

    # Build rows
    matrix_rows = []
    total_done = 0
    for s in students:
        done_set = completions.get(s.id, set())
        mission_set = mission_days.get(s.id, set())
        cells = []
        for d in days:
            pd = projected.get(d)
            if d in done_set:
                state, label, title = 'done', '✓', f'D{d} — completed'
            elif pd and pd < today and d in mission_set:
                state, label, title = 'missed', '✗', f'D{d} — missed'
            elif pd and pd < today:
                state, label, title = 'missed', '✗', f'D{d} — past, no mission'
            elif d in mission_set:
                state, label, title = 'future', '·', f'D{d} — upcoming (has mission)'
            else:
                state, label, title = 'na', '·', f'D{d} — no mission'
            cells.append({
                'day': d, 'state': state, 'label': label,
                'date': pd, 'title': title,
            })
        done_count = len(done_set)
        total_done += done_count
        matrix_rows.append({
            'student': s, 'cells': cells,
            'done_count': done_count,
            'mission_count': len(mission_set),
        })

    return render(request, 'exams/teacher_completion_matrix.html', {
        'all_classes': all_classes,
        'selected_class': selected_class,
        'days': days,
        'matrix_rows': matrix_rows,
        'total_students': len(matrix_rows),
        'total_done': total_done,
        'current_day': current_day,
        'display_days': display_days,
    })



# ═══════════════════════════════════════════════════════════
# Exam Token Queue (T3) — Student-facing views
# ═══════════════════════════════════════════════════════════

@login_required
def portal_exam_token_status(request):
    """Show student's current token + queue position."""
    student = _current_student(request)
    if not student:
        return redirect('portal-dashboard')
    from exams.services import exam_queue
    from exams.models import GlobalStudyConfig
    token, ahead = exam_queue.get_queue_for_student(student)
    snapshot = exam_queue.get_queue_snapshot()
    cfg = GlobalStudyConfig.objects.first()
    # Approved retake days for token page
    from exams.models import RetakeRequest as _RR_token
    _approved_days = sorted(set(
        _RR_token.objects.filter(student=student, status='APPROVED')
        .values_list('day_number', flat=True)
    ))
    _latest_retake_day = _approved_days[-1] if _approved_days else None

    return render(request, 'exams/portal_exam_token_status.html', {
        'student': student,
        'token': token,
        'ahead': ahead,
        'total_pending': snapshot['pending'].count(),
        'batch_size': cfg.exam_batch_size if cfg else 1,
        'grace_minutes': cfg.exam_grace_minutes if cfg else 15,
        'approved_retake_days': _approved_days,
        'latest_retake_day': _latest_retake_day,
    })


@login_required
def portal_exam_token_request(request):
    """Issue 1 or N tokens (POST param 'count', default 1, max 10)."""
    if request.method != 'POST':
        return redirect('portal-exam-token-status')
    student = _current_student(request)
    if not student:
        return redirect('portal-dashboard')
    from exams.services import exam_queue
    try:
        count = int(request.POST.get('count', 1))
    except (ValueError, TypeError):
        count = 1
    count = max(1, min(10, count))

    created, remaining, error = exam_queue.issue_multiple_tokens(student, count)
    if error:
        messages.error(request, error)
    elif created:
        nums = ', '.join(f'#{t.token_number}' for t in created)
        messages.success(request, f'{len(created)} token(s) issued: {nums}. Wait for teacher to call you.')
    else:
        messages.info(request, 'No tokens created.')
    return redirect('portal-exam-token-status')


@login_required
def portal_exam_token_cancel(request):
    """Cancel the student's pending token."""
    if request.method != 'POST':
        return redirect('portal-exam-token-status')
    student = _current_student(request)
    if not student:
        return redirect('portal-dashboard')
    from exams.services import exam_queue
    token = exam_queue.cancel_token(student)
    if token:
        messages.success(request, f'Token #{token.token_number} cancelled.')
    else:
        messages.info(request, 'No pending token to cancel.')
    return redirect('portal-exam-token-status')



# ═══════════════════════════════════════════════════════════
# Exam Token Queue (T4) — Teacher panel
# ═══════════════════════════════════════════════════════════

@login_required
def teacher_exam_queue(request):
    """Teacher queue dashboard for today."""
    if not (request.user.is_staff or request.user.is_superuser):
        messages.error(request, 'Access denied.')
        return redirect('portal-dashboard')
    from exams.services import exam_queue
    from exams.models import GlobalStudyConfig
    from collections import defaultdict
    snapshot = exam_queue.get_queue_snapshot()

    # Group pending tokens by student for the quick-approve panel
    pending_by_student = defaultdict(list)
    for t in snapshot['pending']:
        pending_by_student[t.student].append(t)

    cfg = GlobalStudyConfig.objects.first()
    return render(request, 'exams/teacher_exam_queue.html', {
        'snapshot': snapshot,
        'pending_by_student': dict(pending_by_student),
        'batch_size': cfg.exam_batch_size if cfg else 1,
        'grace_minutes': cfg.exam_grace_minutes if cfg else 15,
    })


@login_required
def teacher_exam_call_next(request):
    """Call the next N students (N = batch_size or override)."""
    if request.method != 'POST':
        return redirect('teacher-exam-queue')
    if not (request.user.is_staff or request.user.is_superuser):
        messages.error(request, 'Access denied.')
        return redirect('portal-dashboard')
    from exams.services import exam_queue
    from exams.models import GlobalStudyConfig
    cfg = GlobalStudyConfig.objects.first()
    default_batch = cfg.exam_batch_size if cfg else 1
    try:
        count = int(request.POST.get('count', default_batch))
    except (ValueError, TypeError):
        count = default_batch
    count = max(1, min(count, 50))
    called = exam_queue.call_next(count=count, user=request.user)
    if called:
        nums = ', '.join(f'#{t.token_number}' for t in called)
        messages.success(request, f'Called {len(called)} student(s): {nums}')
    else:
        messages.info(request, 'No pending tokens to call.')
    return redirect('teacher-exam-queue')


@login_required
@login_required
def teacher_exam_approve_student(request):
    """Approve ALL pending tokens for ONE student → CALLED."""
    if request.method != 'POST':
        return redirect('teacher-exam-queue')
    if not (request.user.is_staff or request.user.is_superuser):
        messages.error(request, 'Access denied.')
        return redirect('portal-dashboard')

    from exams.services import exam_queue
    from exams.models import Student

    student_code = (request.POST.get('student_code') or '').strip()
    if not student_code:
        messages.error(request, 'Student code required.')
        return redirect('teacher-exam-queue')

    student = Student.objects.filter(code__iexact=student_code, is_active=True).first()
    if not student:
        messages.error(request, f'Student {student_code} not found.')
        return redirect('teacher-exam-queue')

    count = exam_queue.approve_student_tokens(student, user=request.user)
    if count:
        messages.success(request, f'✅ Approved {count} token(s) for {student.code} · {student.name}.')
    else:
        messages.info(request, f'No pending tokens for {student.code}.')
    return redirect('teacher-exam-queue')


def teacher_exam_call_all(request):
    """Call ALL pending tokens in batches of 50. Bypasses batch_size.

    Loops until no PENDING tokens remain today. Safety cap at 1000.
    """
    if request.method != 'POST':
        return redirect('teacher-exam-queue')
    if not (request.user.is_staff or request.user.is_superuser):
        messages.error(request, 'Access denied.')
        return redirect('portal-dashboard')
    from exams.services import exam_queue
    from exams.models import ExamToken
    from django.utils import timezone

    today = timezone.localdate()
    total_called = 0
    safety_cap = 1000

    while total_called < safety_cap:
        remaining = ExamToken.objects.filter(date=today, status='PENDING').count()
        if remaining == 0:
            break
        batch = exam_queue.call_next(count=min(remaining, 50), user=request.user)
        if not batch:
            break
        total_called += len(batch)

    if total_called:
        messages.success(
            request,
            f'✅ Called ALL pending: {total_called} token(s) → CALLED. '
            f'Remaining pending: {ExamToken.objects.filter(date=today, status="PENDING").count()}'
        )
    else:
        messages.info(request, 'No pending tokens to call.')
    return redirect('teacher-exam-queue')


@login_required
def teacher_exam_mark_started(request):
    """Mark a CALLED token as IN_PROGRESS."""
    if request.method != 'POST':
        return redirect('teacher-exam-queue')
    if not (request.user.is_staff or request.user.is_superuser):
        messages.error(request, 'Access denied.')
        return redirect('portal-dashboard')
    from exams.services import exam_queue
    from exams.models import ExamToken
    token_id = request.POST.get('token_id')
    token = ExamToken.objects.filter(id=token_id).first()
    if not token:
        messages.error(request, 'Token not found.')
        return redirect('teacher-exam-queue')
    result = exam_queue.mark_in_progress(token, user=request.user)
    if result:
        messages.success(request, f'Token #{token.token_number} started.')
    else:
        messages.error(request, f'Cannot start token #{token.token_number} — wrong status.')
    return redirect('teacher-exam-queue')


@login_required
def teacher_exam_complete(request):
    """Mark an IN_PROGRESS token as COMPLETED."""
    if request.method != 'POST':
        return redirect('teacher-exam-queue')
    if not (request.user.is_staff or request.user.is_superuser):
        messages.error(request, 'Access denied.')
        return redirect('portal-dashboard')
    from exams.services import exam_queue
    from exams.models import ExamToken
    token_id = request.POST.get('token_id')
    token = ExamToken.objects.filter(id=token_id).first()
    if not token:
        messages.error(request, 'Token not found.')
        return redirect('teacher-exam-queue')
    exam_queue.complete_token(token, user=request.user)
    messages.success(request, f'Token #{token.token_number} completed.')
    return redirect('teacher-exam-queue')


@login_required
def teacher_exam_skip(request):
    """Skip a token (mark SKIPPED)."""
    if request.method != 'POST':
        return redirect('teacher-exam-queue')
    if not (request.user.is_staff or request.user.is_superuser):
        messages.error(request, 'Access denied.')
        return redirect('portal-dashboard')
    from exams.services import exam_queue
    from exams.models import ExamToken
    token_id = request.POST.get('token_id')
    reason = (request.POST.get('reason') or '').strip()[:100]
    token = ExamToken.objects.filter(id=token_id).first()
    if not token:
        messages.error(request, 'Token not found.')
        return redirect('teacher-exam-queue')
    exam_queue.skip_token(token, user=request.user, reason=reason or 'manual skip')
    messages.success(request, f'Token #{token.token_number} skipped.')
    return redirect('teacher-exam-queue')



@login_required
def portal_request_question_change(request):
    """Submit a proposed field correction for teacher review."""
    if request.user.is_superuser:
        from exams.models import ModelPaper as _MP_su
        _allowed_classes = list(_MP_su.objects.values_list('student_class', flat=True).distinct())
    else:
        _allowed_classes = _acc_for(_current_student(request))
    if request.method != 'POST':
        return redirect('portal-daily-mission-v3')

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

    qid = request.POST.get('question_id', '')
    field_name = (request.POST.get('field_name') or 'model_answer').strip()
    proposed = (
        request.POST.get('proposed_value')
        or request.POST.get('new_model_answer')
        or ''
    ).strip()
    # The legacy new_question_text field contains the student's reason, not a proposal.
    reason = (
        request.POST.get('reason')
        or request.POST.get('new_question_text')
        or ''
    ).strip()

    if not qid or not proposed or not reason:
        messages.error(request, 'Please provide the suggested correction and explain why it is needed.')
        return redirect('portal-daily-mission-v3')

    from django.db.models import Q as _Q
    _std = (
        ~_Q(paper__code__startswith='SELF-')
        & ~_Q(paper__code__startswith='CUSTOM-')
        & _Q(paper__student_class__in=_allowed_classes)
    )
    _own_self = _Q(paper__code__startswith=f'SELF-{student.code}')
    _own_custom = _Q(paper__code__startswith=f'CUSTOM-{student.code}')
    question = ModelQuestion.objects.filter(
        _std | _own_self | _own_custom
    ).filter(id=qid).first()

    if not question:
        messages.error(request, 'Question not found or not accessible.')
        return redirect('portal-daily-mission-v3')

    result = _queue_question_correction(student, question, field_name, proposed, reason)
    if result == 'created':
        messages.success(request, 'Correction request sent to the teacher for review.')
    elif result == 'duplicate':
        messages.warning(request, 'A correction request for this field is already pending.')
    elif result == 'limit':
        messages.error(request, 'You already have 10 pending correction requests. Please wait for teacher review.')
    elif result == 'unchanged':
        messages.info(request, 'The suggested value is the same as the current value.')
    else:
        messages.error(request, 'The correction could not be submitted. Check the field, suggested value, and reason.')
    return redirect('portal-daily-mission-v3')

@login_required
def reset_selection_v3(request):
    student = None
    try:
        from exams.models import Student
        student = Student.objects.get(student_user=request.user, is_active=True)
    except Exception:
        pass
    if student:
        SKEY = f'select_v3_{student.id}'
        if SKEY in request.session:
            del request.session[SKEY]
    from django.contrib import messages
    messages.success(request, "Selection reset.")
    return redirect('portal-daily-mission-v3')



@login_required
def api_get_pro_learning(request, qid):
    from exams.models_day_mission import QuestionReasoning
    from django.http import JsonResponse
    steps = QuestionReasoning.objects.filter(question_id=qid).values(
        'step_number', 'step_type', 'stage', 'title', 'prompt', 'options', 'correct_answer', 'explanation', 'hint'
    )
    return JsonResponse({'steps': list(steps), 'total': steps.count()})



@login_required
def portal_progress_dashboard(request):
    from exams.models import Student, AttemptLog
    from django.db.models import Avg, Count
    
    student = _current_student(request)
    if not student: return redirect('portal-dashboard')
    
    # Overall Stats
    logs = list(AttemptLog.objects.filter(student=student).order_by('created_at'))
    total_attempts = len(logs)
    overall_avg = sum([a.score for a in logs]) / total_attempts if total_attempts > 0 else 0
    overall_max = sum([float(a.max_score) for a in logs]) / total_attempts if total_attempts > 0 else 5.0
    
    # ── MTSS BRIDGE LOGIC ──
    total_score = sum([float(a.score) for a in logs])
    total_max = sum([float(a.max_score) for a in logs])
    overall_pct = round((total_score / total_max * 100.0), 1) if total_max > 0 else 0.0
    
    trend_delta = 0.0
    if total_attempts >= 6:
        last_3 = logs[-3:]
        prev_3 = logs[-6:-3]
        avg_last = sum([float(a.score)/float(a.max_score)*100 for a in last_3]) / 3
        avg_prev = sum([float(a.score)/float(a.max_score)*100 for a in prev_3]) / 3
        trend_delta = round(avg_last - avg_prev, 1)
        
    # Tier Logic
    tier = 3
    tier_label = "Tier 3: Intensive Support"
    tier_class = "status-box--error"
    tier_icon = "🚨"
    
    if overall_pct >= 60.0 and trend_delta > 5.0:
        tier = 1
        tier_label = "Tier 1: On Track"
        tier_class = "status-box--success"
        tier_icon = "🌟"
    elif overall_pct >= 40.0 and trend_delta >= -5.0:
        tier = 2
        tier_label = "Tier 2: Strategic Support"
        tier_class = "status-box--info"
        tier_icon = "⚠️"

    # Weak KCs Logic
    weak_kcs = []
    seen_codes = set()
    for a in reversed(logs):
        if float(a.score) < (float(a.max_score) * 0.6):
            kc = a.question.kc_code
            if kc and kc not in seen_codes:
                seen_codes.add(kc)
                weak_kcs.append({'code': kc, 'subject': a.question.paper.subject})
                if len(weak_kcs) >= 3: break

    # Subject Breakdown
    subjects = ['Physics', 'Chemistry', 'Biology', 'Mathematics', 'English', 'Urdu', 'Islamiyat', 'Computer Science']
    subject_data = []
    
    for sub in subjects:
        sub_logs = [a for a in logs if a.question.paper.subject == sub]
        if sub_logs:
            avg = sum([float(a.score) for a in sub_logs]) / len(sub_logs)
            avg_max = sum([float(a.max_score) for a in sub_logs]) / len(sub_logs)
            subject_data.append({'name': sub, 'avg': round(avg, 1), 'avg_max': round(avg_max, 1), 'count': len(sub_logs)})
        else:
            subject_data.append({'name': sub, 'avg': 0, 'avg_max': 0, 'count': 0})
            
    return render(request, 'exams/portal_progress_dashboard.html', {
        'student': student,
        'overall_avg': round(overall_avg, 1),
        'overall_max': round(overall_max, 1),
        'total_attempts': total_attempts,
        'subjects': subject_data,
        'tier': tier, 'tier_label': tier_label, 'tier_class': tier_class, 'tier_icon': tier_icon,
        'overall_pct': overall_pct, 'trend_delta': trend_delta, 'weak_kcs': weak_kcs,
    })

def _get_other_subjects(student, exclude_subject):
    """Return list of subjects with attempt counts, excluding the given one."""
    from django.db.models import Count
    rows = (
        AttemptLog.objects
        .filter(student=student)
        .exclude(question__paper__subject=exclude_subject)
        .values('question__paper__subject')
        .annotate(count=Count('id'))
        .order_by('-count')
    )
    return [{'name': r['question__paper__subject'], 'count': r['count']}
            for r in rows if r['question__paper__subject']]


@login_required
def portal_subject_detail(request):
    from exams.models import Student, AttemptLog
    
    student = _current_student(request)
    subject = request.GET.get('subject', 'Physics')
    
    raw_attempts = AttemptLog.objects.filter(
        student=student, 
        question__paper__subject=subject
    ).select_related('question', 'question__paper').order_by('-created_at')
    
    # Filter out Choice copies in Python (so we only show the real direct uploads)
    attempts = []
    for a in raw_attempts:
        is_copy = a.result_json and 'copied_from' in a.result_json
        if not is_copy:
            attempts.append(a)
    
    return render(request, 'exams/portal_detail.html', {
        'student': student,
        'subject': subject,
        'attempts': attempts,
        'current_subject': subject,
        'other_subjects': _get_other_subjects(student, subject),
    })



@login_required
def portal_tree_view(request):
    """Learning Pathway — shift-aware per-day mastery logic.

    Morning shift subjects: PH, CH, {assigned_subject}, TQ (4 pure subjects)
    Evening shift subjects: MA, EN, UR, IS (4 pure subjects)
    Handwriting: tracked separately (via ClassHomeworkRecord).

    Status rules:
      - FUTURE day (> current_day) → 'locked'
      - No codes + no attempts → 'not_started'
      - Attempts exist but neither shift complete → 'in_progress'
      - Morning shift complete, evening pending → 'morning_done'
      - Evening shift complete, morning pending → 'evening_done'
      - Both shifts complete + avg ≥60% + handwriting OK → 'mastered'

    Auto-copied attempts (result_json.copied_from) EXCLUDED.
    """
    from datetime import timedelta
    from exams.models import Student, AttemptLog, EngineState, StudentDailyCode
    from exams.models_day_mission import StudentDayMission

    ABBR_TO_SUBJECT = {
        'PH': 'Physics', 'CH': 'Chemistry', 'BI': 'Biology', 'BIO': 'Biology',
        'TQ': 'Tarjumatul Quran', 'CS': 'Computer Science',
        'MA': 'Mathematics', 'EN': 'English', 'UR': 'Urdu', 'IS': 'Islamiyat',
        'PS': 'Pak Study',
    }

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

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

    pace = student.daily_question_count or 1
    total_days = 120
    start_date = getattr(engine, 'start_date', None) if engine else None

    tree_nodes = []
    for day_num in range(1, total_days + 1):
        day_date = (start_date + timedelta(days=day_num - 1)) if start_date else None

        # ── Future days are always locked ──
        if day_num > current_day:
            tree_nodes.append({
                'day': day_num, 'status': 'locked',
                'total_q': 0, 'score_pct': 0,
                'morning_required': 0, 'morning_done': 0,
                'evening_required': 0, 'evening_done': 0,
                'handwriting': None,
                'questions_attempted': 0, 'questions_needed': pace,
                'is_current': False,
            })
            continue

        # ── Get required subjects from daily codes (with standard fallback) ──
        morning_required = set()
        evening_required = set()
        if day_date:
            daily_code = StudentDailyCode.objects.filter(student=student, date=day_date).first()
            if daily_code and daily_code.per_book_codes:
                pbc = daily_code.per_book_codes
                for abbr in (pbc.get('morning') or {}).keys():
                    subj = ABBR_TO_SUBJECT.get(abbr, abbr)
                    if subj: morning_required.add(subj)
                for abbr in (pbc.get('evening') or {}).keys():
                    subj = ABBR_TO_SUBJECT.get(abbr, abbr)
                    if subj: evening_required.add(subj)
        
        # If no codes exist, fallback to the standard 4+4 structure
        if not morning_required and not evening_required:
            morning_required = {'Physics', 'Chemistry', 'Tarjumatul Quran'}
            opt = (getattr(student, 'assigned_subject', '') or 'Biology').strip()
            if opt: morning_required.add(opt)
            if (student.student_class or '').strip() == '10':
                evening_required = {'Mathematics', 'English', 'Urdu', 'Pak Study'}
            else:
                evening_required = {'Mathematics', 'English', 'Urdu', 'Islamiyat'}

        # ── Get day's missions ──
        missions = list(
            StudentDayMission.objects.filter(student=student, day_number=day_num)
            .values('question_id')
        )
        total_q = len(missions)

        # ── Get REAL attempts only (exclude auto-copies) ──
        q_ids = [m_row['question_id'] for m_row in missions]
        real_attempts = []
        if q_ids:
            all_attempts = list(
                AttemptLog.objects.filter(student=student, question_id__in=q_ids)
                .select_related('question__paper')
                .only('question_id', 'score', 'max_score', 'result_json',
                      'question__question_index', 'question__paper__subject')
            )
            real_attempts = [
                a for a in all_attempts
                if not (a.result_json and 'copied_from' in a.result_json)
            ]

        # ── Real attempts by subject ──
        attempted_subjects = set()
        for a in real_attempts:
            if a.question.paper:
                attempted_subjects.add(a.question.paper.subject)

        # ── Shift completion ──
        morning_done_count = len(morning_required & attempted_subjects)
        evening_done_count = len(evening_required & attempted_subjects)

        # ── Score ──
        if real_attempts:
            total_score = sum(float(a.score) for a in real_attempts)
            total_max = sum(float(a.max_score) for a in real_attempts)
            score_pct = round((total_score / total_max) * 100, 1) if total_max > 0 else 0
        else:
            score_pct = 0

        _mr = (morning_done_count / len(morning_required)) if morning_required else 0.0
        _er = (evening_done_count / len(evening_required)) if evening_required else 0.0
        if morning_required and evening_required:
            completion_pct = round((_mr + _er) / 2 * 100, 1)
        elif morning_required:
            completion_pct = round(_mr * 100, 1)
        elif evening_required:
            completion_pct = round(_er * 100, 1)
        else:
            completion_pct = 0.0

        # ── Handwriting status (from discipline.ClassHomeworkRecord) ──
        # Records with subject="" are handwriting records.
        # Model has handwriting_done OR (handwriting_en_done + handwriting_ur_done).
        handwriting_status = False
        if day_date:
            try:
                from discipline.models import ClassHomeworkRecord
                from django.db.models import Q
                hw = ClassHomeworkRecord.objects.filter(
                    Q(student__linked_code=student.code) | Q(student__code=student.code),
                    subject='',
                    date=day_date,
                ).first()
                if hw is not None:
                    hw_done = getattr(hw, 'handwriting_done', None)
                    hw_en = getattr(hw, 'handwriting_en_done', None)
                    hw_ur = getattr(hw, 'handwriting_ur_done', None)
                    if hw_done is not None:
                        handwriting_status = bool(hw_done)
                    elif hw_en is not None or hw_ur is not None:
                        handwriting_status = bool(hw_en) and bool(hw_ur)
            except Exception as _hw_err:
                # Silently fall through — record just won't show
                pass

        # ── Determine status ──
        has_shift_data = bool(morning_required or evening_required)
        morning_complete = morning_required and (morning_done_count >= len(morning_required))
        evening_complete = evening_required and (evening_done_count >= len(evening_required))
        handwriting_ok = handwriting_status is not False  # True or None = OK

        if not real_attempts:
            status = 'not_started'
        elif has_shift_data:
            both_required = bool(morning_required) and bool(evening_required)
            if both_required:
                if morning_complete and evening_complete and score_pct >= 60 and handwriting_ok:
                    status = 'mastered'
                elif morning_complete and not evening_complete:
                    status = 'morning_done'
                elif evening_complete and not morning_complete:
                    status = 'evening_done'
                else:
                    status = 'in_progress'
            elif morning_required:
                if morning_complete and score_pct >= 60 and handwriting_ok:
                    status = 'mastered'
                else:
                    status = 'in_progress'
            else:  # only evening
                if evening_complete and score_pct >= 60 and handwriting_ok:
                    status = 'mastered'
                else:
                    status = 'in_progress'
        else:
            # No codes — fallback to pace-based logic
            questions_attempted_fb = len(set(a.question_id for a in real_attempts))
            if questions_attempted_fb >= pace and score_pct >= 60:
                status = 'mastered'
            else:
                status = 'in_progress'

        tree_nodes.append({
            'day': day_num, 'status': status,
            'total_q': total_q, 'score_pct': score_pct, 'completion_pct': completion_pct,
            'morning_required': len(morning_required),
            'morning_done': morning_done_count,
            'evening_required': len(evening_required),
            'evening_done': evening_done_count,
            'handwriting': handwriting_status,
            'questions_attempted': len(set(a.question_id for a in real_attempts)),
            'questions_needed': pace,
            'is_current': (day_num == current_day),
        })

    # Summary stats
    mastered_count = sum(1 for n in tree_nodes if n['status'] == 'mastered')
    morning_done_count = sum(1 for n in tree_nodes if n['status'] == 'morning_done')
    evening_done_count = sum(1 for n in tree_nodes if n['status'] == 'evening_done')
    in_progress_count = sum(1 for n in tree_nodes if n['status'] == 'in_progress')

    return render(request, 'exams/portal_tree.html', {
        'student': student,
        'nodes': tree_nodes,
        'current_day': current_day,
        'total_days': total_days,
        'mastered_count': mastered_count,
        'in_progress_count': in_progress_count + morning_done_count + evening_done_count,
        'morning_done_count': morning_done_count,
        'evening_done_count': evening_done_count,
    })


@login_required
def portal_report_hub(request):
    """Unified Report Hub entry point."""
    student = _current_student(request)
    if not student:
        return redirect('portal-dashboard')
    return render(request, 'exams/portal_report_hub.html', {'student': student})


@login_required
def portal_my_questions(request):
    """Student view: their questions grouped by subject for a specific day."""
    from exams.models import EngineState
    from exams.models_day_mission import StudentDayMission

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

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

    # Selected day from query param
    selected_day_str = request.GET.get('day')
    try:
        selected_day = int(selected_day_str) if selected_day_str else current_day
    except (ValueError, TypeError):
        selected_day = current_day
    selected_day = max(1, min(120, selected_day))

    # Fetch missions for that day
    missions = StudentDayMission.objects.filter(
        student=student,
        day_number=selected_day,
        question__paper__superseded_at__isnull=True,
    ).select_related('question', 'question__paper').order_by('subject', 'question__question_index')

    # Group by subject (limit to student's pace per subject, dedupe)
    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)

    # Day options for dropdown (Day 1 to max of current/selected)
    max_day = max(current_day, selected_day, 1)
    day_options = list(range(1, max_day + 1))

    return render(request, 'exams/portal_my_questions.html', {
        'student': student,
        'grouped_questions': grouped_questions,
        'selected_day': selected_day,
        'current_day': current_day,
        'day_options': day_options,
    })


@login_required
def teacher_exam_bulk_issue(request):
    """Bulk-issue exam tokens to a scope: Class / Class+Shift / Shift / ALL."""
    from django.contrib import messages
    from django.shortcuts import redirect
    from exams.models import Student
    from exams.services import exam_queue

    if request.method != 'POST':
        return redirect('teacher-exam-queue')

    if not (request.user.is_staff or request.user.is_superuser):
        messages.error(request, 'Access denied.')
        return redirect('portal-dashboard')

    scope = (request.POST.get('scope') or 'CLASS').strip().upper()
    target_class = (request.POST.get('target_class') or '').strip()
    target_shift = (request.POST.get('target_shift') or '').strip().lower()
    try:
        uses_count = int(request.POST.get('uses', '1'))
        if uses_count < 1: uses_count = 1
        if uses_count > 20: uses_count = 20
    except (ValueError, TypeError):
        uses_count = 1

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

    created = 0
    skipped = 0
    for s in students:
        try:
            token, was_new = exam_queue.issue_token(s, uses=uses_count)
            if was_new:
                created += 1
            else:
                skipped += 1
        except Exception as e:
            import logging
            logging.getLogger(__name__).error(
                "bulk_issue_fail student=%s err=%s", s.code, e
            )
            skipped += 1

    messages.success(
        request,
        f'✅ Bulk exam tokens: created {created} · skipped {skipped} (already had token) · scope={scope}'
    )
    return redirect('teacher-exam-queue')


@login_required
def teacher_exam_bulk_clear(request):
    """Bulk clear tokens (PENDING/CALLED) matching a scope.

    Scope: Class / Class+Shift / Shift / ALL
    Status filter: PENDING only, or PENDING+CALLED.
    COMPLETED/IN_PROGRESS/SKIPPED are never touched (protected).
    """
    from django.contrib import messages
    from django.shortcuts import redirect
    from exams.models import Student, ExamToken
    from django.utils import timezone

    if request.method != 'POST':
        return redirect('teacher-exam-queue')
    if not (request.user.is_staff or request.user.is_superuser):
        messages.error(request, 'Access denied.')
        return redirect('portal-dashboard')

    scope = (request.POST.get('scope') or 'ALL').strip().upper()
    target_class = (request.POST.get('target_class') or '').strip()
    target_shift = (request.POST.get('target_shift') or '').strip().lower()
    clear_statuses = request.POST.getlist('statuses') or ['PENDING']

    # Only allow safe statuses
    allowed_statuses = {'PENDING', 'CALLED'}
    clear_statuses = [s for s in clear_statuses if s in allowed_statuses]
    if not clear_statuses:
        clear_statuses = ['PENDING']

    today = timezone.localdate()
    qs = ExamToken.objects.filter(date=today, status__in=clear_statuses)

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

    student_ids = list(students.values_list('id', flat=True))
    qs = qs.filter(student_id__in=student_ids)

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

    messages.success(
        request,
        f'✅ Bulk cleared: {count} token(s) with statuses {clear_statuses} · '
        f'scope={scope}'
    )
    return redirect('teacher-exam-queue')


@login_required
def portal_teacher_diary_pipeline(request):
    """Teacher's 5-Step Diary Pipeline."""
    if not (request.user.is_staff or request.user.is_superuser):
        messages.error(request, "Access denied.")
        return redirect('portal-dashboard')
        
    from discipline.models import DiaryAssignment
    from exams.models_delegation import TaskDelegation
    from exams.models import Student
    
    today = timezone.localdate()
    
    # Only count TODAY'S assignments, not the whole database
    today_assignments = DiaryAssignment.objects.filter(date=today).count()
    pending_reviews = DiaryAssignment.objects.filter(ai_pending_json__isnull=False, teacher_approved=False).count()
    active_keys = TaskDelegation.objects.filter(task_type='DIARY_UPLOAD', expires_at__gt=timezone.now(), uses_remaining__gt=0).count()
    
    submissions = DiaryAssignment.objects.filter(ai_pending_json__isnull=False, teacher_approved=False).select_related('student').order_by('-id')[:20]
    all_students = Student.objects.filter(is_active=True).order_by('code')

    return render(request, 'exams/portal_teacher_diary_pipeline.html', {
        'today_assignments': today_assignments,
        'pending_reviews': pending_reviews,
        'active_keys': active_keys,
        'submissions': submissions,
        'all_students': all_students,
    })

def portal_teacher_approve_diary(request, assignment_id):
    """Approve a pending diary JSON, award trophies, and publish."""
    if not (request.user.is_staff or request.user.is_superuser):
        return redirect('portal-dashboard')

    from discipline.models import DiaryAssignment, ClassHomeworkRecord
    from exams.models_trophy import TrophyEvent
    from exams.models import Student
    from exams.mizan_algorithm import recompute

    assignment = get_object_or_404(DiaryAssignment, id=assignment_id)
    if not assignment.ai_pending_json or assignment.teacher_approved:
        messages.error(request, "Invalid or already approved submission.")
        return redirect('portal-teacher-diary-pipeline')

    payload = assignment.ai_pending_json
    score = int(payload.get('score', 0))
    stars = max(1, min(5, int(score / 20)))
    
    rec, _ = ClassHomeworkRecord.objects.update_or_create(
        student=assignment.student,
        date=assignment.date,
        subject=assignment.subject[:16],
        defaults={
            'star_rating': stars,
            'handwriting_done': payload.get('handwriting', False),
            'memorization_done': payload.get('memorization', False),
            'understanding_done': payload.get('understanding', False),
            'homework_done': payload.get('homework', False),
            'classwork_done': payload.get('classwork', False),
            'diary_text': payload.get('story', payload.get('feedback', '')), # Save the story
            'diary_visible': True,
            'saved_by': request.user,
        }
    )

    assignment.teacher_approved = True
    assignment.is_completed = True
    assignment.save()

    if stars >= 3:
        exam_student = Student.objects.filter(code=assignment.student.linked_code, is_active=True).first()
        if exam_student:
            tasks = {
                'handwriting': payload.get('handwriting', False),
                'memorization': payload.get('memorization', False),
                'understanding': payload.get('understanding', False),
                'homework': payload.get('homework', False),
                'classwork': payload.get('classwork', False),
            }
            for task_name, is_done in tasks.items():
                if is_done:
                    event_key = f"DIARY_COMPLETE:{exam_student.id}:{assignment.date.isoformat()}:{assignment.subject}:{task_name}"
                    TrophyEvent.objects.get_or_create(
                        student=exam_student, event_key=event_key,
                        defaults={'date': assignment.date, 'reason': 'QUESTION_COMPLETE', 'pace': 1, 'base_count': 1, 'bonus_count': 0, 'count': 1}
                    )
            recompute(exam_student)
            from exams.badges import check_and_award
            check_and_award(exam_student)

    messages.success(request, f"Approved and published for {assignment.student.full_name}!")
    return redirect('portal-teacher-diary-pipeline')

@login_required
def portal_diary_mastery(request, assignment_id):
    """Optional Mastery Stage: Generate Story/MCQs, then take the quiz."""
    from discipline.models import DiaryAssignment
    from exams.models import Student
    from exams.badges import award_badge
    from exams.views_v3 import _parse_ai_json
    from django.contrib import messages

    assignment = get_object_or_404(DiaryAssignment, id=assignment_id)
    student = _current_student(request)
    
    if not student or student.code != assignment.student.linked_code:
        messages.error(request, "Unauthorized.")
        return redirect('portal-dashboard')

    if not assignment.teacher_approved:
        messages.error(request, "This assignment has not been approved yet.")
        return redirect('portal-diary-upload')

    if assignment.mastery_passed:
        return render(request, 'exams/portal_diary_mastery.html', {
            'assignment': assignment,
            'already_passed': True
        })

    # STEP A: Generate the Story & MCQs using AI
    if not assignment.ai_story:
        if request.method == 'POST' and request.POST.get('action') == 'save_story':
            payload = request.POST.get('payload', '').strip()
            try:
                parsed = _parse_ai_json(payload)
                assignment.ai_story = parsed.get('story', '')
                assignment.ai_mcqs = parsed.get('mcqs', [])
                assignment.save()
                messages.success(request, "Story and MCQs generated! Now take the quiz.")
                return redirect('portal-diary-mastery', assignment_id=assignment.id)
            except Exception as e:
                messages.error(request, f"JSON Error: {e}")
                return redirect('portal-diary-mastery', assignment_id=assignment.id)

        # Generate a prompt specifically for this task context
        mastery_prompt = f"""You are a master storyteller and {assignment.subject} teacher.
The student was assigned: {assignment.details or assignment.task_type}.
Based on this exact topic, create a fun, easy-to-understand, 3-act educational story in URDU SCRIPT (Nastaliq) that teaches the core concept.
Also create exactly 5 multiple-choice questions based on the story to test if the student understood it. The questions and options MUST be written in URDU SCRIPT. Each MCQ must have 4 options and specify the correct option.

CRITICAL: Do NOT use Roman Urdu (English alphabet). You MUST use Urdu Script (Arabic alphabet) for the story, questions, and options.

Return ONLY this JSON format:
{{
  "story": "ایک دفعہ کا ذکر ہے... (Urdu script story teaching the topic)",
  "mcqs": [
    {{"question": "اردو میں سوال؟", "options": ["اختیار الف", "اختیار ب", "اختیار ج", "اختیار د"], "correct_index": 0}},
    {{"question": "دوسرا سوال؟", "options": ["اختیار الف", "اختیار ب", "اختیار ج", "اختیار د"], "correct_index": 2}}
  ]
}}
"""
        return render(request, 'exams/portal_diary_mastery.html', {
            'assignment': assignment,
            'mastery_prompt': mastery_prompt,
            'generate_mode': True
        })

    # STEP B: Quiz Submission
    if request.method == 'POST' and request.POST.get('action') == 'submit_quiz':
        mcqs = assignment.ai_mcqs or []
        correct_count = 0
        total = len(mcqs)
        
        for i, mcq in enumerate(mcqs):
            student_ans = request.POST.get(f'mcq_{i}')
            if student_ans is not None and int(student_ans) == mcq.get('correct_index'):
                correct_count += 1
        
        if correct_count >= 4:  # 4/5 or 5/5
            assignment.mastery_passed = True
            assignment.save()
            
            kc_code = f"D{assignment.date.strftime('%Y%m%d')}-{assignment.subject}"
            award_badge(
                student, 
                "KC-MASTERY", 
                trigger_data={"reason": "diary_mastery", "kc_code": kc_code}
            )
            
            messages.success(request, f"Masha'Allah! You passed the quiz ({correct_count}/{total}) and earned a Mastery Badge! 🎖️")
            return redirect('portal-diary-mastery', assignment_id=assignment.id)
        else:
            messages.error(request, f"You scored {correct_count}/{total}. You need at least 4/5 to pass. Please read the story again and retry!")
            return redirect('portal-diary-mastery', assignment_id=assignment.id)

    return render(request, 'exams/portal_diary_mastery.html', {
        'assignment': assignment,
        'generate_mode': False
    })


@login_required
def api_search_students(request):
    """AJAX endpoint to search students by name or code."""
    from django.http import JsonResponse
    from django.db.models import Q
    from exams.models import Student

    q = request.GET.get('q', '').strip()
    if len(q) < 2:
        return JsonResponse({'results': []})
    
    students = Student.objects.filter(
        Q(name__icontains=q) | Q(code__icontains=q),
        is_active=True
    )[:10]
    
    results = [{'code': s.code, 'name': s.name, 'class': s.student_class} for s in students]
    return JsonResponse({'results': results})


@login_required
def portal_teacher_view_diary_assignments(request):
    """Teacher view to just SEE what was assigned today."""
    if not (request.user.is_staff or request.user.is_superuser):
        return redirect('portal-dashboard')
        
    from discipline.models import DiaryAssignment
    from django.utils import timezone
    
    today = timezone.localdate()
    assignments = DiaryAssignment.objects.filter(date=today).select_related('student').order_by('student__grade', 'student__code')

    return render(request, 'exams/portal_teacher_view_diary.html', {
        'assignments': assignments,
        'today': today
    })


@login_required
def portal_my_diary_reports(request):
    """Student's personal Diary Report Card (Equivalent to Mere Papers)."""
    from discipline.models import DiaryAssignment
    from exams.models import Student
    from django.contrib import messages

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

    # Get all approved diary assignments, newest first
    reports = DiaryAssignment.objects.filter(
        student__linked_code=student.code, 
        teacher_approved=True
    ).order_by('-date', 'subject')

    return render(request, 'exams/portal_my_diary_reports.html', {
        'student': student,
        'reports': reports,
    })


@login_required
@require_POST
def api_points_approve(request, award_id):
    from django.http import JsonResponse
    from exams.models import PendingPointAward, CreditEvent
    if not (request.user.is_staff or request.user.is_superuser):
        return JsonResponse({"ok": False, "error": "Forbidden"}, status=403)
    a = PendingPointAward.objects.filter(id=award_id, status="PENDING").first()
    if not a:
        return JsonResponse({"ok": False, "error": "Not found"}, status=404)
    CreditEvent.objects.create(student=a.student, code=a.code, points=a.points, reason=a.reason, evidence=a.evidence or {}, source=a.source or "TEACHER")
    a.status = "APPROVED"
    a.save()
    return JsonResponse({"ok": True})


@login_required
@require_POST
def api_points_reject(request, award_id):
    from django.http import JsonResponse
    from exams.models import PendingPointAward
    if not (request.user.is_staff or request.user.is_superuser):
        return JsonResponse({"ok": False, "error": "Forbidden"}, status=403)
    a = PendingPointAward.objects.filter(id=award_id, status="PENDING").first()
    if not a:
        return JsonResponse({"ok": False, "error": "Not found"}, status=404)
    a.status = "REJECTED"
    a.save()
    return JsonResponse({"ok": True})


@login_required
@require_POST
def api_points_bulk_award(request):
    from django.http import JsonResponse
    from exams.models import Student
    from exams.services import points_ledger
    if not (request.user.is_staff or request.user.is_superuser):
        return JsonResponse({"ok": False, "error": "Forbidden"}, status=403)
    cn = request.POST.get("class_name", "").strip()
    pts = int(request.POST.get("points", 0))
    reason = request.POST.get("reason", "Bulk award")[:200]
    if not cn or not pts:
        return JsonResponse({"ok": False, "error": "Missing fields"}, status=400)
    students = Student.objects.filter(is_active=True, student_class=cn)
    n = 0
    for s in students:
        try:
            points_ledger.award(s, pts, reason, code="BULK_AWARD", source="TEACHER")
            n += 1
        except Exception:
            pass
    return JsonResponse({"ok": True, "awarded": n})


@login_required
def api_points_data(request):
    from django.http import JsonResponse
    from exams.models import PendingPointAward, CreditEvent, Student
    from datetime import date as _d
    if not (request.user.is_staff or request.user.is_superuser):
        return JsonResponse({"ok": False, "error": "Forbidden"}, status=403)
    pending = list(PendingPointAward.objects.filter(status="PENDING").select_related("student").order_by("-id")[:50].values("id", "student__name", "points", "reason"))
    recent = list(CreditEvent.objects.select_related("student").order_by("-id")[:30].values("student__name", "points", "reason", "created_at"))
    today_total = sum(e.points for e in CreditEvent.objects.filter(created_at__date=_d.today()))
    classes = sorted(set(Student.objects.filter(is_active=True).exclude(student_class="").values_list("student_class", flat=True)))
    for r in recent:
        if r["created_at"]:
            r["created_at"] = r["created_at"].strftime("%d %b %H:%M")
    return JsonResponse({"ok": True, "pending": pending, "recent": recent, "today_total": today_total, "classes": classes})


# ============================================================
# ADMIN OVERRIDES — Merged into Control Room (2026-11-16)
# ============================================================
from django.views.decorators.http import require_POST as _require_POST_v3
from django.contrib import messages as _messages_v3


@login_required(login_url="portal-login")
@_require_POST_v3
def teacher_reset_sm2(request, student_code):
    """Reset a student's SM-2 memory state (all keywords due now)."""
    from exams.models import Student, MemorizationState
    from django.shortcuts import redirect as _redirect
    from django.contrib import messages as _m

    if not (request.user.is_staff or request.user.is_superuser):
        _m.error(request, 'Access denied — teachers only.')
        return _redirect('portal-teacher-control')

    try:
        student = Student.objects.get(code=student_code, is_active=True)
    except Student.DoesNotExist:
        _m.error(request, f'Student {student_code} not found')
        return _redirect('portal-teacher-control')

    count = MemorizationState.objects.filter(student=student).count()
    MemorizationState.objects.filter(student=student).delete()
    _m.success(request, f'✅ Reset {count} memory states for {student_code}.')
    return _redirect('portal-teacher-control')


@login_required(login_url="portal-login")
@_require_POST_v3
def teacher_force_pass(request, student_code, qid):
    """Force-mark a question as done for a student (with audit trail)."""
    from exams.models import Student, ModelQuestion, AttemptLog
    from django.shortcuts import redirect as _redirect
    from django.contrib import messages as _m

    if not (request.user.is_staff or request.user.is_superuser):
        _m.error(request, 'Access denied — teachers only.')
        return _redirect('portal-teacher-control')

    try:
        student = Student.objects.get(code=student_code, is_active=True)
        question = ModelQuestion.objects.get(pk=qid)
    except (Student.DoesNotExist, ModelQuestion.DoesNotExist):
        _m.error(request, 'Student or question not found')
        return _redirect('portal-teacher-control')

    AttemptLog.objects.create(
        student=student, question=question,
        student_answer=f'[FORCE-PASSED by {request.user.username}]',
        score=question.marks, max_score=question.marks,
        outcome='CORRECT',
        result_json={'force_passed': True, 'teacher': request.user.username},
    )
    _m.success(request, f'✅ Force-passed Q{qid} for {student_code}.')
    return _redirect('portal-teacher-control')


# ============================================================
# STANDALONE ADMIN OVERRIDES PAGE (2026-11-16)
# ============================================================
@login_required(login_url="portal-login")
def portal_admin_overrides(request):
    """Standalone Admin Overrides page: SM-2 reset, Force-Pass, Student Lookup."""
    from exams.models import Student, MemorizationState, CreditEvent
    from exams.models_flow import FlowRun

    if not (request.user.is_staff or request.user.is_superuser):
        from django.shortcuts import redirect

import hmac
import hashlib
from django.conf import settings

# FIX 500 (recurrence prevention): guarantee chief_examiner.band always exists
def _ensure_ce_band(ce):
    """Template does {{ chief_examiner.band }}. Old rows / some AI responses
    only had 'band_urdu'. Normalize at write time so the template never crashes."""
    if not isinstance(ce, dict):
        return {'band': 'N/A'}
    out = dict(ce)
    if not out.get('band'):
        out['band'] = out.get('band_urdu') or 'N/A'
    return out

