"""Daily Mission Engine — Preparation (24 Qs) + Test Code (1 Q per book)."""
import random
from django.utils import timezone
from exams.models import ModelQuestion, StudentQuestionLock, ModelPaper, StudentDailyCode
from exams.services.subject_normalizer import unique_canonical_subjects

def get_student_books(student):
    from exams.models import StudentQuestionLock
    _cls = (student.student_class or '').strip().lower()
    is_board_class = _cls.startswith('9') or _cls.startswith('10') or _cls.startswith('11') or _cls.startswith('12')

    if not is_board_class:
        # 1. Use active locks if they exist
        subjects = set(StudentQuestionLock.objects.filter(student=student, is_active=True) \
            .values_list('question__paper__subject', flat=True).distinct())

        # 2. Derive from ingested ModelPapers for this class (Industry Standard)
        from exams.models import ModelPaper
        paper_subjects = set(ModelPaper.objects.filter(student_class=_cls) \
            .values_list('subject', flat=True).distinct())

        combined = subjects.union(paper_subjects)
        if combined:
            return list(combined)

        # 3. Ultimate fallback if school hasn't ingested anything yet
        return ['Urdu', 'English', 'Mathematics', 'Science']

    # Board classes (9th and 10th) — ALWAYS return fixed list
    if _cls.startswith('10'):
        fixed_books = ['Urdu', 'English', 'Pak Study', 'Mathematics', 'Chemistry', 'Physics', 'Tarjumatul Quran']
    elif _cls.startswith('11') or _cls.startswith('12'):
        # Class 11 & 12 comprehensive list (Humanities, Pre-Med, Pre-Eng, ICS, Commerce)
        fixed_books = [
            'Urdu', 'English', 'Islamiyat', 'Pak Study', 'Tarjumatul Quran', 
            'Economics', 'Civics', 'Islamiyat Optional', 
            'Mathematics', 'Physics', 'Chemistry', 'Biology', 'Computer Science'
        ]
    else:
        fixed_books = ['Urdu', 'English', 'Islamiyat', 'Mathematics', 'Chemistry', 'Physics', 'Tarjumatul Quran']

    optional_book = student.assigned_subject or 'Computer Science'
    if optional_book and optional_book not in fixed_books:
        return fixed_books + [optional_book]
    return fixed_books
def get_available_subjects():
    from exams.management.commands.assign_daily_codes import ALL_SUBJECTS
    raw = set(ModelPaper.objects.values_list('subject', flat=True).distinct())
    raw.update(ALL_SUBJECTS)
    return unique_canonical_subjects(raw)

def get_subject_counts(student):
    _cls = (student.student_class or '').strip().lower()
    if _cls.startswith('9'):
        _allowed_classes = ['9', '9th', '9th class', '9a', '9b', '9c']
    else:
        _allowed_classes = [_cls]

    counts = {}
    for subj in get_available_subjects():
        counts[subj] = ModelQuestion.objects.filter(paper__student_class__in=_allowed_classes,
            paper__subject__iexact=subj, superseded_at__isnull=True, marks__gt=1,
        ).exclude(question_text__startswith='[]').exclude(question_text='').count()
    return counts

def _get_or_create_code(student, for_date=None):
    """Test Code: Which of the 'pace' questions to actually write in the exam."""
    target = for_date or timezone.now().date()
    existing = StudentDailyCode.objects.filter(student=student, date=target).first()
    if existing:
        return existing.code
    pace = student.daily_question_count or 1
    code = random.randint(1, pace)
    StudentDailyCode.objects.create(student=student, date=target, code=code)
    return code

def get_daily_mission_questions(student, pace_per_book=3, for_date=None, curriculum_day=None):
    """Day N → skip (N-1)*pace per book, pick next pace.
    Also writes StudentDayMission rows for days 1..N (idempotent).
    """
    from exams.models import EngineState
    from exams.models_day_mission import StudentDayMission

    books = get_student_books(student)
    target_date = for_date or timezone.now().date()
    code = _get_or_create_code(student, target_date)
    pace = student.daily_question_count or 1

    engine = EngineState.objects.filter(id=1).first()
    start_day = engine.start_day if engine else 1
    if curriculum_day is None:
        if engine and engine.has_started:
            curriculum_day = engine.get_current_day()
        else:
            curriculum_day = start_day

    skip_per_book = max(0, (curriculum_day - 1) * pace)
    end_per_book = skip_per_book + pace

    # ── CLASS SEPARATION LOGIC ──
    _cls = (student.student_class or '').strip().lower()
    if _cls.startswith('9'):
        _allowed_classes = ['9', '9th', '9th class', '9a', '9b', '9c']
    else:
        _allowed_classes = [_cls]

    mission_data = {}
    for book in books:
        # NEW: Protect student/teacher choices from auto-cron overwrite
        if curriculum_day:
            existing_sdm = StudentDayMission.objects.filter(
                student=student, day_number=curriculum_day, subject=book
            ).exclude(source='AUTO').first()
            if existing_sdm:
                _existing_qs = StudentDayMission.objects.filter(
                    student=student, day_number=curriculum_day, subject=book
                ).order_by('position').values_list('question_id', flat=True)
                mission_data[book] = list(_existing_qs)
                # INDUSTRY STANDARD FIX: Create locks for pre-existing (choice/custom/override) SDMs
                for qid in _existing_qs:
                    StudentQuestionLock.objects.update_or_create(
                        student=student, question_id=qid,
                        defaults={'is_active': True, 'locked_at': timezone.now()}
                    )
                continue

        qs = ModelQuestion.objects.filter(
            paper__subject__iexact=book,
            paper__student_class__in=_allowed_classes,
            superseded_at__isnull=True,
            marks__gt=1,
        ).exclude(
            question_text__startswith='[]'
        ).exclude(
            question_text=''
        ).order_by('paper_id', 'question_index')

        picked = []
        _used_qids = set(
            StudentDayMission.objects.filter(student=student)
            .values_list('question_id', flat=True)
        )

        # ── HUMAN IN THE LOOP: check pool health before picking ──
        _pool_status = check_and_alert_pool(student, book, pace)

        if _pool_status == 'LOOP_BACK':
            # Teacher approved loop-back — reset used set for this book
            _used_qids = set()  # allow reuse from start
            _cursor = 0
        elif _pool_status == 'BLOCKED':
            # Teacher hasn't decided — skip this book entirely
            import logging as _lg_block
            _lg_block.getLogger('idealogy.mission').warning(
                "MISSION_BLOCKED_PENDING_TEACHER student=%s book=%s (no pool decision)",
                student.code, book
            )
            mission_data[book] = []
            continue  # skip to next book
        else:
            _cursor = skip_per_book

        while len(picked) < pace and _cursor < len(qs):
            _q = qs[_cursor]
            if _q.id not in _used_qids:
                picked.append(_q)
                _used_qids.add(_q.id)
            _cursor += 1
        if not picked:
            import logging as _lg_ac
            _lg_ac.getLogger('idealogy.mission').warning(
                "MISSION_POOL_EXHAUSTED student=%s book=%s day=%s pace=%s pool_size=%s",
                student.code, book, curriculum_day, pace, len(qs)
            )

        mission_data[book] = [q.id for q in picked]

        for q in picked:
            StudentQuestionLock.objects.update_or_create(
                student=student, question=q,
                defaults={'is_active': True, 'locked_at': timezone.now()}
            )

        # Archive backfill for days 1..N — idempotent + pace-change cleanup
        try:
            all_qs = list(qs[:end_per_book])
            for day_idx in range(curriculum_day):
                day_num = day_idx + 1

                # NEW: Cleanup stale SDMs from pace changes
                # Compute expected question_ids for this day at CURRENT pace
                expected_qids = [
                    all_qs[q_idx].id
                    for q_idx in range(day_idx * pace, (day_idx + 1) * pace)
                    if q_idx < len(all_qs)
                ]
                if expected_qids:
                    # Delete stale standard-curriculum SDMs
                    # Preserve SELF-/CUSTOM- question SDMs (student-authored)
                    StudentDayMission.objects.filter(
                        student=student, day_number=day_num, subject=book
                    ).exclude(
                        question_id__in=expected_qids
                    ).exclude(
                        question__paper__code__startswith='SELF-'
                    ).exclude(
                        question__paper__code__startswith='CUSTOM-'
                    ).exclude(
                        source='MANUAL_OVERRIDE'  # GUARD: preserve teacher overrides
                    ).delete()

                # GUARD: skip positions already overridden by teacher
                _override_positions = set(
                    StudentDayMission.objects.filter(
                        student=student, day_number=day_num, subject=book,
                        source='MANUAL_OVERRIDE'
                    ).values_list('position', flat=True)
                )

                # Now create/ensure expected SDMs (idempotent)
                for q_idx in range(day_idx * pace, (day_idx + 1) * pace):
                    if q_idx < len(all_qs):
                        _pos = (q_idx - day_idx * pace) + 1
                        if _pos in _override_positions:
                            continue  # GUARD: don't overwrite manual override
                        
                        _q_obj = all_qs[q_idx]
                        
                        # INDUSTRY STANDARD FIX: Strictly prevent duplication across days
                        if StudentDayMission.objects.filter(student=student, question=_q_obj).exists():
                            continue
                            
                        StudentDayMission.objects.get_or_create(
                            student=student,
                            day_number=day_num,
                            question=_q_obj,
                            defaults={'subject': book, 'position': _pos}
                        )
        except Exception as e:
            import logging as _lg
            _lg.getLogger('idealogy.mission').error(
                f"MISSION_BACKFILL_FAILED student={student.code} book={book} day={day_num} error={e}"
            )

    return mission_data

def get_replacement_question(student, exclude_ids, subject=None):
    _cls = (student.student_class or '').strip().lower()
    if _cls.startswith('9'):
        _allowed_classes = ['9', '9th', '9th class', '9a', '9b', '9c']
    else:
        _allowed_classes = [_cls]

    _cls = (student.student_class or '').strip().lower()
    if _cls.startswith('9'):
        _allowed_classes = ['9', '9th', '9th class', '9a', '9b', '9c']
    else:
        _allowed_classes = [_cls]

    qs = ModelQuestion.objects.filter(
        paper__student_class__in=_allowed_classes,
        superseded_at__isnull=True, 
        marks__gt=1
    ).exclude(id__in=exclude_ids).exclude(question_text__startswith='[]').exclude(question_text='')
    
    if subject: 
        qs = qs.filter(paper__subject__iexact=subject)
    return qs.order_by('paper_id', 'question_index').first()

def get_source_display(question):
    sref = (question.source_ref or '').strip()
    subj = (question.paper.subject or 'General').strip()
    qnum = "Q" + str(question.question_index)
    if 'Board' in sref or 'Page' in sref: return sref
    parts = [subj]
    paper_title = (question.paper.title or '').strip()
    paper_code = (question.paper.code or '').strip()
    if paper_title and paper_title != paper_code: parts.append(paper_title)
    elif paper_code: parts.append(paper_code)
    if sref and len(sref) > 2: parts.append(sref)
    parts.append(qnum)
    return " · ".join(parts)


def check_and_alert_pool(student, book, pace):
    """
    Scan a book's pool for this student. Create PoolExhaustionAlert if low.

    Returns:
      'OK' — plenty of questions (no action)
      'WARNING' — running low (alert created, continue normally)
      'LOOP_BACK' — teacher chose to loop back, engine should reuse
      'BLOCKED' — teacher hasn't decided, halt assignment for this book
    """
    from exams.models import ModelQuestion
    from exams.models_day_mission import PoolExhaustionAlert, StudentDayMission
    from exams.utils_class import allowed_classes_for

    allowed = allowed_classes_for((student.student_class or '').strip())
    used_qids = set(
        StudentDayMission.objects.filter(student=student)
        .values_list('question_id', flat=True)
    )

    total_pool = ModelQuestion.objects.filter(
        paper__subject__iexact=book,
        paper__student_class__in=allowed,
        superseded_at__isnull=True,
        marks__gt=1,
    ).count()

    available = ModelQuestion.objects.filter(
        paper__subject__iexact=book,
        paper__student_class__in=allowed,
        superseded_at__isnull=True,
        marks__gt=1,
    ).exclude(id__in=used_qids).count()

    days_of_buffer = available // max(pace, 1) if pace else 0

    # Check existing alert/decision
    alert = PoolExhaustionAlert.objects.filter(
        book__iexact=book, student_class=(student.student_class or '').strip()
    ).first()

    # If exhausted
    if available < pace:
        if alert and alert.decision == 'LOOP_BACK':
            return 'LOOP_BACK'
        if alert and alert.decision in ('EXTENDED', 'SKIPPED'):
            return 'BLOCKED'

        # No decision → create/update alert, block
        if alert:
            alert.alert_type = 'EXHAUSTED'
            alert.remaining_questions = available
            alert.days_of_buffer = days_of_buffer
            alert.save()
        else:
            PoolExhaustionAlert.objects.create(
                book=book,
                student_class=(student.student_class or '').strip(),
                alert_type='EXHAUSTED',
                remaining_questions=available,
                pace_needed=pace,
                days_of_buffer=days_of_buffer,
            )
        return 'BLOCKED'

    # Running low (below 7 days of buffer)
    if days_of_buffer < 7:
        if not alert or alert.alert_type != 'WARNING':
            PoolExhaustionAlert.objects.update_or_create(
                book__iexact=book,
                student_class=(student.student_class or '').strip(),
                defaults={
                    'book': book,
                    'student_class': (student.student_class or '').strip(),
                    'alert_type': 'WARNING',
                    'remaining_questions': available,
                    'pace_needed': pace,
                    'days_of_buffer': days_of_buffer,
                }
            )
        elif alert:
            alert.remaining_questions = available
            alert.days_of_buffer = days_of_buffer
            alert.save()
        return 'WARNING'

    # Plenty
    return 'OK'

