"""Stage skip (1 pt/question, 3-5 pts bulk) and ungate (teacher-granted) controls."""
from django.db import transaction
from django.db.models import Q
from django.utils import timezone
from exams.models import (
    StageSkip, StageUngate, StageUngateRequest,
)
from exams.services import points_ledger
from exams.services.pipeline_state import (
    SKIPPABLE, get_skip_cost, get_bulk_skip_cost,
)


def skip_stage(student, question, stage):
    """Skip ONE question at a stage. Cost: 1 pt."""
    stage_upper = (stage or '').upper()
    if stage_upper not in SKIPPABLE:
        raise ValueError(f'{stage} is not skippable')
    # Policy: Computer Science and English cannot be skipped
    from exams.services.pipeline_state import NON_SKIPPABLE_SUBJECTS
    subject = question.paper.subject if question.paper else ''
    if subject in NON_SKIPPABLE_SUBJECTS:
        raise ValueError(f'{subject} questions cannot be skipped.')
    # Block if individual OR bulk skip already exists
    if StageSkip.objects.filter(
        student=student, stage=stage_upper,
    ).filter(Q(question=question) | Q(question__isnull=True)).exists():
        raise ValueError('Already skipped')
    cost = get_skip_cost(stage_upper)
    if not points_ledger.can_afford(student, cost):
        raise ValueError(f'Need {cost} pts, you have {points_ledger.get_balance(student)}')
    with transaction.atomic():
        points_ledger.spend(
            student, cost,
            reason=f'Skip {stage_upper} (Q{question.id})',
            code='SKIP_STAGE',
            evidence={'question_id': question.id, 'stage': stage_upper},
        )
        return StageSkip.objects.create(
            student=student, question=question, stage=stage_upper,
            cost_points=cost, is_bulk=False,
        )


def skip_stage_bulk(student, stage):
    """Skip entire stage for ALL student questions. Cost: 3-5 pts depending on stage."""
    stage_upper = (stage or '').upper()
    if stage_upper not in SKIPPABLE:
        raise ValueError(f'{stage} is not skippable')
    # Policy: block bulk skip if student has CS/English questions at this stage
    from exams.services.pipeline_state import NON_SKIPPABLE_SUBJECTS, get_question_stage
    from exams.models import StudentQuestionLock
    locks = StudentQuestionLock.objects.filter(student=student, is_active=True).select_related('question', 'question__paper')
    for lock in locks:
        q = lock.question
        subj = q.paper.subject if q.paper else ''
        if subj in NON_SKIPPABLE_SUBJECTS and get_question_stage(student, q)['current_stage'] == stage_upper:
            raise ValueError(f'Cannot bulk-skip: {subj} questions must be completed individually.')
    if StageSkip.objects.filter(
        student=student, question__isnull=True, stage=stage_upper, is_bulk=True,
    ).exists():
        raise ValueError('Stage already bulk-skipped')
    cost = get_bulk_skip_cost(stage_upper)
    if not points_ledger.can_afford(student, cost):
        raise ValueError(f'Need {cost} pts, you have {points_ledger.get_balance(student)}')
    with transaction.atomic():
        points_ledger.spend(
            student, cost,
            reason=f'Bulk skip {stage_upper}',
            code='SKIP_BULK_STAGE',
            evidence={'stage': stage_upper},
        )
        return StageSkip.objects.create(
            student=student, question=None, stage=stage_upper,
            cost_points=cost, is_bulk=True,
        )


def is_skipped(student, question, stage):
    """True if question OR whole stage was skipped."""
    return StageSkip.objects.filter(
        student=student, stage=(stage or '').upper(),
    ).filter(Q(question=question) | Q(question__isnull=True)).exists()


def is_bulk_skipped(student, stage):
    return StageSkip.objects.filter(
        student=student, question__isnull=True,
        stage=(stage or '').upper(), is_bulk=True,
    ).exists()


# --- Ungate (teacher-granted, no reason required) ---

def request_ungate(student, stage, question=None, note=''):
    return StageUngateRequest.objects.create(
        student=student, stage=stage, question=question, student_note=note,
    )


def approve_ungate(request_obj, teacher):
    with transaction.atomic():
        request_obj.status = 'APPROVED'
        request_obj.resolved_by = teacher
        request_obj.resolved_at = timezone.now()
        request_obj.save()
        return StageUngate.objects.create(
            student=request_obj.student, question=request_obj.question,
            stage=request_obj.stage, ungated_by=teacher,
        )


def reject_ungate(request_obj, teacher):
    request_obj.status = 'REJECTED'
    request_obj.resolved_by = teacher
    request_obj.resolved_at = timezone.now()
    request_obj.save()
    return request_obj


def direct_ungate(student, stage, teacher, question=None):
    return StageUngate.objects.create(
        student=student, question=question, stage=stage, ungated_by=teacher,
    )


def revoke_ungate(ungate_obj):
    ungate_obj.revoked_at = timezone.now()
    ungate_obj.save(update_fields=['revoked_at'])


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


# ═══════════════════════════════════════════════════════════════
# Per-Book Bulk Skip (2026-10-28)
# Skips entire stage for ONE book only. Flat bulk cost charged once.
# Creates individual StageSkip rows so _is_skipped() finds them.
# ═══════════════════════════════════════════════════════════════

def skip_stage_bulk_for_book(student, book, stage):
    """Bulk-skip an entire stage for one book.

    Cost: BULK_SKIP_COSTS[stage] charged ONCE (per book).
    Creates individual StageSkip rows (is_bulk=True, cost_points=0) for
    each pending question in the book. This is compatible with existing
    _is_skipped() logic in pipeline_state.py (checks Q(question) OR Q(null)).

    Raises ValueError if:
    - stage not skippable
    - no pending questions at this stage in the book
    - insufficient contribution balance
    """
    from exams.models import StudentQuestionLock
    from exams.services.pipeline_state import get_question_stage

    stage_upper = (stage or '').upper()
    if stage_upper not in SKIPPABLE:
        raise ValueError(f'{stage} is not skippable')

    locks = StudentQuestionLock.objects.filter(
        student=student, is_active=True,
        question__paper__subject=book,
    ).select_related('question')
    pending = []
    for lock in locks:
        st = get_question_stage(student, lock.question)['current_stage']
        if st == stage_upper:
            pending.append(lock.question)

    if not pending:
        raise ValueError(f'No questions at {stage_upper} in {book}')

    already = StageSkip.objects.filter(
        student=student, question__in=pending, stage=stage_upper,
    ).count()
    if already >= len(pending):
        raise ValueError('Stage already bulk-skipped for this book')

    cost = get_bulk_skip_cost(stage_upper)
    if not points_ledger.can_afford(student, cost):
        raise ValueError(
            f'Need {cost} contribution, you have {points_ledger.get_balance(student)}'
        )

    with transaction.atomic():
        points_ledger.spend(
            student, cost,
            reason=f'Bulk skip {stage_upper} for {book}',
            code='SKIP_BULK_BOOK_STAGE',
            evidence={'stage': stage_upper, 'book': book},
        )
        created = []
        for q in pending:
            if not StageSkip.objects.filter(
                student=student, question=q, stage=stage_upper,
            ).exists():
                created.append(StageSkip.objects.create(
                    student=student, question=q, stage=stage_upper,
                    cost_points=0, is_bulk=True,
                ))
        return created
