"""Per-book pipeline service.

Each book (paper subject) has its own 7-stage pipeline. Student can
switch books freely but stages within a book are sequential.

Standards:
- Ordered Learning Paths (LearnUpon, Totara, Docebo, Moodle)
- UDL/CAST — learner choice of book order
- CBE — acceleration via bulk-skip with mastery cost
- Nielsen #1 (status visibility), #6 (recognition over recall)
- Sweller Cognitive Load (one book's pipeline at a time = bounded load)
"""
from exams.models import StudentQuestionLock
from exams.services.pipeline_state import (
    STAGES, SKIPPABLE, get_question_stage, get_mission_stage,
    get_stepper_data, get_bulk_skip_cost,
)
from exams.services.points_ledger import get_balance


def get_all_books(student):
    """Return sorted list of distinct book (subject) names for student.
    Industry standard: derive from enrollment + active locks, not just locks.
    This ensures optional subjects (e.g., Biology) are always available."""
    from exams.services.daily_mission_engine import get_student_books
    books = set(get_student_books(student))
    
    locks = StudentQuestionLock.objects.filter(
        student=student, is_active=True,
    ).select_related('question__paper')
    for lock in locks:
        paper = lock.question.paper
        if paper and paper.subject:
            books.add(paper.subject)
            
    return sorted(list(books))


def get_book_questions(student, book):
    """Return list of ModelQuestion objects locked for student in this book."""
    locks = StudentQuestionLock.objects.filter(
        student=student, is_active=True,
        question__paper__subject=book,
    ).select_related('question__paper', 'question__kc')
    return [lock.question for lock in locks]


def get_book_state(student, book):
    """Return dict describing one book's pipeline state.
    
    Source priority:
      1. StudentQuestionLock (with get_mission_stage) — legacy + active flows
      2. StudentDayMission for today — fallback when locks are empty.
         SDM-sourced books are forced to STUDY (they are today's assigned material,
         not "awaiting assignment"; get_mission_stage misclassifies them as SELECT).
    """
    questions = get_book_questions(student, book)
    source = 'locks'

    if not questions:
        from exams.models_day_mission import StudentDayMission
        from exams.models import EngineState
        _eng = EngineState.objects.filter(id=1).first()
        _cur_day = _eng.get_current_day() if (_eng and _eng.has_started) else None
        if _cur_day:
            _sdm_qs = StudentDayMission.objects.filter(
                student=student, day_number=_cur_day, subject=book
            ).select_related('question', 'question__paper', 'question__kc')
            questions = [sdm.question for sdm in _sdm_qs]
            source = 'sdm'

    if not questions:
        return {
            'book': book, 'status': 'empty', 'current_stage': 'SELECT',
            'counts': {}, 'total': 0,
        }

    if source == 'sdm':
        return {
            'book': book,
            'status': 'active',
            'current_stage': 'STUDY',
            'counts': {'STUDY': len(questions)},
            'total': len(questions),
        }

    state = get_mission_stage(student, questions)
    is_complete = (
        state['aggregate_stage'] == 'SAFAR'
        and state['counts'].get('SAFAR', 0) == state['total']
    )
    return {
        'book': book,
        'status': 'complete' if is_complete else 'active',
        'current_stage': state['aggregate_stage'],
        'counts': state['counts'],
        'total': state['total'],
    }

def get_all_book_states(student):
    """Return list of all book states."""
    return [get_book_state(student, b) for b in get_all_books(student)]


def get_bulk_skip_availability(student, book):
    """Return list of {stage, count, cost, can_afford, balance}
    for skippable stages with pending questions in this book."""
    balance = get_balance(student)
    questions = get_book_questions(student, book)
    stage_counts = {}
    for q in questions:
        st = get_question_stage(student, q)['current_stage']
        if st in SKIPPABLE:
            stage_counts[st] = stage_counts.get(st, 0) + 1
    avail = []
    for stage in ('STUDY', 'REMEDIATION', 'VERIFY', 'ESCALATED'):
        count = stage_counts.get(stage, 0)
        if count > 0:
            cost = get_bulk_skip_cost(stage)
            avail.append({
                'stage': stage,
                'stage_label': stage.title(),
                'count': count,
                'cost': cost,
                'can_afford': balance >= cost,
                'balance': balance,
            })
    return avail
