from urllib.parse import quote
"""Pipeline state — 7-stage machine. Database-only, no session dependency.

Stages: SELECT → STUDY → ATTEMPT → REMEDIATION / VERIFY → ESCALATED → SAFAR

ATTEMPT combines "submit paper" and "get graded" into one atomic action
(industry standard: one assessment = one pipeline stage).

Skip costs:
- Per-question skip: 1 point (flat across all skippable stages)
- Bulk stage skip: 3 pts (STUDY), 5 pts (REMEDIATION/VERIFY/ESCALATED)
"""
from django.db.models import Q
from exams.models import (
    StudentQuestionLock, StudentNote, AttemptLog, RPSItem,
    RetakeTicket, StageSkip, StageUngate,
)

STAGES = ['SELECT', 'STUDY', 'ATTEMPT', 'REMEDIATION',
          'VERIFY', 'ESCALATED', 'SAFAR']
SKIPPABLE = {'STUDY', 'REMEDIATION', 'VERIFY', 'ESCALATED'}

SKIP_COST_PER_QUESTION = 1
BULK_SKIP_COSTS = {
    'STUDY': 3,
    'REMEDIATION': 5,
    'VERIFY': 5,
    'ESCALATED': 5,
}
BULK_SKIP_COST = 3

# Policy: certain subjects require full completion — no skips allowed
NON_SKIPPABLE_SUBJECTS = {'Computer Science', 'English'}

STAGE_TITLES = {
    'SELECT': 'Select', 'STUDY': 'Study', 'ATTEMPT': 'Attempt',
    'REMEDIATION': 'Remediation', 'VERIFY': 'Boss Fight',
    'ESCALATED': 'Escalated', 'SAFAR': 'Safar',
}
SHORT_TITLES = {
    'SELECT': 'Select', 'STUDY': 'Study', 'ATTEMPT': 'Attempt',
    'REMEDIATION': 'Remed', 'VERIFY': 'Verify',
    'ESCALATED': 'Escal', 'SAFAR': 'Safar',
}


def get_skip_cost(stage):
    """Per-question skip cost — always 1 point."""
    return SKIP_COST_PER_QUESTION


def get_bulk_skip_cost(stage):
    """Bulk skip cost for entire stage."""
    return BULK_SKIP_COSTS.get((stage or '').upper(), BULK_SKIP_COST)


def _is_ungated(student, question, stage):
    return StageUngate.objects.filter(
        student=student, stage=stage, revoked_at__isnull=True,
    ).filter(Q(question=question) | Q(question__isnull=True)).exists()


def _is_skipped(student, question, stage):
    """True if this question OR the entire stage was bulk-skipped."""
    return StageSkip.objects.filter(
        student=student, stage=(stage or '').upper(),
    ).filter(
        Q(question=question) | Q(question__isnull=True)
    ).exists()



def award_safar_points(student, question):
    """Idempotently award +5 points when a question reaches SAFAR.

    Safety guarantee: points_ledger.award() uses SHA-256 idempotency key.
    Historical rows migrated in R4-pre (344 signed, hash-verified).
    Safe to call from any code path (skip, mastery pass, attempt pass, ungate).
    """
    from exams.services import points_ledger
    r = points_ledger.award(
        student=student,
        points=5,
        reason=f"Completed Q{question.question_index} ({question.paper.subject if question.paper else 'GEN'})",
        code='QUESTION_MASTERED',
        evidence={'qid': question.id},
        source='AUTO',
    )
    return r is not None


def get_question_stage(student, question):
    """Returns current_stage = the NEXT action the student should do."""
    has_lock = StudentQuestionLock.objects.filter(
        student=student, question=question, is_active=True,
    ).exists()
    if not has_lock:
        return {'current_stage': 'SELECT',
                'locked_reason': 'Select this question first.',
                'skippable': False, 'latest_attempt': None}

    subject = question.paper.subject if question.paper else ''
    # ── FRESH RESET CHECK ──
    # If engine not started (post-reset), ignore old notes entirely.
    # This forces every new student to STUDY first even if they had notes before.
    from exams.models import EngineState as _EngineState
    _eng = _EngineState.objects.filter(id=1).first()
    _force_fresh = (_eng is None) or (not _eng.has_started)

    if _force_fresh:
        has_note = False
    else:
        # Match by question TEXT — prevents false positives from old notes
        _q_text = (question.question_text or '').strip()
        if _q_text:
            has_note = StudentNote.objects.filter(
                student=student, subject=subject,
                q_number=str(question.question_index),
            ).filter(
                Q(question__iexact=_q_text) | Q(question__startswith=_q_text[:80])
            ).exists()
        else:
            has_note = False
    study_done = (has_note
                  or _is_skipped(student, question, 'STUDY')
                  or _is_ungated(student, question, 'STUDY'))

    latest = AttemptLog.objects.filter(
        student=student, question=question, cancelled_at__isnull=True,
    ).order_by('-created_at').first()

    subject_blocks_skip = subject in NON_SKIPPABLE_SUBJECTS

    if not study_done:
        return {'current_stage': 'STUDY', 'locked_reason': None,
                'skippable': not subject_blocks_skip, 'latest_attempt': None}

    # ATTEMPT is MANDATORY. Only a physical paper upload (is_physical=True)
    # with result_json advances the pipeline. No skip, no ungate, no legacy bypass.
    if not latest or not latest.result_json or not getattr(latest, 'is_physical', False):
        return {'current_stage': 'ATTEMPT',
                'locked_reason': 'Upload your physical paper via the paste flow to advance.',
                'skippable': False, 'latest_attempt': latest}

    kc_code = question.kc_code or (question.kc.code if question.kc else None)

    if latest.passed:
        graduated = False
        if kc_code:
            rps = RPSItem.objects.filter(student=student, kc_code=kc_code).first()
            graduated = rps and rps.mastery_state == 'GRADUATED'
        verify_done = (graduated
                       or _is_skipped(student, question, 'VERIFY')
                       or _is_ungated(student, question, 'VERIFY'))
        if verify_done:
            return {'current_stage': 'SAFAR', 'locked_reason': None,
                    'skippable': False, 'latest_attempt': latest}
        return {'current_stage': 'VERIFY',
                'locked_reason': 'Attempt the Boss Fight to complete.',
                'skippable': not subject_blocks_skip, 'latest_attempt': latest}

    rem_done = (_is_skipped(student, question, 'REMEDIATION')
                or _is_ungated(student, question, 'REMEDIATION'))
    if rem_done:
        # Skipping REMEDIATION means: don't re-study, retry now.
        # Must NOT reach SAFAR without passing VERIFY.
        return {'current_stage': 'ATTEMPT',
                'locked_reason': 'Remediation skipped. Attempt again to improve.',
                'skippable': False, 'latest_attempt': latest}

    ticket = RetakeTicket.objects.filter(
        student=student, question=question,
    ).order_by('-attempt_number').first()

    if ticket and ticket.status == 'ESCALATED':
        esc_done = _is_skipped(student, question, 'ESCALATED')
        if esc_done:
            return {'current_stage': 'SAFAR', 'locked_reason': None,
                    'skippable': False, 'latest_attempt': latest}
        return {'current_stage': 'ESCALATED',
                'locked_reason': 'Escalated — talk to teacher or skip.',
                'skippable': not subject_blocks_skip, 'latest_attempt': latest}

    return {'current_stage': 'REMEDIATION',
            'locked_reason': 'Re-study and re-attempt to score 80%+.',
            'skippable': True, 'latest_attempt': latest}


def get_mission_stage(student, question_objs):
    if not question_objs:
        return {'aggregate_stage': 'SELECT', 'counts': {}, 'total': 0}

    stage_counts = {}
    for q in question_objs:
        s = get_question_stage(student, q)['current_stage']
        stage_counts[s] = stage_counts.get(s, 0) + 1

    aggregate = 'SELECT'
    for s in STAGES:
        if stage_counts.get(s, 0) > 0:
            aggregate = s
            break

    return {'aggregate_stage': aggregate, 'counts': stage_counts,
            'total': len(question_objs)}


def get_stepper_data(mission_state, current_book=None, requested_stage=None):
    counts = mission_state['counts']
    aggregate = mission_state['aggregate_stage']
    agg_idx = STAGES.index(aggregate) if aggregate in STAGES else 0

    # The stage the user is currently viewing (from URL param)
    view_idx = agg_idx
    if requested_stage and requested_stage in STAGES:
        view_idx = STAGES.index(requested_stage)

    stepper = []
    for i, stage in enumerate(STAGES):
        title = STAGE_TITLES.get(stage, stage.title())
        # Show the currently-viewed stage as ACTIVE (blue circle)
        if i == view_idx:
            status, icon = 'active', str(i + 1)
        # Show all previously-passed stages as COMPLETED (green tick)
        elif i < agg_idx:
            status, icon = 'completed', '✓'
        else:
            status, icon = 'pending', str(i + 1)
        stepper.append({
            'stage': stage, 'title': title, 'status': status, 'icon': icon,
            'short_title': SHORT_TITLES.get(stage, title),
            'link': f'?stage={stage}' + (f'&book={quote(current_book)}' if current_book else ''),
            'skippable': stage in SKIPPABLE,
        })
    return stepper
