import re
import math
from collections import Counter
import requests
from urllib.parse import quote
from datetime import timedelta
from django.shortcuts import render, get_object_or_404, redirect
from django.contrib.auth.decorators import login_required
from django.contrib import messages
from django.utils import timezone
from django.db.models import Q
from django.http import JsonResponse
from django.core.paginator import Paginator
from exams.models import Student, ModelQuestion, StudentQuestionLock, Submission, StudentNote, ModelPaper, KCCard, Exam, Submission, StudentContribution
from exams.services.daily_mission_engine import (
    get_daily_mission_questions, get_replacement_question, get_source_display,
    get_available_subjects, get_student_books
)
from .view_db_helpers import _current_student


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 _normalize_socratic_ladder(final_result):
    """Defensive normalizer for attempt_result rendering.
    Ensures every ladder step has a 'text' key; template accesses step.text.
    Mutates final_result in place; safe for None / malformed input.
    """
    if not isinstance(final_result, dict):
        return final_result
    steps = final_result.get('socratic_ladder')
    if not isinstance(steps, list):
        return final_result
    for step in steps:
        if not isinstance(step, dict):
            continue
        if not step.get('text'):
            step['text'] = (
                step.get('question')
                or step.get('prompt')
                or step.get('hint')
                or ''
            )
        if 'polya_phase' not in step:
            step['polya_phase'] = ''
    return final_result


def build_timeline(current_step=1):
    steps = [
        {'number': 1, 'title': 'Select Questions', 'desc': 'Sawal chunein (150 Din Lock)'},
        {'number': 2, 'title': 'Study & Notes', 'desc': 'Jawab parhein aur notes banayen'},
        {'number': 3, 'title': 'Attempt & Grade', 'desc': 'Paper upload karein aur AI check karwayen'},
        {'number': 4, 'title': 'Mizan & Dohrai', 'desc': 'Points kamayen aur revision karein'},
    ]
    for s in steps:
        if s['number'] < current_step: s['status'] = 'done'
        elif s['number'] == current_step: s['status'] = 'active'
        else: s['status'] = 'locked'
    return steps

@login_required
@login_required
def translate_text(request):
    text = request.GET.get('text', '').strip()
    if not text:
        return JsonResponse({'error': 'No text provided'}, status=400)
    
    import requests
    from urllib.parse import quote

    # Attempt 1: Google Translate (Unofficial API)
    try:
        url = f"https://translate.googleapis.com/translate_a/single?client=gtx&sl=en&tl=ur&dt=t&q={quote(text)}"
        res = requests.get(url, headers={'User-Agent': 'Mozilla/5.0'}, timeout=3)
        if res.status_code == 200:
            data = res.json()
            translated = "".join([x[0] for x in data[0] if x[0]])
            if translated:
                return JsonResponse({'translated_text': translated})
    except Exception:
        pass # Google failed (rate limit or network), move to fallback

    # Attempt 2: MyMemory API (Highly reliable fallback)
    try:
        url = f"https://api.mymemory.translated.net/get?q={quote(text)}&langpair=en|ur"
        res = requests.get(url, timeout=5)
        if res.status_code == 200:
            data = res.json()
            translated = data.get('responseData', {}).get('translatedText', '')
            if translated and translated.lower() != text.lower():
                return JsonResponse({'translated_text': translated})
    except Exception:
        pass
        
    # Attempt 3: LibreTranslate (Open Source Fallback)
    try:
        url = "https://libretranslate.com/translate"
        payload = {"q": text, "source": "en", "target": "ur", "format": "text"}
        res = requests.post(url, json=payload, timeout=5)
        if res.status_code == 200:
            data = res.json()
            translated = data.get('translatedText', '')
            if translated:
                return JsonResponse({'translated_text': translated})
    except Exception:
        pass

    # INDUSTRY STANDARD: Explicit error return so the frontend doesn't hang
    return JsonResponse({'error': 'Translation service temporarily unavailable. Please try again later.'}, status=503)

    return JsonResponse({'error': 'Translation services unavailable'}, status=500)
def _is_duplicate_text(student, candidate_q):
    """True if student has ever seen this question text (active OR past).

    Defense in depth — checks 3 sources:
      1. StudentQuestionLock (active)    — current assignment
      2. StudentQuestionLock (inactive)  — unlocked/past assignment
      3. AttemptLog                       — past attempt on same text

    Exception: if an active RetakeTicket exists for the original question
    with this text, retries are allowed.

    Skips short text (<20 chars) and HTML/MathML fragments to avoid false positives.
    """
    from exams.models import AttemptLog as _AL, RetakeTicket as _RT
    text = (candidate_q.question_text or '').strip()
    if len(text) < 20 or text.startswith('<'):
        return False
    _tp = text[:500]

    # Active lock → duplicate
    if StudentQuestionLock.objects.filter(
        student=student, is_active=True, question__question_text=_tp,
    ).exists():
        return True

    # Inactive lock → duplicate unless retake ticket exists
    _inactive = StudentQuestionLock.objects.filter(
        student=student, is_active=False, question__question_text=_tp,
    ).first()
    if _inactive:
        if _RT.objects.filter(
            student=student, question=_inactive.question, status='FAILED',
        ).exists():
            return False
        return True

    # Past attempt → duplicate unless retake ticket exists
    _past = _AL.objects.filter(
        student=student, question__question_text=_tp,
    ).first()
    if _past:
        if _RT.objects.filter(
            student=student, question=_past.question, status='FAILED',
        ).exists():
            return False
        return True

    return False


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

    _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 [])

    pace_per_book = student.daily_question_count or 1
    enrolled_books = get_student_books(student)

    SKEY = f'select_v3_{student.id}'
    selections = request.session.get(SKEY, {})
    if not isinstance(selections, dict):
        selections = {}

    subject_filter = request.GET.get('subject', '').strip()
    search_query = request.GET.get('q', '').strip()

    # INDUSTRY STANDARD: TENANT ISOLATION
    # Prevent non-9th from seeing 9th content
    _cls = (student.student_class or '').strip().lower()
    from exams.utils_class import is_personalized_student
    is_non9 = is_personalized_student(student)
    if is_non9 and not subject_filter:
        subject_filter = 'Personalized'

    progress = {}
    for subj in enrolled_books:
        picked = selections.get(subj, [])
        progress[subj] = {'done': len(picked) == pace_per_book, 'count': len(picked)}
    done_count = sum(1 for p in progress.values() if p['done'])
    all_done = done_count == len(enrolled_books) and len(enrolled_books) > 0
    total_selected = sum(len(v) for v in selections.values())
    total_needed = pace_per_book * len(enrolled_books)

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

        if action == 'save_current' and subject_filter:
            picked = request.POST.getlist('question_ids')
            if len(picked) != pace_per_book:
                messages.error(request, f"{subject_filter}: bilkul {pace_per_book} sawal chunein. Aap ne {len(picked)} chune.")
            else:
                qs = list(ModelQuestion.objects.filter(id__in=picked, paper__student_class__in=_allowed_classes).select_related('paper'))
                if is_non9:
                    qs = [q for q in qs if q.paper and q.paper.code == f'CUSTOM-{student.code}']
                bad = [q for q in qs if (q.paper.subject or '').lower() != subject_filter.lower()]
                if bad or len(qs) != pace_per_book:
                    messages.error(request, "Kuch sawal is book se nahi hain. Dobara try karein.")
                else:
                    selections[subject_filter] = [int(x) for x in picked]
                    request.session[SKEY] = selections
                    request.session.modified = True
                    messages.success(request, f"{subject_filter}: {len(picked)} sawal save.")
                    next_subj = next((s for s in enrolled_books if s not in selections or len(selections[s]) != pace_per_book), None)
                    if next_subj:
                        return redirect(f"{request.path}?subject={next_subj}")
                    return redirect(f"{request.path}?subject={subject_filter}")

        elif action == 'confirm_all':
            if not all_done:
                messages.error(request, "Pehle sab books complete karein.")
            else:
                locked = 0
                _skipped_dupes = 0
                locked_per_subject = {}
                for subj, qids in selections.items():
                    for qid in qids:
                        try:
                            q = ModelQuestion.objects.get(id=qid, paper__student_class__in=_allowed_classes)
                            if _is_duplicate_text(student, q):
                                _skipped_dupes += 1
                                continue
                            StudentQuestionLock.objects.update_or_create(
                                student=student, question=q, defaults={'is_active': True}
                            )
                            if q.kc:
                                KCCard.objects.get_or_create(
                                    student=student, kc=q.kc,
                                    defaults={'state': 'NEW', 'next_due_at': timezone.now() + timedelta(days=1)}
                                )
                            locked += 1
                            locked_per_subject.setdefault(subj, []).append(q)
                        except ModelQuestion.DoesNotExist:
                            pass
                # Write SDM with selected questions
                from exams.models import EngineState as _sdm_ES
                from exams.models_day_mission import StudentDayMission as _sdm_SDM
                _e = _sdm_ES.objects.filter(id=1).first()
                _day = _e.get_current_day() if (_e and _e.has_started) else 1
                for _subj, _qs_list in locked_per_subject.items():
                    _sdm_SDM.objects.filter(student=student, day_number=_day, subject=_subj).delete()
                    _src = 'STUDENT_CUSTOM' if is_non9 else 'STUDENT_CHOICE'
                    for _pos, _q in enumerate(_qs_list, start=1):
                        _sdm_SDM.objects.create(
                            student=student, day_number=_day, subject=_subj,
                            position=_pos, question=_q, source=_src
                        )
                try:
                    del request.session[SKEY]
                except KeyError:
                    pass
                request.session.modified = True
                _msg = f"🎉 {locked} sawal lock ho gaye! Ab padhai shuru karein."
                if _skipped_dupes > 0:
                    _msg += f" ({_skipped_dupes} duplicate sawal skip kiye gaye.)"
                messages.success(request, _msg)
                return redirect('portal-daily-mission-v3')

    if not subject_filter and enrolled_books:
        first_incomplete = next((s for s in enrolled_books if not progress[s]['done']), enrolled_books[0])
        return redirect(f"{request.path}?subject={first_incomplete}")

    available_qs = []

    already_picked = selections.get(subject_filter, []) if subject_filter else []

    if subject_filter:
        locked_ids = StudentQuestionLock.objects.filter(student=student, is_active=True).values_list('question_id', flat=True)
        
        if is_non9:
            # STRICT ISOLATION: Non-9th can see their CUSTOM or SELF papers
            qs = ModelQuestion.objects.filter(
                Q(paper__code__startswith=f'CUSTOM-{student.code}') | 
                Q(paper__code__startswith=f'SELF-{student.code}'),
                superseded_at__isnull=True
            ).exclude(id__in=locked_ids).select_related('paper')
        else:
            # CLASS ISOLATION (fixed): show this student's class papers only.
            # Non-personalized students see papers matching their own class.
            qs = ModelQuestion.objects.filter(
                Q(paper__student_class__in=_allowed_classes) |
                Q(paper__code__startswith=f'SELF-{student.code}') |
                Q(paper__code__startswith=f'CUSTOM-{student.code}'),
                paper__subject__iexact=subject_filter,
                superseded_at__isnull=True,
            ).exclude(
                # Reject SELF/CUSTOM papers belonging to OTHER students
                Q(paper__code__startswith='SELF-') & ~Q(paper__code__startswith=f'SELF-{student.code}')
            ).exclude(
                Q(paper__code__startswith='CUSTOM-') & ~Q(paper__code__startswith=f'CUSTOM-{student.code}')
            ).exclude(id__in=locked_ids).select_related('paper')
        qs = qs.exclude(Q(marks=1) | Q(question_text__regex=r'\([A-D]\)') | Q(question_text__regex=r'[A-D]\)'))
        if search_query:
            qs = qs.filter(question_text__icontains=search_query)
        available_qs = list(qs.order_by('-id')[:50])

        # Attach existing StudentNote for inline note UI (correct placement)
        try:
            _qnums = [str(x.question_index) for x in available_qs]
            _notes_map = {(n.subject.lower(), n.q_number): n for n in StudentNote.objects.filter(student=student, q_number__in=_qnums)} if _qnums else {}
            for x in available_qs:
                _subj = (x.paper.subject if x.paper else '').lower()
                x.student_note = _notes_map.get((_subj, str(x.question_index)))
        except Exception:
            pass

    return render(request, 'exams/portal_select_questions.html', {
        'student': student,
        'available_qs': available_qs,
        'subjects': enrolled_books,
        'current_subject': subject_filter,
        'search_query': search_query,
        'pace_per_book': pace_per_book,
        'progress': progress,
        'done_count': done_count,
        'total_subjects': len(enrolled_books),
        'all_done': all_done,
        'total_selected': total_selected,
        'total_needed': total_needed,
        'already_picked': [int(x) for x in already_picked],
    })

@login_required
def question_detail(request, qid):
    from exams.views_v3 import _current_student
    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.user.is_superuser:
        student = Student.objects.filter(is_active=True).first()
    else:
        student = Student.objects.filter(student_user=request.user, is_active=True).first()
    if not student: return redirect('portal-dashboard')
    # IDOR FIX: standard questions (admin-authored) viewable by all;
    # SELF-/CUSTOM- questions only by their owner. Superuser bypass.
    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:
        _std = ~Q(paper__code__startswith='SELF-') & ~Q(paper__code__startswith='CUSTOM-')
        _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_name = question.paper.subject if question.paper.subject else 'GEN'
    q_num = str(question.question_index)

    # Fetch existing note if it exists
    existing_note = StudentNote.objects.filter(student=student, subject=subject_name, q_number=q_num).first()

    if request.method == 'POST':
        # DEFENSE-IN-DEPTH: strip HTML before persistence (latent XSS prevention)
        _raw_ans = request.POST.get('answer_html', '')
        try:
            from exams.services.text_cleaner import strip_tags as _strip_html
            answer_html = _strip_html(_raw_ans)
        except Exception:
            answer_html = _raw_ans
        medium = request.POST.get('medium', 'EN')
        if answer_html.strip():
            if existing_note:
                existing_note.short_core_answer = answer_html
                existing_note.medium = medium
                existing_note.save()
                messages.success(request, "Note update ho gaya!")
            else:
                StudentNote.objects.create(
                    student=student, subject=subject_name, medium=medium, 
                    q_number=q_num, question=question.question_text, 
                    short_core_answer=answer_html, model_source='other'
                )
                messages.success(request, "Note save ho gaya!")
            return redirect('portal-question-detail', qid=qid)

    return render(request, 'exams/portal_question_detail.html', {
        'student': student, 'question': question, 'is_solved': bool(question.model_answer),
        'existing_note': existing_note
    })

@login_required
def attempt_question(request, qid):
    from exams.models import AttemptLog, RetakeTicket, RPSItem, CreditEvent
    from django.utils import timezone

    from exams.views_v3 import _current_student
    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.user.is_superuser:
        student = Student.objects.filter(is_active=True).first()
    else:
        student = Student.objects.filter(student_user=request.user, is_active=True).first()
    if not student:
        return redirect('portal-dashboard')

    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')

    # GATE 1: must be in today's mission (from session mission_data)
    mission_data = request.session.get('mission_data', {})
    assigned_qids = {q for qids in mission_data.values() for q in qids}
    if qid not in assigned_qids and not request.user.is_superuser:
        messages.error(request, 'This question is not in your mission.')
        return redirect('portal-daily-mission-v3')

    # GATE 2: must be locked to student
    lock = StudentQuestionLock.objects.filter(
        student=student, question=question, is_active=True
    ).first()
    if not lock and not request.user.is_superuser:
        messages.error(request, 'This question is not assigned to you.')
        return redirect('portal-daily-mission-v3')

    # ── EXTRACT MCQ OPTIONS ──
    mcq_options = []
    correct_index = 0
    
    # Try reasoning_chain first, then socratic_ladder
    chain = question.reasoning_chain or {}
    if isinstance(chain, list) and len(chain) > 0:
        chain = chain[0]
    
    if isinstance(chain, dict) and 'options' in chain:
        mcq_options = chain['options']
        correct_index = chain.get('correct_index', 0)
    elif question.socratic_ladder and isinstance(question.socratic_ladder, list) and len(question.socratic_ladder) > 0:
        ladder = question.socratic_ladder[0]
        if isinstance(ladder, dict) and 'options' in ladder:
            mcq_options = ladder['options']
            correct_index = ladder.get('correct_index', 0)

    # ── RETRY LOGIC ──
    prior_attempt = AttemptLog.objects.filter(
        student=student, question=question
    ).order_by('-created_at').first()

    is_retry = False
    if prior_attempt:
        retake = RetakeTicket.objects.filter(
            student=student, question=question, status='FAILED'
        ).exists()
        if not retake and not request.user.is_superuser:
            messages.error(request, 'You have already attempted this question. A RetakeTicket is required to re-attempt.')
            return redirect('portal-daily-mission-v3')
        is_retry = True

    if request.method == 'POST':
        selected_choice = request.POST.get('choice')
        
        if selected_choice is not None and mcq_options:
            # MCQ GRADING
            selected_idx = int(selected_choice)
            is_correct = (selected_idx == correct_index)
            
            result = {
                'score': question.marks if is_correct else 0,
                'outcome': 'CORRECT' if is_correct else 'WRONG',
                'feedback': 'Sahi jawab!' if is_correct else 'Ghalat jawab. Dobara koshish karein.',
                'selected_index': selected_idx,
                'correct_index': correct_index
            }
            student_answer = f"MCQ Option: {selected_idx}"
        elif request.POST.get('student_answer'):
            # FALLBACK: Text grading (if no options exist but text submitted)
            student_answer = request.POST.get('student_answer', '').strip()
            from exams.services.step_grading import grade_student_answer
            result = grade_student_answer(
                student_text=student_answer,
                model_text=question.model_answer,
                max_marks=question.marks or 5,
            )
        else:
            messages.error(request, 'Baraye meharbani koi option select karein.')
            return redirect('portal-attempt-question', qid=qid)

        from django.db import transaction
        with transaction.atomic():
            # Persist attempt
            attempt = AttemptLog.objects.create(
                student=student,
                question=question,
                student_answer=student_answer,
                score=result.get('score', 0),
                max_score=question.marks or 5,
                outcome=result.get('outcome', 'WRONG'),
                result_json=result,
            )

            # ── DEDUCT POINTS ON RETRY (inside txn, after attempt exists) ──
            if is_retry:
                from exams.services import points_ledger
                points_ledger.penalize(
                    student=student,
                    points=2,
                    reason=f'Retry attempt for Q{question.id}',
                    code='RETRY_PENALTY',
                    evidence={'attempt_id': attempt.id},
                    source='AUTO',
                )

            # Route based on pass/fail
            kc_code = question.kc_code or (question.kc.code if question.kc else None)

            if attempt.passed:
                if 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}')
                RetakeTicket.objects.filter(
                    student=student, question=question, status='FAILED'
                ).update(status='MASTERED')
            else:
                ticket, created = RetakeTicket.objects.get_or_create(
                    student=student, question=question,
                    status='FAILED',
                    defaults={'attempt_number': 1},
                )
                if not created:
                    ticket.attempt_number = min(5, ticket.attempt_number + 1)
                    if ticket.attempt_number >= 3:
                        ticket.status = 'ESCALATED'
                    ticket.save()

        # ── AI JOURNEY PIPELINE (Industry Standard: Outside Transaction) ──
        # Trigger the Expert Panel AI to generate the next stage based on this attempt.
        try:
            from exams.services.ai_journey import generate_next_stage
            generate_next_stage(attempt)
        except Exception as e:
            import logging
            logging.getLogger(__name__).error(f"AI Journey generation failed: {e}")
        # ─────────────────────────────────────────────────────────────────

        request.session['last_grading_result'] = result
        request.session['last_graded_question'] = question.id
        return redirect('portal-attempt-result')

    return render(request, 'exams/portal_attempt_upload.html', {
        'student': student, 
        'question': question,
        'mcq_options': mcq_options,
        'is_retry': is_retry
    })

@login_required
def attempt_result(request, exam_id=None):
    from exams.views_v3 import _current_student
    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.user.is_superuser and exam_id:
        submission_owner = Submission.objects.filter(exam__id=exam_id).first()
        student = submission_owner.exam.student if submission_owner else Student.objects.filter(is_active=True).first()
    elif request.user.is_superuser:
        student = Student.objects.filter(is_active=True).first()
    else:
        student = Student.objects.filter(student_user=request.user, is_active=True).first()
    if not student:
        return redirect('portal-dashboard')

    submission = None
    if exam_id:
        submission = Submission.objects.filter(
            exam__id=exam_id, exam__student=student
        ).select_related('exam__model_question').first()
    else:
        submission = Submission.objects.filter(
            exam__student=student, ai_raw__isnull=False
        ).select_related('exam__model_question').order_by('-created_at').first()

    if submission and submission.ai_raw:
        result = submission.ai_raw
        question = submission.exam.model_question or ModelQuestion.objects.filter(
            paper__subject__iexact=submission.exam.subject,
            question_index=submission.exam.question_index
        ).first()
        if not question:
            messages.error(request, "Question data missing for this submission.")
            return redirect('portal-daily-mission-v3')
    else:
        result = request.session.get('last_grading_result')
        qid = request.session.get('last_graded_question')
        if not result or not qid:
            messages.error(request, "Koi result nahi mila. Pehle paper upload karein.")
            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')

    # --- KC LOOKUP: exam.kc_code, then question.kc (FK), then question.kc_code ---
    from exams.models import KnowledgeComponent, KCCard
    kc_obj = None
    kc_card = None

    if submission and submission.exam.kc_code:
        kc_obj = KnowledgeComponent.objects.filter(code=submission.exam.kc_code).first()

    if not kc_obj and question:
        kc_obj = getattr(question, 'kc', None)
        if not kc_obj:
            q_kc_code = getattr(question, 'kc_code', '') or ''
            if q_kc_code:
                kc_obj = KnowledgeComponent.objects.filter(code=q_kc_code).first()

    if kc_obj:
        kc_card = KCCard.objects.filter(student=student, kc=kc_obj).first()

    cls = str(student.student_class).strip().lower()
    if '9' in cls:
        try:
            from exams.models import HealthScore
            score_obj, _ = HealthScore.objects.get_or_create(student=student)
        except Exception as e:
            print(f"Error: {e}")

    # STAGE 23 & 24 FIX
    final_result = dict(result) if result else {}
    if not final_result.get('socratic_ladder') and submission and submission.ai_raw:
        final_result['socratic_ladder'] = submission.ai_raw.get('socratic_ladder', [])
    if 'socratic_ladder' not in final_result:
        ladders = final_result.get('ladders') or []
        steps = []
        for ladder in ladders:
            if isinstance(ladder, dict):
                steps.extend(ladder.get('steps', []))
        final_result['socratic_ladder'] = steps
    if 'misconceptions' not in final_result and submission:
        final_result['misconceptions'] = submission.ai_mistakes or []
    if 'score' not in final_result and submission and submission.ai_score is not None:
        final_result['score'] = float(submission.ai_score)

    # --- HANDWRITING POINTS FOR LIKHAI BADGE ---
    hw_points = 0
    try:
        from discipline.models import ClassHomeworkRecord
        hw_recs = ClassHomeworkRecord.objects.filter(student__linked_code=student.code, subject="").order_by('-date')[:14]
        if not hw_recs.exists():
            hw_recs = ClassHomeworkRecord.objects.filter(student__code=student.code, subject="").order_by('-date')[:14]
        hw_points = sum(5 for r in hw_recs if r.handwriting_en_done) + sum(5 for r in hw_recs if r.handwriting_ur_done)
    except Exception:
        hw_points = 0

    # --- ROADBLOCK CHECKS ---
    roadblock_prompt = None
    ladder_roadblock_prompt = None
    keyterms_roadblock_prompt = None
    story_roadblock_prompt = None
    if kc_obj:
        from exams.services.story_panel.prompt_templates import (
            build_misconception_prompt,
            build_socratic_ladder_prompt,
            build_key_terms_prompt,
        )
        if not kc_obj.misconceptions:
            roadblock_prompt = build_misconception_prompt(kc_obj)
        if not kc_obj.socratic_ladder:
            ladder_roadblock_prompt = build_socratic_ladder_prompt(kc_obj)
        if not kc_obj.key_terms:
            keyterms_roadblock_prompt = build_key_terms_prompt(kc_obj)
        if not kc_obj.story or kc_obj.story_status not in ('PANEL_PASSED', 'TEACHER_OVERRIDE'):
            from exams.services.story_panel.prompt_builder import build_prompt as _build_story
            story_roadblock_prompt = _build_story(kc_obj)

    # Defensive: normalize ladder so template never sees missing 'text'
    _normalize_socratic_ladder(final_result)

    # --- AI JOURNEY STAGE FETCH ---
    ai_stage = None
    if question:
        from exams.models import AIJourneyStage, AttemptLog
        latest_attempt = AttemptLog.objects.filter(student=student, question=question, cancelled_at__isnull=True).order_by('-created_at').first()
        if latest_attempt:
            ai_stage = AIJourneyStage.objects.filter(attempt_log=latest_attempt).first()

    return render(request, 'exams/portal_attempt_result.html', {
        'ai_stage': ai_stage,
        'result': final_result,
        'question': question,
        'is_9th': '9' in cls if student else False,
        'kc_obj': kc_obj,
        'kc_card': kc_card,
        'hw_points': hw_points,
        'roadblock_prompt': roadblock_prompt,
        'ladder_roadblock_prompt': ladder_roadblock_prompt,
        'keyterms_roadblock_prompt': keyterms_roadblock_prompt,
        'story_roadblock_prompt': story_roadblock_prompt,
        'field_name': 'misconceptions',
    })

@login_required
def portal_daily_mission(request):
    from exams.models import EngineState
    from exams.models_day_mission import StudentDayMission
    from exams.models import StudentNote, Submission
    from collections import defaultdict

    from exams.views_v3 import _current_student
    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.user.is_superuser:
        student = Student.objects.filter(is_active=True).first()
    else:
        student = Student.objects.filter(student_user=request.user, is_active=True).first()
    if not student: return redirect('portal-dashboard')

    _sc = (student.student_class or "9").strip().lower()
    if _sc not in ("9", "9th", "9th class"):
        return redirect('portal-dashboard')

    subject_filter = request.GET.get('subject', '').strip()
    expected_books = get_student_books(student)
    target_total = 3 * len(expected_books)

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

    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
    session_mission_day = request.session.get('mission_day', None)
    mission_data = request.session.get('mission_data', {})
    actual_total = sum(len(qids) for qids in mission_data.values())

    if not mission_data or actual_total < target_total or session_mission_day != effective_day:
        if effective_day > 0:
                        # ---- SINGLE SOURCE OF TRUTH: read SDM, not raw ModelQuestion ----
            from exams.models_day_mission import StudentDayMission as _SDM_pipe
            _sdm_rows = (
                _SDM_pipe.objects
                .filter(student=student, day_number=effective_day)
                .select_related('question', 'question__paper')
                .order_by('subject', 'position', 'id')
            )
            mission_data = {}
            for _m in _sdm_rows:
                _book = _m.subject or (_m.question.paper.subject if _m.question.paper else 'Unknown')
                mission_data.setdefault(_book, []).append(_m.question_id)
        else:
            mission_data = {}
        request.session['mission_data'] = mission_data
        request.session['mission_day'] = effective_day

    questions = []
    # XSS FIX (defense-in-depth): scope by SELF/CUSTOM ownership regardless of how
    # the qid got into session (defense against session-poisoning chain)
    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}')
    if request.user.is_superuser:
        _dq = ModelQuestion.objects.select_related('paper')
    else:
        _dq = ModelQuestion.objects.select_related('paper').filter(
            _std | _own_self | _own_custom
        )
    for book, qids in mission_data.items():
        if subject_filter and subject_filter.lower() != book.lower(): continue
        for idx, qid in enumerate(qids):
            try:
                q = _dq.get(id=qid)
                questions.append({'obj': q, 'index': idx, 'source_display': get_source_display(q), 'subject': q.paper.subject or book})
            except ModelQuestion.DoesNotExist: pass

    # === Archive: 3-state status per question ===
    archive_days = []
    if effective_day > 0:
        archive_qs = list(StudentDayMission.objects.filter(
            student=student, day_number__lt=effective_day
        ).select_related('question', 'question__paper').order_by('-day_number', 'subject', 'question__question_index'))

        q_ids = [entry.question_id for entry in archive_qs]
        submission_qids = set()
        if q_ids:
            # Only count a submission if it matches the exact date the question was assigned
            q_dates = {entry.question_id: entry.locked_at.date() for entry in archive_qs if entry.locked_at}
            subs_qs = Submission.objects.filter(
                exam__student=student,
                exam__model_question_id__in=q_ids
            ).values('exam__model_question_id', 'exam__exam_date')
            
            for s in subs_qs:
                qid = s['exam__model_question_id']
                if qid in q_dates and s['exam__exam_date'] == q_dates[qid]:
                    submission_qids.add(qid)

        note_keys = set(
            StudentNote.objects.filter(student=student).values_list('subject', 'q_number')
        )

        archive_by_day = defaultdict(lambda: defaultdict(list))
        for entry in archive_qs:
            q = entry.question
            if q.id in submission_qids:
                status = 'graded'
            elif (entry.subject, str(q.question_index)) in note_keys:
                status = 'drafted'
            else:
                status = 'not_started'
            archive_by_day[entry.day_number][entry.subject].append({
                'question': q,
                'status': status,
            })

        for day_num in sorted(archive_by_day.keys(), reverse=True):
            day_subjects = []
            total_q = graded_q = drafted_q = 0
            for subject in sorted(archive_by_day[day_num].keys()):
                qlist = archive_by_day[day_num][subject]
                day_subjects.append({'subject': subject, 'questions': qlist})
                total_q += len(qlist)
                for x in qlist:
                    if x['status'] == 'graded': graded_q += 1
                    elif x['status'] == 'drafted': drafted_q += 1
            archive_days.append({
                'day_number': day_num,
                'subjects': day_subjects,
                'total_questions': total_q,
                'graded_questions': graded_q,
                'drafted_questions': drafted_q,
                'attempted_questions': graded_q + drafted_q,
            })

    # --- DYNAMIC STEPPER LOGIC ---
    from exams.models import Submission
    day_qids = [q['obj'].id for q in questions]
    
    has_submission = False
    if day_qids:
        has_submission = Submission.objects.filter(exam__student=student, exam__model_question_id__in=day_qids).exists()
        
    has_notes = False
    if day_qids:
        has_notes = StudentNote.objects.filter(student=student, q_number__in=[str(q.question_index) for q in [x['obj'] for x in questions]]).exists()

    today = timezone.now().date()
    morning_unlocked = request.session.get(f'daily_code_unlocked_{today}_morning', False)
    evening_unlocked = request.session.get(f'daily_code_unlocked_{today}_evening', False)
    
    # Backward compatibility
    if request.session.get(f'daily_code_unlocked_{today}', False):
        morning_unlocked = True
        evening_unlocked = True

    code_verified = morning_unlocked or evening_unlocked
    if request.user.is_superuser:
        code_verified = True
        morning_unlocked = True
        evening_unlocked = True

    if has_submission:
        current_step = 4 # Unlocked Mizan & Dohrai
    elif code_verified:
        current_step = 3 # Unlocked Attempt & Grade
    else:
        current_step = 2 # Active Study & Notes (or waiting for code)

    show_waiting_banner = (current_step == 3 and not has_submission)
    
    # Book labels for the code entry form
    BOOK_ABBR = {
        'Urdu': 'UR', 'English': 'EN', 'Islamiyat': 'IS',
        'Mathematics': 'MA', 'Chemistry': 'CH', 'Physics': 'PH',
        'Tarjumatul Quran': 'TQ', 'Computer Science': 'CS',
        'Biology': 'BI', 'Bio': 'BI', 'Computer': 'CS',
        'Pak Study': 'PS',
    }
    books_with_abbr = [{'name': b, 'abbr': BOOK_ABBR.get(b, b[:2].upper() if len(b) >= 2 else b.upper())} for b in expected_books]
    MORNING_BOOK_NAMES = ['Physics', 'Chemistry', 'Biology', 'Computer Science', 'Tarjumatul Quran']
    EVENING_BOOK_NAMES = ['Mathematics', 'English', 'Urdu', 'Islamiyat']
    
    morning_books_with_abbr = [b for b in books_with_abbr if b['name'] in MORNING_BOOK_NAMES]
    evening_books_with_abbr = [b for b in books_with_abbr if b['name'] in EVENING_BOOK_NAMES]


    # ── Contribution OR explicit skip bypasses notes requirement ──
    has_contributed = StudentContribution.objects.filter(student=student).exists()
    notes_skipped_today = request.session.get(f'notes_skipped_{timezone.localdate().isoformat()}', False)
    notes_bypassed = has_contributed or notes_skipped_today
    notes_or_contributed = has_notes or notes_bypassed
    notes_skipped_via_contribution = notes_bypassed and not has_notes
    notes_skipped_reason = (
        'skipped' if notes_skipped_today
        else ('contributed' if has_contributed else '')
    )
    # ── SELF-HEAL: Attach story prompts for missing stories ──
    from exams.services.story_panel.prompt_builder import build_prompt as _build_story
    for _q in questions:
        _q['story_prompt'] = None
        _kc = getattr(_q.get('obj'), 'kc', None)
        if _kc and not _kc.story:
            try:
                _q['story_prompt'] = _build_story(_kc)
            except Exception as _e:
                print(f'[_story_prompt] {_e}')
    # ── END SELF-HEAL ──



    _guide_ctx = {
        "title": "Aaj Ka Mission",
        "purpose": "Yeh aap ke rozana ke sawalat ka page hai. Har din aap ko naye sawalat milte hain.",
        "value": "Aap ka daily target aap ke Pace ke mutabiq hota hai. Har sawal mukammal karne par trophies milti hain.",
        "how_to": "Har sawal par click karein aur apna jawab likh kar upload karein. Saare sawalat mukammal karne par day complete ho jata hai.",
        "controls": "Back/Forward buttons se navigate karein. Test codes teacher set karte hain.",
    }
    return render(request, 'exams/portal_daily_mission.html', {
        'guide': _guide_ctx,
        'student': student, 'questions': questions, 'pace': 3,
        'books_with_abbr': books_with_abbr, 'morning_books_with_abbr': morning_books_with_abbr, 'evening_books_with_abbr': evening_books_with_abbr, 'morning_unlocked': morning_unlocked, 'evening_unlocked': evening_unlocked,
        'show_waiting_banner': show_waiting_banner,
        'timeline': build_timeline(current_step=current_step), 'subjects': expected_books,
        'current_subject': subject_filter,
        'effective_day': effective_day,
        'base_day': base_day,
        'override_days': override,
        'archive_days': archive_days,
        'show_code_form': notes_or_contributed and not code_verified and not has_submission,
        'show_notes_instruction': not notes_or_contributed and not has_submission,
        'notes_skipped_via_contribution': notes_skipped_via_contribution,
        'notes_skipped_reason': notes_skipped_reason,
    })



@login_required
def portal_swap_question(request, swap_index):
    """Swap a student's currently-locked question for a replacement.

    BATCH 5_105b fix: previous version had multiple UnboundLocalError/NameError bugs
    (student used before assignment, invalid FK lookup, several undefined variables
    used in the final render). This version does the swap then redirects to
    portal-daily-mission which renders the page correctly with its own context.
    """
    from datetime import timedelta
    from django.utils import timezone
    from django.contrib import messages
    from django.shortcuts import redirect
    from exams.models import (
        Submission, StudentQuestionLock, StudentSwapLog, ModelQuestion,
    )

    if request.user.is_superuser:
        student = Student.objects.filter(is_active=True).first()
    else:
        student = Student.objects.filter(student_user=request.user, is_active=True).first()

    if not student:
        messages.error(request, "No active student found.")
        return redirect('portal-daily-mission')

    _cls = ((student.student_class or '') if student else '').strip().lower()
    from exams.utils_class import allowed_classes_for
    _allowed_classes = allowed_classes_for(_cls) or ([_cls] if _cls else []) if _cls else []

    qid = swap_index

    # Lock: cannot swap if the question was already answered
    already_answered = Submission.objects.filter(
        exam__student=student,
        exam__model_question_id=qid,
    ).exists()
    if already_answered:
        messages.error(request, "Aap is sawal ka jawab de chuke hain.")
        return redirect('portal-daily-mission')

    # IDOR: question must be currently locked to this student
    old_lock = StudentQuestionLock.objects.filter(
        student=student, question_id=qid, is_active=True
    ).first()
    if not old_lock:
        messages.error(request, "Yeh sawal aap ke paas nahi hai.")
        return redirect('portal-daily-mission')

    if (timezone.now() - old_lock.locked_at) > timedelta(hours=3):
        messages.error(request, "Yeh sawal 3 ghante se zyada purana hai.")
        return redirect('portal-daily-mission')

    # Daily limit
    today = timezone.now().date()
    swap_log, _ = StudentSwapLog.objects.get_or_create(student=student, date=today)
    if swap_log.count >= 5:
        messages.error(request, "Aap ne aaj ki limit (5 dafa) mukammal kar li hai.")
        return redirect('portal-daily-mission')

    # Attempt the swap
    swapped = False
    try:
        old_q = ModelQuestion.objects.get(
            id=qid, paper__student_class__in=_allowed_classes
        )
        subject = old_q.paper.subject
        mission_data = request.session.get('mission_data', {}) or {}

        if subject in mission_data and qid in mission_data[subject]:
            exclude = [q for sublist in mission_data.values() for q in sublist]
            new_q = get_replacement_question(student, exclude, subject=subject)

            if new_q:
                swap_log.count += 1
                swap_log.save()

                idx = mission_data[subject].index(qid)
                mission_data[subject][idx] = new_q.id
                request.session['mission_data'] = mission_data

                StudentQuestionLock.objects.filter(
                    student=student, question_id=qid
                ).delete()
                StudentQuestionLock.objects.update_or_create(
                    student=student, question=new_q,
                    defaults={'is_active': True},
                )
                swapped = True
                messages.success(request, "Sawal tabdeel ho gaya.")
            else:
                messages.warning(request, "Koi replacement sawal nahi mila.")
        else:
            messages.warning(request, "Swap ke liye sawal session mein nahi mila.")
    except ModelQuestion.DoesNotExist:
        messages.error(request, "Yeh sawal maujood nahi hai.")
    except Exception as exc:
        import logging
        logging.getLogger(__name__).exception(
            'portal_swap_question failed for student=%s qid=%s: %s',
            getattr(student, 'pk', None), qid, exc,
        )
        messages.error(request, "Sawal tabdeel nahi ho saka. Dobara koshish karein.")

    return redirect('portal-daily-mission')

@login_required
def portal_advance_day(request):
    from django.contrib import messages
    if request.method != 'POST':
        return redirect('portal-daily-mission')
    if request.user.is_superuser:
        student = Student.objects.filter(is_active=True).first()
    else:
        student = Student.objects.filter(student_user=request.user, is_active=True).first()
    if not student: return redirect('portal-dashboard')

    current_override = request.session.get('mission_override', 0)
    if current_override >= 14:
        messages.warning(request, "Aap maximum 14 din aage tak preview kar sakte hain. Pehle reset karein.")
        return redirect('portal-daily-mission')

    request.session['mission_override'] = current_override + 1
    request.session['mission_data'] = {}
    request.session['mission_day'] = None
    messages.success(request, "Agle din ke sawal load ho gaye! Aage ka kaam shuru kar sakte hain.")
    return redirect('portal-daily-mission')


@login_required
def portal_reset_day(request):
    from django.contrib import messages
    request.session['mission_override'] = 0
    request.session['mission_data'] = {}
    request.session['mission_day'] = None
    messages.info(request, "Aap aaj ke din par wapas aa gaye hain.")
    return redirect('portal-daily-mission')



def _clean_subject_name(raw):
    """Convert an internal subject code into a professional display name."""
    if not raw:
        return None
    s = str(raw).strip()
    if not s or s.isdigit():
        return None
    upper = s.upper()
    for prefix in ('SELF-', 'CUSTOM-', 'STD-'):
        if upper.startswith(prefix):
            return 'Personalized'
    if s.islower() or s.isupper():
        return s.title()
    return s


def _curated_note_subjects(student):
    """
    Strict, professional subject list for the Notes page.
    Includes standard 9th subjects, General Knowledge, General Science,
    Personalized, 10 custom subjects, and Class A-K for custom paths.
    """
    # Standard 9th Subjects + General
    subjects = [
        "English",
        "Urdu",
        "Mathematics",
        "Physics",
        "Chemistry",
        "Biology",
        "Computer Science",
        "Islamiyat",
        "Tarjumatul Quran",
        "General Knowledge",
        "General Science",
        "Personalized",
    ]
    
    # Custom Subjects for self-paced learning
    for i in range(1, 11):
        subjects.append(f"Subject {i}")
        
    # Custom Classes for self-paced learning
    for letter in "ABCDEFGHIJK":
        subjects.append(f"Class {letter}")
        
    return subjects


@login_required(login_url='portal-login')
def portal_my_notes(request):
    from django.contrib import messages
    if request.user.is_superuser:
        student = Student.objects.filter(is_active=True).first()
    else:
        student = Student.objects.filter(student_user=request.user, is_active=True).first()
    if not student: return redirect('portal-dashboard')

    if request.method == 'POST':
        _action = (request.POST.get('action') or '').strip()
        if _action in ('edit', 'delete'):
            _note_id = request.POST.get('note_id', '')
            _note = StudentNote.objects.filter(id=_note_id, student=student).first()
            if not _note:
                messages.error(request, 'Note not found.')
                return redirect('portal-my-notes')
            if _action == 'edit':
                _new_ans = request.POST.get('short_core_answer', '').strip()[:2000]
                if _new_ans:
                    _note.short_core_answer = _new_ans
                    _note.save(update_fields=['short_core_answer'])
                    messages.success(request, 'Note updated.')
                else:
                    messages.error(request, 'Answer cannot be empty.')
            elif _action == 'delete':
                _note.delete()
                messages.success(request, 'Note deleted.')
            return redirect('portal-my-notes')

        subject = request.POST.get('subject', '').strip()
        q_num = request.POST.get('q_number', '').strip()
        question = request.POST.get('question', '').strip()
        answer = request.POST.get('answer', '').strip()
        medium = request.POST.get('medium', 'EN')

        if subject and q_num and question and answer:
            StudentNote.objects.create(
                student=student,
                subject=subject,
                q_number=q_num,
                question=question,
                short_core_answer=answer,
                medium=medium
            )
            messages.success(request, "Note save ho gaya!")
            return redirect('portal-my-notes')
        else:
            messages.error(request, "Tamam fields bharna zaroori hai.")

    subject_filter = request.GET.get('subject', '').strip()
    search_query = request.GET.get('q', '').strip()

    # INDUSTRY STANDARD: TENANT ISOLATION
    # Prevent non-9th from seeing 9th content
    _cls = (student.student_class or '').strip().lower()
    from exams.utils_class import is_personalized_student
    is_non9 = is_personalized_student(student)
    if is_non9 and not subject_filter:
        subject_filter = 'Personalized'
    notes = StudentNote.objects.filter(student=student).order_by('-created_at')
    if subject_filter: notes = notes.filter(subject__iexact=subject_filter)
    if search_query: notes = notes.filter(question__icontains=search_query)

    from django.core.paginator import Paginator as _Pag
    _paginator = _Pag(notes, 20)
    _page_obj = _paginator.get_page(request.GET.get('page'))
    _notes_total = _paginator.count
    notes = list(_page_obj.object_list)

    from exams.models import StudentContribution
    has_contributed = StudentContribution.objects.filter(student=student).exists()

    # INDUSTRY STANDARD FIX: Use StudentDayMission (SDM) as source of truth instead of legacy StudentQuestionLock
    from exams.models_day_mission import StudentDayMission as _SDM
    _missions = _SDM.objects.filter(student=student).select_related('question', 'question__paper').order_by('-day_number', 'position')
    seen_q_ids = set()
    active_qs = []
    for m in _missions:
        if m.question and m.question.id not in seen_q_ids:
            seen_q_ids.add(m.question.id)
            subj = m.subject or (m.question.paper.subject if m.question.paper else 'General')
            active_qs.append({
                'id': m.question.id,
                'subject': subj,
                'q_num': getattr(m.question, 'question_index', ''),
                'text': getattr(m.question, 'question_text', '')[:80]
            })
        if len(active_qs) >= 100:
            break
    return render(request, 'exams/portal_my_notes.html', {
        'page_obj': _page_obj,
        'notes_total': _notes_total,
        'active_qs': active_qs,
        'student': student, 'notes': notes, 'subjects': _curated_note_subjects(student),
        'current_subject': subject_filter, 'search_query': search_query,
        'has_contributed': has_contributed,
    })

@login_required
def portal_search_questions(request):
    # FIX (batch 5_103): fetch student FIRST, then compute _cls (was UnboundLocalError).
    # Guard against no-student-profile: fall back to class filter from superuser's default,
    # or empty (blocks all standard questions). Also guards AttributeError if student is None.
    if request.user.is_superuser:
        student = Student.objects.filter(is_active=True).first()
    else:
        student = Student.objects.filter(student_user=request.user, is_active=True).first()

    _cls = ((student.student_class or '') if student else '').strip().lower()
    from exams.utils_class import allowed_classes_for
    _allowed_classes = allowed_classes_for(_cls) or ([_cls] if _cls else []) if _cls else []

    search_query = request.GET.get('q', '').strip()
    subject_filter = request.GET.get('subject', '').strip()
    page_number = request.GET.get('page', 1)

    # IDOR/XSS FIX: standard questions only for non-owners of SELF-/CUSTOM- papers.
    # Superuser sees everything. select_related avoids N+1 on q.paper.*
    results_qs = ModelQuestion.objects.filter(
        paper__student_class__in=_allowed_classes,
        superseded_at__isnull=True, marks__gt=1
    ).exclude(question_text__startswith='[]').exclude(question_text='').select_related('paper')
    if not request.user.is_superuser:
        if student:
            _std = ~Q(paper__code__startswith='SELF-') & ~Q(paper__code__startswith='CUSTOM-')
            results_qs = results_qs.filter(
                _std
                | Q(paper__code__startswith=f'SELF-{student.code}')
                | Q(paper__code__startswith=f'CUSTOM-{student.code}')
            )
        else:
            results_qs = results_qs.exclude(
                Q(paper__code__startswith='SELF-') | Q(paper__code__startswith='CUSTOM-')
            )
    if search_query: results_qs = results_qs.filter(question_text__icontains=search_query)
    if subject_filter: results_qs = results_qs.filter(paper__subject__iexact=subject_filter)

    results_qs = results_qs.order_by('paper__subject', 'paper_id', 'question_index')

    paginator = Paginator(results_qs, 50)
    page_obj = paginator.get_page(page_number)

    results = [{'obj': q, 'source_display': get_source_display(q)} for q in page_obj]

    _guide_ctx = {
        "title": "Sawal Talash Kaise Karein",
        "purpose": "Yeh page purane sawalat ko dhoondne ke liye hai.",
        "value": "Aap kisi bhi subject, topic, ya keyword se sawal talash kar sakte hain.",
        "how_to": "Search box mein keyword likhein, ya filters use karein. Result par click kar ke sawal dekh sakte hain.",
        "controls": "Filtter dropdowns se subject/chapter select karein. Clear button se search reset karein.",
    }
    return render(request, 'exams/portal_search_questions.html', {
        'guide': _guide_ctx,
        'student': student, 'results': results, 'subjects': get_available_subjects(),
        'current_subject': subject_filter, 'search_query': search_query,
        'page_obj': page_obj,
    })


@login_required
def portal_attest_notes(request):
    from exams.views_v3 import _current_student
    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')
    
    # Get the student
    if request.user.is_superuser:
        student = Student.objects.filter(is_active=True).first()
    else:
        student = Student.objects.filter(student_user=request.user, is_active=True).first()
    
    if not student:
        return redirect('portal-dashboard')
    
    # Create a generic attestation note (or use StudentNote with a special marker)
    # We'll create a StudentNote with subject='_ATTESTATION_' to act as a flag.
    from exams.models import StudentNote
    from django.utils import timezone
    
    # Check if an attestation already exists for today
    today = timezone.now().date()
    # This is a simplified check; in production, you'd link to the specific mission day.
    # For now, we just create a note if it doesn't exist to unlock the step.
    # A more robust approach would be to link to StudentDayMission.
    
    # We'll use a simple flag: if the student submits the form, we create a note.
    # The view logic below will check for the existence of ANY note for the day's questions.
    # This is a temporary solution.
    
    # Get the current mission day's questions from session
    mission_data = request.session.get('mission_data', {})
    qids = []
    for book, ids in mission_data.items():
        qids.extend(ids)
    
    if not qids:
        messages.error(request, "No active mission to attest to.")
        return redirect('portal-daily-mission')
    
    # HARDENING: scope qids + atomic + no bare-except
    from exams.models import ModelQuestion
    from django.db import transaction
    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)

    with transaction.atomic():
        for qid in qids:
            try:
                q = _allowed.get(id=qid)
                note, created = StudentNote.objects.get_or_create(
                    student=student,
                    subject=q.paper.subject,
                    q_number=str(q.question_index),
                    defaults={'question': q.question_text, 'short_core_answer': 'ATTESTED'}
                )
                if created:
                    break
            except ModelQuestion.DoesNotExist:
                continue
            except Exception:
                continue
    
    messages.success(request, "Shabash! Aap ne notes confirm kar liye hain. Ab aap paper attempt kar sakte hain.")
    return redirect('portal-daily-mission')



@login_required
def portal_verify_code(request):
    if request.method != 'POST':
        return redirect('portal-daily-mission')

    if request.user.is_superuser:
        student = Student.objects.filter(is_active=True).first()
    else:
        student = Student.objects.filter(student_user=request.user, is_active=True).first()

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

    today = timezone.now().date()
    from exams.models import StudentDailyCode
    from exams.views_student_pipeline import get_student_books

    code_obj = StudentDailyCode.objects.filter(student=student, date=today).first()
    expected_books = get_student_books(student)

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

    shift = request.POST.get('shift', 'morning')
    valid = False

    if code_obj and code_obj.per_book_codes:
        all_correct = True
        
        # Get the specific shift dict
        shift_codes = code_obj.per_book_codes.get(shift, {})
        order_key = f'{shift}_order'
        books_to_check = code_obj.per_book_codes.get(order_key, list(shift_codes.keys()))
        
        if not books_to_check:
            books_to_check = list(shift_codes.keys())

        for abbr in books_to_check:
            entered = request.POST.get(f'code_{abbr}', '').strip()
            correct = str(shift_codes.get(abbr, ''))

            if not correct or entered != correct:
                all_correct = False
                break

        if all_correct and books_to_check:
            valid = True
    elif code_obj and str(code_obj.code) == request.POST.get('code_GLOBAL', '').strip():
        valid = True

    if valid:
        request.session[f'daily_code_unlocked_{today}_{shift}'] = True
        messages.success(request, f"Shabash! {shift.title()} codes verified. Ab aap paper attempt kar sakte hain.")
    else:
        messages.error(request, f"Ghalat code for {shift.title()}. Baraye meharbani apne teacher se sahi code lein.")

    return redirect('portal-daily-mission')


@login_required
def portal_practice_kc(request, kc_code):
    student = Student.objects.filter(is_active=True).first() if request.user.is_superuser else Student.objects.filter(student_user=request.user, is_active=True).first()
    _cls = ((student.student_class or '') if student else '').strip().lower()
    from exams.utils_class import allowed_classes_for
    _allowed_classes = allowed_classes_for(_cls) or ([_cls] if _cls else [])

    from exams.models import KnowledgeComponent, RPSItem, ModelQuestion
    from exams.services.bkt import BKTParams, update
    import random

    if request.user.is_superuser:
        student = Student.objects.filter(is_active=True).first()
    else:
        student = Student.objects.filter(student_user=request.user, is_active=True).first()
        
    if not student:
        messages.error(request, "No active student found to test this page.")
        return redirect('portal-dashboard')

    kc = get_object_or_404(KnowledgeComponent, code=kc_code)

    # Fetch questions FIRST so we can attach one to the RPSItem
    # IDOR FIX: filter out other students' SELF-/CUSTOM- questions
    from django.db.models import Q as _Q
    _qs = ModelQuestion.objects.filter(kc=kc, paper__student_class__in=_allowed_classes).exclude(model_answer='')
    if not request.user.is_superuser:
        _qs = _qs.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}')
        )
    questions = list(_qs)
    skip_key = f'practice_gate_skipped_{kc.code}'

    # If questions now exist (thanks to a previous contribution), clear skip flag
    if questions and skip_key in request.session:
        del request.session[skip_key]

    if not questions:
        from exams.services.story_panel.prompt_templates import build_question_prompt

        # Handle explicit skip POST
        if request.method == 'POST' and request.POST.get('action') == 'skip_practice_gate':
            request.session[skip_key] = True
            messages.info(request, "Aap ne is KC ka contribution skip kiya. Is session mein dobara nahi poochenge. Next session mein phir yaad dilayenge.")
            return redirect('portal-daily-mission-v3')

        # If already skipped this session, auto-pass with info
        if request.session.get(skip_key, False):
            messages.info(request, f"{kc.code}: content abhi tak nahi hai. Aap ne pehle skip kiya tha. Practice agle session mein available hogi. Teacher ko bhi notification bhejne ke liye bol sakte hain.")
            return redirect('portal-daily-mission-v3')

        from exams.models import StudentContribution
        from django.utils import timezone as _tz
        is_admin = request.user.is_superuser or request.user.is_staff
        has_contributed = StudentContribution.objects.filter(student=student).exists()
        contribution_skipped = request.session.get(
            f'contribution_skipped_{_tz.localdate().isoformat()}', False
        )
        gate_is_compulsory = not (has_contributed or is_admin or contribution_skipped)

        return render(request, 'exams/portal_practice.html', {
            'kc': kc,
            'student': student,
            'no_questions': True,
            'question_roadblock_prompt': build_question_prompt(kc),
            'gate_is_compulsory': gate_is_compulsory,
            'contribution_skipped': contribution_skipped,
        })

    question = random.choice(questions)

    # Get or create RPSItem with the required model_question and next_due_at
    from django.utils import timezone
    rps, _ = RPSItem.objects.get_or_create(
        student=student, 
        kc_code=kc_code,
        defaults={
            'model_question': question,
            'next_due_at': timezone.now()
        }
    )

    # NEW: VIP Pass for Contribution Mode
    contribute_mode = request.GET.get('contribute') == 'true'
    if contribute_mode:
        from exams.services.story_panel.prompt_builder import build_prompt as build_story_prompt
        story_prompt = build_story_prompt(kc)
        return render(request, 'exams/portal_practice.html', {
            'kc': kc,
            'student': student,
            'contribute_mode': True,
            'story_roadblock_prompt': story_prompt,
            'gate_is_compulsory': False,
        })

    if rps.mastery_probability >= 0.80:
        messages.success(request, "Aap ye concept already master kar chuke hain!")
        return redirect('portal-dashboard')

    bkt_params = BKTParams()

    if request.method == 'POST':
        action = request.POST.get('action')
        if action in ('correct', 'incorrect'):
            is_correct = (action == 'correct')
            # Update BKT
            new_prob = update(rps.mastery_probability, is_correct, bkt_params)
            rps.mastery_probability = new_prob
            rps.mastery_attempts += 1
            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}')
            
            if rps.mastery_probability >= 0.80:
                messages.success(request, "Mubarak ho! Ab Mastery Challenge ka waqt hai.")
                return redirect('portal-mastery-challenge', kc_code=kc.code)
            
            # Pick a new question for the next round
            question = random.choice(questions)

    return render(request, 'exams/portal_practice.html', {
        'kc': kc,
        'rps': rps,
        'question': question,
        'student': student,
        'mastery_pct': int(rps.mastery_probability * 100),
    })


@login_required
@login_required
def portal_mastery_challenge(request, kc_code):
    student = Student.objects.filter(is_active=True).first() if request.user.is_superuser else Student.objects.filter(student_user=request.user, is_active=True).first()
    _cls = ((student.student_class or '') if student else '').strip().lower()
    from exams.utils_class import allowed_classes_for
    _allowed_classes = allowed_classes_for(_cls) or ([_cls] if _cls else [])

    from exams.models import KnowledgeComponent, RPSItem, ModelQuestion, SupportTicket
    from academy.models import AcademyStudent, AcademyPoints, AcademyPointTx
    from django.utils import timezone
    from django.db import transaction
    import random
    import re

    if request.user.is_superuser:
        student = Student.objects.filter(is_active=True).first()
    else:
        student = Student.objects.filter(student_user=request.user, is_active=True).first()

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

    kc = get_object_or_404(KnowledgeComponent, code=kc_code)
    rps = RPSItem.objects.filter(student=student, kc_code=kc_code).first()

    if not rps:
        messages.error(request, "Pehle practice karein.")
        return redirect('portal-practice-kc', kc_code=kc_code)

    # IDOR/XSS FIX: filter out other students' SELF-/CUSTOM- questions
    from django.db.models import Q as _Q
    _qs = ModelQuestion.objects.filter(kc=kc, paper__student_class__in=_allowed_classes).exclude(model_answer='')
    if not request.user.is_superuser:
        _qs = _qs.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}')
        )
    questions = list(_qs)
    if not questions:
        messages.error(request, "Challenge ke liye koi sawal available nahi hai.")
        return redirect('portal-practice-kc', kc_code=kc_code)

    question = random.choice(questions)

    raw_sentences = re.split(r'(?<=[.!?])\s+', question.model_answer.strip())
    while len(raw_sentences) < 3:
        raw_sentences.append("Review the model answer carefully.")

    session_key = f'challenge_state_{kc_code}'
    state = request.session.get(session_key)

    required_keys = ['question_id', 'step', 'sentences', 'terms', 'start_time']
    if not state or not all(k in state for k in required_keys):
        state = {
            'question_id': question.id,
            'step': 1,
            'sentences': raw_sentences,
            'terms': [t.get('term') for t in kc.key_terms] if kc.key_terms else [kc.title],
            'start_time': timezone.now().isoformat()
        }
        request.session[session_key] = state

    start_time = timezone.datetime.fromisoformat(state['start_time'])
    if timezone.is_naive(start_time):
        start_time = timezone.make_aware(start_time)
    elapsed = (timezone.now() - start_time).total_seconds()

    if elapsed > 300:
        rps.mastery_attempts += 1
        rps.mastery_probability = max(0.1, 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}')
        del request.session[session_key]
        messages.error(request, "Time up! Aap challenge mein 3 minute se zyada lag gaye. Wapas practice par jayen.")
        return redirect('portal-practice-kc', kc_code=kc_code)

    question = ModelQuestion.objects.filter(
        id=state['question_id'],
        paper__student_class__in=_allowed_classes
    ).first()
    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')
    if not question:
        messages.error(request, 'Question not found or not allowed for your class.')
        return redirect('portal-practice-kc', kc_code=kc_code)
    sentences = state['sentences']
    step = state['step']

    from exams.services.points_ledger import get_balance
    balance = get_balance(student)

    # Ensure AcademyPoints row exists for clue spend/award audit (idempotent)
    acad_student = AcademyStudent.objects.filter(linked_code=student.code).first()
    if acad_student:
        points_obj, _ = AcademyPoints.objects.get_or_create(student=acad_student)
    else:
        points_obj = None

    if request.method == 'POST' and request.POST.get('action') == 'prev_step':
        if step > 1:
            state['step'] = step - 1
            request.session[session_key] = state
            return redirect('portal-mastery-challenge', kc_code=kc_code)
        return redirect('portal-mastery-challenge', kc_code=kc_code)

    if request.method == 'POST' and request.POST.get('action') == 'buy_clue':
        clue_cost = step
        if request.user.is_superuser:
            request.session[f'clue_{kc_code}'] = True
            messages.success(request, "Admin Clue unlocked! (Free)")
        elif balance >= clue_cost:
            with transaction.atomic():
                points_obj.balance -= clue_cost
                points_obj.spent_total += clue_cost
                points_obj.save()
                AcademyPointTx.objects.create(
                    student=acad_student,
                    delta=-clue_cost,
                    reason="Clue",
                    note=f"Mastery step {step}: {kc.code}"[:100]
                )
                request.session[f'clue_{kc_code}'] = True
            messages.success(request, f"Clue unlocked! -{clue_cost} points deducted.")
        else:
            messages.error(request, f"Aap ke paas kaafi points nahi hain! (Zaroorat: {clue_cost}, Aap ke paas: {balance})")
        return redirect('portal-mastery-challenge', kc_code=kc_code)

    mcq_options = []
    display_text = ""
    prompt = ""
    clue_hint = ""

    if step == 1:
        target = sentences[0]
        words = re.findall(r'[a-zA-Z]+', target)
        blank_word = max(words, key=len) if words else "concept"
        display_text = re.sub(re.escape(blank_word), '__________', target, flags=re.IGNORECASE)
        prompt = "Step 1: Select the correct missing word."
        clue_hint = f"Hint: The word starts with '{blank_word[:2]}...'"
        
        distractors = []
        for t in kc.key_terms:
            term = t.get('term', '')
            if term and term.lower() != blank_word.lower():
                distractors.append(term)
        all_words = re.findall(r'[a-zA-Z]+', " ".join(sentences))
        for w in all_words:
            if len(w) > 3 and w.lower() != blank_word.lower() and w not in distractors:
                distractors.append(w)
            if len(distractors) >= 3: break
        while len(distractors) < 3: distractors.append(blank_word) # Fallback to avoid crash
        mcq_options = [blank_word] + distractors[:3]
        random.shuffle(mcq_options)

    elif step == 2:
        target = sentences[1]
        words = re.findall(r'[a-zA-Z]+', target)
        blank_word = max(words, key=len) if words else "concept"
        display_text = re.sub(re.escape(blank_word), '__________', target, flags=re.IGNORECASE)
        prompt = "Step 2: Select the correct missing word."
        clue_hint = f"Hint: The word starts with '{blank_word[:2]}...'"
        
        distractors = []
        for t in kc.key_terms:
            term = t.get('term', '')
            if term and term.lower() != blank_word.lower():
                distractors.append(term)
        all_words = re.findall(r'[a-zA-Z]+', " ".join(sentences))
        for w in all_words:
            if len(w) > 3 and w.lower() != blank_word.lower() and w not in distractors:
                distractors.append(w)
            if len(distractors) >= 3: break
        while len(distractors) < 3: distractors.append(blank_word) # Fallback to avoid crash
        mcq_options = [blank_word] + distractors[:3]
        random.shuffle(mcq_options)

    elif step == 3:
        display_text = "Which of the following is the correct final conclusion for this concept?"
        prompt = "Step 3: Choose the correct conclusion."
        clue_hint = "Hint: Look for the sentence that perfectly summarizes the concept."
        
        # Dynamically generate sentence distractors from other questions
        distractor_sents = []
        other_qs = ModelQuestion.objects.filter(kc=kc, paper__student_class__in=_allowed_classes).exclude(id=question.id).exclude(model_answer='')[:5]
        for oq in other_qs:
            oq_sents = re.split(r'(?<=[.!?])\s+', oq.model_answer.strip())
            if len(oq_sents) >= 3:
                distractor_sents.append(oq_sents[2])
            elif oq_sents:
                distractor_sents.append(oq_sents[-1])
        
        # Fallback to the first two sentences of the current question
        if sentences[0] not in distractor_sents: distractor_sents.append(sentences[0])
        if sentences[1] not in distractor_sents: distractor_sents.append(sentences[1])
        
        # Ensure we have 3 unique distractors
        distractor_sents = list(dict.fromkeys(distractor_sents))[:3]
        while len(distractor_sents) < 3:
            distractor_sents.append(sentences[0]) # Safe fallback
            
        mcq_options = [sentences[2]] + distractor_sents
        random.shuffle(mcq_options)

    if request.method == 'POST' and 'selected_option' in request.POST:
        answer = request.POST.get('selected_option', '').strip()
        passed = False
        failed_msg = ""

        if step == 1:
            target = sentences[0]
            blank_word = max(re.findall(r'[a-zA-Z]+', target), key=len) if re.findall(r'[a-zA-Z]+', target) else "concept"
            if answer.lower() == blank_word.lower(): passed = True
            else: failed_msg = f"Step 1 fail. Sahi lafz tha: '{blank_word}'"
        elif step == 2:
            target = sentences[1]
            blank_word = max(re.findall(r'[a-zA-Z]+', target), key=len) if re.findall(r'[a-zA-Z]+', target) else "concept"
            if answer.lower() == blank_word.lower(): passed = True
            else: failed_msg = f"Step 2 fail. Sahi lafz tha: '{blank_word}'"
        elif step == 3:
            if answer.strip() == sentences[2].strip(): passed = True
            else: failed_msg = "Step 3 fail. Aap ne ghalat conclusion select kiya."

        if passed:
            # Award +1 point for solving the step
            try:
                from exams.services import points_ledger
                points_ledger.award(
                    student=student,
                    points=1,
                    reason=f'Mastery Step {step} passed for {kc.code}',
                    code='MASTERY_STEP',
                    evidence={'qid': rps.model_question_id, 'step': step},
                    source='AUTO',
                )

                messages.success(request, "🎉 Correct! You earned +1 point.")
            except Exception as e:
                print(f"Point award error: {e}")

            if step < 3:
                state['step'] += 1
                request.session[session_key] = state
                request.session[f'clue_{kc_code}'] = False
                messages.success(request, f"Step {step} clear! Next step.")
                return redirect('portal-mastery-challenge', kc_code=kc_code)
            else:
                rps.mastery_probability = 1.0
                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}')
                del request.session[session_key]
                if f'clue_{kc_code}' in request.session:
                    del request.session[f'clue_{kc_code}']
                messages.success(request, "Mubarak ho! Aap ne Mastery haasil kar li.")
                return redirect('portal-daily-mission-v3')
        else:
            rps.mastery_attempts += 1
            rps.mastery_probability = max(0.1, 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}')
            del request.session[session_key]
            if f'clue_{kc_code}' in request.session:
                del request.session[f'clue_{kc_code}']

            if rps.mastery_attempts >= 3:
                try:
                    SupportTicket.objects.get_or_create(
                        student=student,
                        subject=f"Mastery Failed: {kc.code}",
                        defaults={
                            'category': 'ACADEMIC',
                            'priority': 'HIGH',
                            'status': 'OPEN',
                            'body': f"Failed 3-step faded example on {kc.code}.",
                            'opened_by': student.student_user if student.student_user else None,
                        }
                    )
                    messages.warning(request, "Aap 3 baar fail ho chuke hain. Teacher ko alert bhej diya gaya hai.")
                except Exception as e:
                    messages.warning(request, "Aap 3 baar fail ho chuke hain.")
            else:
                messages.error(request, failed_msg + " Wapas practice par jayen.")
            return redirect('portal-practice-kc', kc_code=kc_code)

    has_clue = request.session.get(f'clue_{kc_code}', False)
    remaining = max(0, 300 - int(elapsed))

    # Pull the question story for the clue
    story_clue = question.explanation or (kc.story[0] if kc.story and isinstance(kc.story, list) else "")

    return render(request, 'exams/portal_mastery_challenge.html', {
        'kc': kc,
        'question': question,
        'story_clue': story_clue,
        'display_text': display_text,
        'step': step,
        'prompt': prompt,
        'remaining_seconds': remaining,
        'balance': balance,
        'has_clue': has_clue,
        'clue_hint': clue_hint,
        'mcq_options': mcq_options,
    })

@login_required
def save_roadblock_content(request, kc_code, field_name):
    import json
    import re
    from django.http import JsonResponse
    from exams.models import KnowledgeComponent

    from exams.views_v3 import _current_student
    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')

    ai_response = request.POST.get('ai_response', '').strip()
    if not ai_response:
        messages.error(request, "AI response cannot be empty.")
        return redirect(request.META.get('HTTP_REFERER', 'portal-task-hub'))

    # Clean the JSON (strip markdown fences if AI included them)
    clean_json = re.sub(r'^```(?:json)?\s*', '', ai_response)
    clean_json = re.sub(r'\s*```$', '', clean_json)
    
    # Find first { and last }
    start = clean_json.find('{')
    end = clean_json.rfind('}')
    if start != -1 and end != -1:
        clean_json = clean_json[start:end+1]

    try:
        payload = json.loads(clean_json)
    except json.JSONDecodeError as e:
        messages.error(request, f"Invalid JSON format. Error: {str(e)[:100]}")
        return redirect(request.META.get('HTTP_REFERER', 'portal-task-hub'))

    kc = get_object_or_404(KnowledgeComponent, code=kc_code)
    
    # Save based on field
    try:
        if field_name == 'question_story':
            q_id = request.POST.get('question_id')
            if not q_id:
                messages.error(request, "Question ID missing.")
            else:
                from exams.models import ModelQuestion
                from django.db.models import Q as _Q
                _qs = ModelQuestion.objects.filter(paper__student_class__in=_allowed_classes)
                if not request.user.is_superuser:
                    _cs = _current_student(request)
                    if _cs:
                        _qs = _qs.filter(
                            (~_Q(paper__code__startswith='SELF-') & ~_Q(paper__code__startswith='CUSTOM-'))
                            | _Q(paper__code__startswith=f'SELF-{_cs.code}')
                            | _Q(paper__code__startswith=f'CUSTOM-{_cs.code}')
                        )
                    else:
                        _qs = _qs.none()
                q_obj = _qs.filter(id=q_id).first()
                if q_obj:
                    story_text = payload.get('story') or payload.get('text') or ''
                    if isinstance(story_text, list):
                        story_text = ' '.join(str(s) for s in story_text)
                    story_text = str(story_text).strip()
                    if len(story_text) < 30:
                        messages.error(request, "Story too short.")
                    else:
                        q_obj.explanation = story_text
                        q_obj.save(update_fields=['explanation'])
                        messages.success(request, f"✅ Story added for Question {q_obj.question_index}!")
                else:
                    messages.error(request, "Question not found.")
        elif field_name == 'misconceptions':
            kc.misconceptions = payload.get('misconceptions', [])
            kc.save(update_fields=['misconceptions', 'updated_at'])
            messages.success(request, f"✅ {kc.code}: Misconceptions successfully added! Sab students ke liye unlock ho gaya.")
        elif field_name == 'socratic_ladder':
            kc.socratic_ladder = payload.get('socratic_ladder', [])
            kc.save(update_fields=['socratic_ladder', 'updated_at'])
            messages.success(request, f"✅ {kc.code}: Socratic Ladder successfully added!")
        elif field_name == 'resource_links':
            # Accept either {"resource_links": [...]} or plain list, or a single URL string
            new_links = payload.get('resource_links')
            if new_links is None and isinstance(payload, list):
                new_links = payload
            if new_links is None:
                # Fallback: whole payload might be a single URL
                url_val = payload.get('url') or payload.get('link') or ''
                if url_val:
                    new_links = [{'kind': 'link', 'label': 'User contributed', 'url': url_val}]
            if new_links and isinstance(new_links, list):
                kc.resource_links = new_links
                kc.save(update_fields=['resource_links', 'updated_at'])
                messages.success(request, f"✅ {kc.code}: Learning resource added! Sab students ke liye available.")
            else:
                messages.error(request, "Invalid format. Use: {\"resource_links\": [{\"kind\":\"youtube\",\"label\":\"...\",\"url\":\"...\"}]}")
        elif field_name == 'description':
            new_desc = payload.get('description') or payload.get('text') or ''
            if new_desc and len(new_desc) >= 15:
                kc.description = new_desc
                kc.save(update_fields=['description', 'updated_at'])
                messages.success(request, f"✅ {kc.code}: Description added! Sab students ke liye available.")
            else:
                messages.error(request, "Description too short (min 15 chars). Use: {\"description\": \"...\"}")
        elif field_name == 'key_terms':
            kc.key_terms = payload.get('key_terms', [])
            kc.save(update_fields=['key_terms', 'updated_at'])
            messages.success(request, f"✅ {kc.code}: Key Terms successfully added! Sab students ke liye unlock ho gaya.")
        elif field_name == 'story':
            story_text = ''
            if isinstance(payload, dict):
                story_text = payload.get('story') or payload.get('text') or payload.get('final_story') or ''
            if isinstance(story_text, list):
                story_text = ' '.join(str(s) for s in story_text)
            story_text = str(story_text).strip()
            if len(story_text) < 50:
                messages.error(request, f'Story too short ({len(story_text)} chars). Paste full text.')
            else:
                kc.story = [story_text]
                kc.story_status = 'TEACHER_OVERRIDE'
                kc.save(update_fields=['story', 'story_status', 'updated_at'])
                messages.success(request, f'✅ {kc.code}: Story added! Sab students ke liye unlock ho gaya.')
        elif field_name == 'pokemon_lore':
            kc.monster_name = payload.get('monster_name_en', '')[:60]
            kc.monster_type = payload.get('monster_type', '')
            kc.monster_lore = {
                'name_en': payload.get('monster_name_en', ''),
                'name_ur': payload.get('monster_name_ur', ''),
                'lore_en': payload.get('lore_en', ''),
                'lore_ur': payload.get('lore_ur', ''),
                'cry_en': payload.get('battle_cry_en', ''),
                'cry_ur': payload.get('battle_cry_ur', ''),
                'rarity': payload.get('rarity', 'Common'),
                'hp_base': payload.get('hp_base', 100),
                'concept_traits': payload.get('concept_traits', []),
            }
            kc.save(update_fields=['monster_name', 'monster_type', 'monster_lore', 'updated_at'])
            messages.success(request, f"✅ {kc.code}: Monster lore added! Sab students ke liye unlock ho gaya.")
        elif field_name == 'practice_questions':
            from exams.models import ModelPaper, ModelQuestion
            from django.utils.text import slugify
            qs_data = payload.get('questions', [])
            if not qs_data:
                messages.error(request, "No questions found in AI output.")
            else:
                from exams.services.text_cleaner import strip_tags as _st
                from django.db import transaction as _tx
                from django.db.models import Max as _Max
                _subj = (kc.subject or 'General').strip() or 'General'
                # SECURITY FIX: SELF-prefix scopes paper to contributor only
                # (was AI-ROADBLOCK-{subject} = global paper = cross-student XSS vector)
                _contrib_s = _current_student(request)
                if _contrib_s:
                    paper_code = f"SELF-{_contrib_s.code}-RB-{_subj}".replace(' ', '-').upper()[:30]
                else:
                    paper_code = f"AI-ROADBLOCK-{_subj}".replace(' ', '-').upper()[:30]
                with _tx.atomic():
                    paper, created = ModelPaper.objects.get_or_create(
                        code=paper_code,
                        defaults={
                            'subject': _subj,
                            'medium': 'en',
                            'title': f'AI Roadblock Practice — {_subj}',
                            'total_questions': 0,
                            'source_note': 'Auto-generated by student via roadblock fixer',
                        }
                    )
                    existing_max = ModelQuestion.objects.filter(paper=paper).aggregate(
                        mx=_Max('question_index')
                    )['mx'] or 0
                    added = 0
                    for i, q in enumerate(qs_data[:3]):
                        idx = existing_max + i + 1
                        slug = f"{kc.code.lower()}-rq{idx}"[:80]
                        try:
                            ModelQuestion.objects.create(
                                paper=paper,
                                question_index=idx,
                                question_text=_st(q.get('question_text_en', '')),
                                model_answer=_st(q.get('model_answer_en', '')),
                                kc_code=kc.code,
                                kc=kc,
                                marks=q.get('marks', 2),
                                question_slug=slug,
                                explanation=_st(q.get('explanation_en', '')),
                                socratic_hint=_st(q.get('socratic_hint_en', '')),
                                translated_question_text=_st(q.get('question_text_ur', '')),
                                translated_model_answer=_st(q.get('model_answer_ur', '')),
                            )
                            added += 1
                        except Exception as qe:
                            print(f"[QUESTION CREATE ERROR] {qe}")
                    paper.total_questions = ModelQuestion.objects.filter(paper=paper).count()
                    paper.save(update_fields=['total_questions'])
                messages.success(
                    request,
                    f"✅ {kc.code}: {added} practice questions added to paper '{paper.code}'. Sab students ke liye unlock ho gaya."
                )
        else:
            messages.error(request, "Unknown field type.")
    except Exception as e:
        messages.error(request, f"Error saving: {str(e)}")

    # Redirect back to the result page
    # Log the contribution (satisfies compulsory gate on first save)
    # Log the contribution (satisfies compulsory gate and awards points)
    try:
        from exams.models import StudentContribution, Student as _S, CreditEvent
        _contrib_student = _S.objects.filter(student_user=request.user, is_active=True).first()
        if not _contrib_student and request.user.is_superuser:
            _contrib_student = _S.objects.filter(is_active=True).first()
        if _contrib_student:
            from django.db import transaction as _tx2
            with _tx2.atomic():
                contrib, created = StudentContribution.objects.get_or_create(
                    student=_contrib_student,
                    kc_code=kc.code,
                    field_type=field_name,
                )
                if created:
                    from exams.services import points_ledger
                    points_ledger.award(
                        student=_contrib_student,
                        points=1,
                        reason=f'Contributed {field_name} for {kc.code}',
                        code='CONTRIBUTION_REWARD',
                        evidence={'contribution_id': contrib.id},
                        source='AUTO',
                    )
                messages.success(request, "You earned +1 point for this contribution!")
    except Exception as e:
        print(f"[CONTRIBUTION LOG ERROR] {e}")

    return_url = request.POST.get('return_url', '').strip()
    if return_url:
        from django.utils.http import url_has_allowed_host_and_scheme
        if url_has_allowed_host_and_scheme(return_url, allowed_hosts={request.get_host()}, require_https=request.is_secure()):
            return redirect(return_url)

    if field_name == 'practice_questions':
        return redirect('portal-practice-kc', kc_code=kc.code)

    exam_id = request.POST.get('exam_id')
    if exam_id:
        return redirect('portal-attempt-result-with-id', exam_id=exam_id)
    return redirect('portal-daily-mission-v3')


# ═══════════════════════════════════════════════════════════════
# Step-by-Step Math Reasoning (per Newman + Carnegie standards)
# ═══════════════════════════════════════════════════════════════
@login_required
def portal_step_reasoning(request, qid):
    """Serve step-by-step reasoning for a math/physics question.

    - If reasoning_chain has steps: walk through with MCQ per step.
    - If empty: show 'Help Build This' roadblock with prompt.
    - After 2 wrong attempts per step: reveal correct answer, advance.
    - On completion: update KCCard mastery based on retries.
    """
    from exams.models import ModelQuestion, KCCard
    from django.utils import timezone

    from exams.views_v3 import _current_student
    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))
    # Resolve student
    if request.user.is_superuser:
        student = Student.objects.filter(is_active=True).first()
    else:
        student = Student.objects.filter(student_user=request.user, is_active=True).first()

    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)

    # Load steps from reasoning_chain
    steps = []
    rc = question.reasoning_chain
    if isinstance(rc, dict):
        steps = rc.get('steps', []) or []
    elif isinstance(rc, list):
        steps = rc

    # If no steps: show roadblock (with skip if student has contributed)
    if not steps:
        from exams.services.story_panel.prompt_templates import build_step_reasoning_prompt
        from exams.models import StudentContribution
        from django.utils import timezone as _tz
        is_admin = request.user.is_superuser or request.user.is_staff
        has_contributed = StudentContribution.objects.filter(student=student).exists()
        contribution_skipped = request.session.get(
            f'contribution_skipped_{_tz.localdate().isoformat()}', False
        )
        can_skip = has_contributed or is_admin or contribution_skipped
        return render(request, 'exams/portal_step_reasoning.html', {
            'question': question,
            'student': student,
            'no_steps': True,
            'step_prompt': build_step_reasoning_prompt(question),
            'has_contributed': has_contributed,
            'can_skip': can_skip,
        })

    total_steps = len(steps)
    session_key = f'step_reasoning_{qid}'
    state = request.session.get(session_key)

    # Initialize session
    if not state or 'step' not in state:
        state = {
            'step': 0,
            'wrong': 0,
            'attempts': [],  # [{step, ok, revealed}]
            'started_at': timezone.now().isoformat(),
        }
        request.session[session_key] = state

    # Handle POST (answer choice)
    if request.method == 'POST':
        try:
            choice = int(request.POST.get('choice', -1))
        except (ValueError, TypeError):
            choice = -1

        current_idx = state['step']
        if current_idx >= total_steps:
            # Session already complete — reset
            del request.session[session_key]
            return redirect('portal-step-reasoning', qid=qid)

        current_step = steps[current_idx]
        correct_idx = current_step.get('correct_index', 0)

        if choice == correct_idx:
            # Correct
            state['attempts'].append({'step': current_idx + 1, 'ok': True})
            state['step'] += 1
            state['wrong'] = 0
            request.session[session_key] = state

            if state['step'] >= total_steps:
                return _finish_step_session(request, student, question, state, session_key)

            messages.success(request, f"✓ Sahi! Step {current_idx + 1} mukammal.")
            return redirect('portal-step-reasoning', qid=qid)
        else:
            state['wrong'] += 1
            if state['wrong'] >= 2:
                # Reveal correct, advance
                state['attempts'].append({
                    'step': current_idx + 1,
                    'ok': False,
                    'revealed': True,
                    'correct_text': (current_step.get('options', [{}])[correct_idx] or {}).get('text', ''),
                })
                state['step'] += 1
                state['wrong'] = 0
                request.session[session_key] = state

                if state['step'] >= total_steps:
                    return _finish_step_session(request, student, question, state, session_key)

                correct_display = (current_step.get('options', [{}])[correct_idx] or {}).get('text', '')
                messages.warning(request, f"Sahi jawab: {correct_display}. Agla step dekhein.")
                return redirect('portal-step-reasoning', qid=qid)
            else:
                request.session[session_key] = state
                messages.error(request, "Ghalat jawab. Hint dekhein aur dobara koshish karein.")
                return redirect('portal-step-reasoning', qid=qid)

    # GET — render current step
    current_idx = state['step']
    if current_idx >= total_steps:
        # Already complete — restart
        del request.session[session_key]
        return redirect('portal-step-reasoning', qid=qid)

    current_step = steps[current_idx]
    options = current_step.get('options', [])

    return render(request, 'exams/portal_step_reasoning.html', {
        'question': question,
        'student': student,
        'current_step': current_step,
        'current_step_num': current_idx + 1,
        'total_steps': total_steps,
        'options': options,
        'correct_index': current_step.get('correct_index', 0),
        'progress_pct': int(((current_idx) / total_steps) * 100),
        'attempt_number': state['wrong'] + 1,
        'show_hint': state['wrong'] >= 1,
        'no_steps': False,
    })


def _finish_step_session(request, student, question, state, session_key):
    """Called when all steps complete.
    Uses RPSItem.mastery_probability (BKT) for mastery tracking
    and KCCard for spaced-repetition state (FSRS).
    """
    from exams.models import KCCard, RPSItem, KnowledgeComponent
    from django.utils import timezone

    kc = getattr(question, 'kc', None) or KnowledgeComponent.objects.filter(
        code=question.kc_code
    ).first()

    all_correct = all(a.get('ok') for a in state.get('attempts', []))
    any_revealed = any(a.get('revealed') for a in state.get('attempts', []))

    if kc:
        # ── RPSItem holds mastery_probability (BKT) ──
        rps, _ = RPSItem.objects.get_or_create(
            student=student,
            kc_code=kc.code,
            defaults={
                'model_question': question,
                'next_due_at': timezone.now(),
            }
        )
        prior = rps.mastery_probability or 0.3
        if all_correct:
            rps.mastery_probability = min(1.0, prior + 0.2)
        elif not any_revealed:
            rps.mastery_probability = min(1.0, prior + 0.1)
        if rps.mastery_probability >= 0.80:
            rps.mastery_state = 'MASTERED'
        rps.mastery_attempts = (rps.mastery_attempts or 0) + 1
        rps.last_attempted_at = timezone.now()
        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}')

        # ── KCCard holds FSRS spaced-repetition state ──
        kc_card, _ = KCCard.objects.get_or_create(student=student, kc=kc)
        if rps.mastery_probability >= 0.80:
            kc_card.state = 'MASTERED'
        elif kc_card.state == 'NEW':
            kc_card.state = 'LEARNING'
        kc_card.reps = (kc_card.reps or 0) + 1
        kc_card.last_review_at = timezone.now()
        kc_card.save()

    # Clean session
    del request.session[session_key]

    attempts = state.get('attempts', [])
    correct_count = sum(1 for a in attempts if a.get('ok'))
    total = len(attempts)

    return render(request, 'exams/portal_step_reasoning.html', {
        'question': question,
        'student': student,
        'session_complete': True,
        'total_steps': total,
        'correct_count': correct_count,
        'all_correct': all_correct,
        'any_revealed': any_revealed,
        'no_steps': False,
    })


@login_required
def save_step_reasoning(request, qid):
    """Save AI-generated reasoning steps to question.reasoning_chain."""
    import json
    import re
    from exams.models import ModelQuestion
    from django.http import JsonResponse
    from exams.views_v3 import _current_student

    from exams.views_v3 import _current_student
    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)

    # IDOR + CONTENT-POISONING FIX: standard-question reasoning = staff only.
    # Students can only contribute to own SELF-/CUSTOM- (self-XSS only).
    _cs = _current_student(request)
    if request.user.is_superuser or request.user.is_staff:
        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:
        if not _cs:
            return JsonResponse({'error': 'No student linked.'}, status=403)
        from django.db.models import Q as _Q
        _allowed = ModelQuestion.objects.filter(
            _Q(paper__code__startswith=f'SELF-{_cs.code}') |
            _Q(paper__code__startswith=f'CUSTOM-{_cs.code}')
        )
        question = get_object_or_404(_allowed, id=qid)
    raw = (request.POST.get('ai_response') or '').strip()

    if not raw:
        return JsonResponse({'error': 'empty'}, status=400)

    # Clean JSON (strip markdown fences)
    clean = re.sub(r'^```(?:json)?\s*', '', raw)
    clean = re.sub(r'\s*```$', '', clean)
    s = clean.find('{')
    e = clean.rfind('}')
    if s != -1 and e != -1:
        clean = clean[s:e+1]

    try:
        payload = json.loads(clean)
    except json.JSONDecodeError as ex:
        return JsonResponse({'error': f'invalid_json: {str(ex)[:100]}'}, status=400)

    steps = payload.get('steps', [])
    if not steps or not isinstance(steps, list):
        return JsonResponse({'error': 'no_steps'}, status=400)

    question.reasoning_chain = {
        'question_id': qid,
        'kc_code': payload.get('kc_code', question.kc_code),
        'total_steps': len(steps),
        'steps': steps,
        'source': 'student_contribution',
    }
    question.save(update_fields=['reasoning_chain', 'updated_at'])

    return JsonResponse({'ok': True, 'steps_saved': len(steps)})


@login_required
def portal_skip_notes(request):
    """Mark today's notes as skipped. Unlocks daily mission for today only.
    Auto-expires at midnight (session key includes date)."""
    from django.utils import timezone
    if request.method != 'POST':
        return redirect('portal-my-notes')

    today = timezone.localdate()
    request.session[f'notes_skipped_{today.isoformat()}'] = True
    messages.success(
        request,
        "📝 Aaj ke notes skip kiye. Daily Mission par jayen."
    )
    return redirect('portal-daily-mission')



@login_required
def portal_skip_contribution(request):
    """Mark today's contribution as skipped. Unlocks gated content for today only.
    Auto-expires at midnight (session key includes date)."""
    from django.utils import timezone
    if request.method != 'POST':
        return redirect('portal-daily-mission-v3')

    today = timezone.localdate()
    request.session[f'contribution_skipped_{today.isoformat()}'] = True
    messages.success(
        request,
        "Aaj ke liye contribution skip ki. Aap aaram se practice kar sakte hain — kal phir yaad dilayenge."
    )
    return redirect('portal-daily-mission-v3')



@login_required
def portal_profile_edit(request):
    from exams.models import Student
    from django.contrib import messages
    from django.shortcuts import render, redirect
    from django.contrib.auth import update_session_auth_hash
    
    student = Student.objects.filter(student_user=request.user, is_active=True).first()
    if not student:
        return redirect('portal-dashboard')

    if request.method == 'POST':
        first = request.POST.get('first_name', '').strip()
        last = request.POST.get('last_name', '').strip()
        cls = request.POST.get('student_class', '').strip()
        pace = request.POST.get('daily_question_count', '4').strip()
        gender = request.POST.get('gender', 'M').strip()
        new_password = request.POST.get('new_password', '').strip()
        confirm_password = request.POST.get('confirm_password', '').strip()

        if not first:
            messages.error(request, "First name cannot be empty.")
        else:
            student.first_name = first
            student.last_name = last
            student.name = f"{first} {last}".strip()
            request.user.first_name = first
            request.user.last_name = last
            request.user.save(update_fields=['first_name', 'last_name'])
            from academy.models import AcademyStudent
            acad = AcademyStudent.objects.filter(linked_code=student.code).first()
            if acad:
                acad.full_name = student.name
                acad.save(update_fields=['full_name'])
            student.student_class = cls
            try:
                student.daily_question_count = max(1, min(10, int(pace)))
            except ValueError:
                student.daily_question_count = 4
            student.gender = gender
            student.save()

            if new_password:
                if new_password != confirm_password:
                    messages.error(request, "Passwords do not match.")
                    return render(request, 'exams/portal_profile_edit.html', {'student': student})
                request.user.set_password(new_password)
                request.user.save()
                update_session_auth_hash(request, request.user) # Keeps them logged in
                messages.success(request, "✓ Profile and password updated successfully.")
            else:
                messages.success(request, "✓ Profile updated successfully.")
            
            return redirect('portal-profile-edit')

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


@login_required
def save_custom_kc(request, qid):
    import json
    from exams.models import ModelQuestion, KnowledgeComponent
    from exams.views_v3 import _current_student
    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))
    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')
    
    if request.method == 'POST':
        raw_json = request.POST.get('ai_response', '').strip()
        if not raw_json:
            messages.error(request, 'JSON paste karein.')
            return redirect('portal-daily-mission-v3')
            
        try:
            raw_json = raw_json.replace('```json', '').replace('```', '').strip()
            data = json.loads(raw_json)
            
            # Create the KC
            kc_code = f"CUSTOM-KC-{question.id}"
            kc, created = KnowledgeComponent.objects.get_or_create(
                code=kc_code,
                defaults={
                    'title': data.get('title', question.question_text[:50]),
                    'subject': question.paper.subject or 'Personalized',
                    'story': data.get('story', []),
                    'misconceptions': data.get('misconceptions', []),
                    'socratic_ladder': data.get('socratic_ladder', []),
                    'key_terms': data.get('key_terms', []),
                    'is_active': True
                }
            )
            
            # Link to question
            question.kc = kc
            question.kc_code = kc_code
            question.save(update_fields=['kc', 'kc_code'])
            
            messages.success(request, 'Boss Fight unlocked! KC successfully generated.')
            return redirect('portal-daily-mission-v3')
            
        except Exception as e:
            messages.error(request, f'Error parsing JSON: {str(e)}')
            return redirect('portal-daily-mission-v3')

    # Generate the prompt
    prompt = f"""You are an Expert Curriculum Designer. Generate a Knowledge Component (KC) for the following question.
    
Question: {question.question_text}
Model Answer: {question.model_answer}

Return ONLY a valid JSON object with this exact schema:
{{
    "title": "Short Title of the Concept",
    "story": ["Paragraph 1 of story", "Paragraph 2 of story"],
    "misconceptions": [{{"text": "Common mistake", "mechanism": "Why it happens"}}],
    "socratic_ladder": [{{"question": "Guiding question?", "hint": "Small hint"}}],
    "key_terms": [{{"term": "Keyword", "definition": "Meaning"}}]
}}"""

    return render(request, 'exams/portal_save_custom_kc.html', {
        'question': question,
        'prompt': prompt
    })


@login_required
def prepare_stage_content(request):
    try:
        return _prepare_stage_content_impl(request)
    except Exception:
        import traceback
        log_path = '/tmp/prepare_stage_error.log'
        with open(log_path, 'w') as f:
            f.write(traceback.format_exc())
        raise


def _prepare_stage_content_impl(request):
    """Pre-stage content preparation gate. Blocks stage entry until KC content exists."""
    import json
    from exams.models import KnowledgeComponent, ModelQuestion, StudentQuestionLock

    from exams.views_v3 import _current_student
    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))
    student = Student.objects.filter(student_user=request.user, is_active=True).first()
    if not student:
        return redirect('portal-dashboard')

    stage = (request.GET.get('stage') or 'STUDY').upper()
    book = request.GET.get('book', '').strip()

    if request.method == 'POST':
        stage = request.POST.get('stage', 'STUDY').upper()
        book = request.POST.get('book', '').strip()
        raw = request.POST.get('ai_response', '').strip()

        if not raw:
            messages.error(request, 'JSON paste karein.')
            return redirect(f'/api/portal/prepare-stage/?stage={stage}&book={book}')

        try:
            # Robust JSON extraction (strips markdown and extracts object)
            match = re.search(r'\{.*\}', raw, re.DOTALL)
            if match:
                raw = match.group(0)
            data = json.loads(raw)
            saved = 0
            for q_data in data.get('questions', []):
                q_id = q_data.get('question_id')
                if not q_id:
                    continue
                try:
                    question = ModelQuestion.objects.filter(
                        id=q_id, 
                        paper__student_class__in=_allowed_classes
                    ).first()
                    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')
                    if not question:
                        continue
                except Exception:
                    continue
                kc_code = question.kc_code or f"AUTO-KC-{q_id}"
                kc, _ = KnowledgeComponent.objects.get_or_create(
                    code=kc_code,
                    defaults={
                        'title': q_data.get('title', question.question_text[:50]),
                        'subject': (question.paper.subject if question.paper else 'Personalized') or 'Personalized',
                    }
                )
                if q_data.get('story'):
                    kc.story = q_data['story']
                if q_data.get('misconceptions'):
                    kc.misconceptions = q_data['misconceptions']
                if q_data.get('socratic_ladder'):
                    kc.socratic_ladder = q_data['socratic_ladder']
                if q_data.get('key_terms'):
                    kc.key_terms = q_data['key_terms']
                kc.is_active = True
                kc.save()

                question.kc = kc
                question.kc_code = kc_code
                question.save(update_fields=['kc', 'kc_code'])
                saved += 1

            messages.success(request, f'✓ {saved} questions prepared. Stage unlocked.')
            return redirect(f'/api/portal/daily-mission-v3/?stage={stage}&book={book}')
        except json.JSONDecodeError as e:
            messages.error(request, f'Invalid JSON: {e}')
            return redirect(f'/api/portal/prepare-stage/?stage={stage}&book={book}')

    # GET — identify gaps
    locks = StudentQuestionLock.objects.filter(student=student, is_active=True)
    if book:
        locks = locks.filter(question__paper__subject__iexact=book)

    required = ['story'] if stage in ('STUDY', 'REMEDIATION') else ['misconceptions', 'socratic_ladder', 'key_terms']

    gaps = []
    for lock in locks.select_related('question', 'question__kc'):
        q = lock.question
        if not q.kc:
            gaps.append({'question': q, 'missing': required + ['KC']})
            continue
        missing = [f for f in required if not getattr(q.kc, f, None)]
        if missing:
            gaps.append({'question': q, 'missing': missing})

    if not gaps:
        return redirect(f'/api/portal/daily-mission-v3/?stage={stage}&book={book}')

    questions_data = [{
        'question_id': g['question'].id,
        'question_text': g['question'].question_text,
        'model_answer': g['question'].model_answer or '',
        'missing_fields': g['missing'],
    } for g in gaps]

    from exams.services.kc_prompt import build_kc_prompt
    subject_for_prompt = (book or 'Personalized').strip()
    questions_json = json.dumps(questions_data, indent=2, ensure_ascii=False)

    # Build three tier-calibrated KC prompts (Basic / Standard / Advanced)
    tier_prompts = {
        1: build_kc_prompt(subject_for_prompt, 1, questions_data),
        2: build_kc_prompt(subject_for_prompt, 2, questions_data),
        3: build_kc_prompt(subject_for_prompt, 3, questions_data),
    }

    return render(request, 'exams/portal_content_prep.html', {
        'gaps': gaps,
        'requested_stage': stage,
        'current_book': book,
        'tier_prompts': tier_prompts,
        'subject_name': subject_for_prompt,
        'prompt_json': questions_json,
    })



def _filtered_subjects(student):
    from exams.services.daily_mission_engine import get_available_subjects
    from exams.models import ModelPaper
    _cls = (student.student_class or '').strip().lower()
    _allowed = ['9', '9th', '9th class'] if _cls.startswith('9') else [_cls]
    valid_subs = set(ModelPaper.objects.filter(student_class__in=_allowed).values_list('subject', flat=True))
    return [s for s in get_available_subjects() if s in valid_subs]
