"""Fraud cancellation service — atomic apply + reverse.

Standards:
- ISO 15489-1:2016 s9.6 — void records are amendments, never deletions
- NIST SP 800-53 AU-9 (audit trail integrity), SI-10 (input validation), SI-12 (info handling)
- Django transaction.atomic() — all-or-nothing
- CBSE/IB academic integrity — partial fraud does not void whole-day legit work

Public API:
    resolve_scope(student, scope, ...)    -> dict (read-only)
    preview(student, scope, ...)          -> dict (read-only, no writes)
    apply_cancel(teacher, student, ...)   -> FraudCancellation (writes, atomic)
    apply_reversal(fraud, superuser)      -> dict summary (writes, atomic)
"""
from datetime import timedelta

from django.db import transaction
from django.db.models import F
from django.utils import timezone

from exams.models import AttemptLog, ExamToken, StudentNotification
from exams.models_trophy import TrophyEvent

__all__ = [
    'VALID_SCOPES', 'resolve_scope', 'preview', 'apply_cancel', 'apply_reversal',
]

VALID_SCOPES = ('SINGLE', 'DAY', 'DAY_RANGE', 'DATE_RANGE', 'MONTH')
_MONTH_DAYS = 20


def _day_date_range(day_from, day_to):
    """Map curriculum day numbers to calendar dates via EngineState.start_date.

    Canonical mapping (matches mizan_algorithm._detailed_question_stats):
        Day N calendar date = engine.start_date + (N-1) days
    """
    from exams.models import EngineState
    engine = EngineState.objects.filter(id=1).first()
    if not engine or not engine.has_started or not engine.start_date:
        return None, None
    start = engine.start_date + timedelta(days=day_from - 1)
    end = engine.start_date + timedelta(days=day_to - 1)
    return start, end


def resolve_scope(student, scope, day=None, day_from=None, day_to=None,
                  date_from=None, date_to=None, month=None,
                  subject_filter='', attempt_ids=None):
    """Translate scope parameters to a queryset + day/date metadata."""
    if scope not in VALID_SCOPES:
        raise ValueError("Invalid scope: %r. Must be one of %s" % (scope, VALID_SCOPES))

    base = AttemptLog.objects.filter(student=student, cancelled_at__isnull=True)
    day_set = set()
    date_range = None
    df, dt = None, None

    if scope == 'SINGLE':
        if not attempt_ids:
            raise ValueError("SINGLE scope requires attempt_ids")
        qs = base.filter(id__in=attempt_ids)
        day_set = set(x for x in qs.values_list('target_day_number', flat=True) if x)

    elif scope == 'DAY':
        if day is None:
            raise ValueError("DAY scope requires day")
        qs = base.filter(target_day_number=day)
        day_set = {day}
        df, dt = day, day

    elif scope == 'DAY_RANGE':
        if day_from is None or day_to is None:
            raise ValueError("DAY_RANGE requires day_from and day_to")
        if day_from > day_to:
            raise ValueError("day_from must be <= day_to")
        qs = base.filter(target_day_number__range=(day_from, day_to))
        day_set = set(range(day_from, day_to + 1))
        df, dt = day_from, day_to

    elif scope == 'DATE_RANGE':
        if not (date_from and date_to):
            raise ValueError("DATE_RANGE requires date_from and date_to")
        if date_from > date_to:
            raise ValueError("date_from must be <= date_to")
        qs = base.filter(created_at__date__gte=date_from, created_at__date__lte=date_to)
        date_range = (date_from, date_to)

    elif scope == 'MONTH':
        if month is None or not (1 <= int(month) <= 6):
            raise ValueError("MONTH must be an integer 1..6")
        df = (int(month) - 1) * _MONTH_DAYS + 1
        dt = int(month) * _MONTH_DAYS
        qs = base.filter(target_day_number__range=(df, dt))
        day_set = set(range(df, dt + 1))

    if subject_filter:
        qs = qs.filter(question__paper__subject=subject_filter)

    id_list = list(qs.values_list('id', flat=True))

    return {
        'scope': scope,
        'attempt_qs': qs,
        'attempt_ids': id_list,
        'attempt_count': len(id_list),
        'day_set': day_set,
        'date_range': date_range,
        'day_from': df,
        'day_to': dt,
        'subject_filter': subject_filter or '',
    }


def _compute_trophy_cancellations(student, resolved):
    """Return list of TrophyEvent ids that should be voided.

    Conservative matching (CBSE/IB partial-fraud rule):
    - Q_COMPLETE:{sid}:{qid}   -> void iff no *active* AttemptLog remains for that qid
    - CHOICE_COMPLETE:{sid}:{day}:{subj} -> void iff all AttemptLog for (day,subj) cancelled
    - DAY_COMPLETE:{sid}:{date} -> void iff subject_filter empty AND every active
                                  AttemptLog for that day is cancelled
    """
    student_id = student.id
    cancelled_ids = set(resolved['attempt_ids'])
    if not cancelled_ids:
        return []

    candidate_ids = []

    # --- Q_COMPLETE ---
    # New day-scoped awards are cancelled only when no active attempt for
    # the same question remains on that mission day. Legacy keys retain
    # their historical all-days check.
    cancelled_attempts = AttemptLog.objects.filter(
        id__in=cancelled_ids
    ).values_list(
        'question_id', 'target_day_number', 'question__paper__subject'
    )

    cancelled_pairs = set(cancelled_attempts)

    for qid, day, subj in cancelled_pairs:
        if day is not None and subj:
            active_same_day = AttemptLog.objects.filter(
                student=student,
                question_id=qid,
                target_day_number=day,
                cancelled_at__isnull=True,
            ).exclude(id__in=cancelled_ids).exists()

            if not active_same_day:
                day_key = 'Q_COMPLETE:%d:%d:%d' % (student_id, day, qid)
                candidate_ids.extend(
                    TrophyEvent.objects.filter(
                        student=student,
                        subject=subj,
                        event_key=day_key,
                        cancelled_at__isnull=True,
                    ).values_list('id', flat=True)
                )

        # Legacy key has no mission-day component. Preserve its original
        # behaviour: cancel only when no active attempt remains on any day.
        active_any_day = AttemptLog.objects.filter(
            student=student,
            question_id=qid,
            cancelled_at__isnull=True,
        ).exclude(id__in=cancelled_ids).exists()

        if not active_any_day:
            legacy_key = 'Q_COMPLETE:%d:%d' % (student_id, qid)
            candidate_ids.extend(
                TrophyEvent.objects.filter(
                    student=student,
                    event_key=legacy_key,
                    cancelled_at__isnull=True,
                ).values_list('id', flat=True)
            )

    # --- CHOICE_COMPLETE ---
    pairs = set(
        AttemptLog.objects.filter(id__in=cancelled_ids)
        .values_list('target_day_number', 'question__paper__subject')
    )
    for day, subj in pairs:
        if day is None or not subj:
            continue
        active_remaining = AttemptLog.objects.filter(
            student=student, target_day_number=day,
            question__paper__subject=subj, cancelled_at__isnull=True,
        ).exclude(id__in=cancelled_ids).exists()
        if not active_remaining:
            candidate_ids.extend(
                TrophyEvent.objects.filter(
                    student=student,
                    event_key='CHOICE_COMPLETE:%d:%d:%s' % (student_id, day, subj),
                    cancelled_at__isnull=True,
                ).values_list('id', flat=True)
            )

    # --- DAY_COMPLETE (only on whole-day cancel) ---
    if not resolved['subject_filter'] and resolved['day_set']:
        for day in resolved['day_set']:
            active_remaining = AttemptLog.objects.filter(
                student=student, target_day_number=day, cancelled_at__isnull=True,
            ).exclude(id__in=cancelled_ids).exists()
            if active_remaining:
                continue  # legitimate work remains -> keep DAY_COMPLETE
            day_start, _ = _day_date_range(day, day)
            if day_start is None:
                continue
            candidate_ids.extend(
                TrophyEvent.objects.filter(
                    student=student,
                    event_key='DAY_COMPLETE:%d:%s' % (student_id, day_start.isoformat()),
                    cancelled_at__isnull=True,
                ).values_list('id', flat=True)
            )

    # De-duplicate
    return sorted(set(candidate_ids))


def _compute_token_ids(student, attempt_ids):
    """Return ExamToken ids attached to the attempts being cancelled."""
    if not attempt_ids:
        return []
    return list(
        ExamToken.objects.filter(student=student, attempt_id__in=attempt_ids)
        .values_list('id', flat=True)
    )


def preview(student, scope, **kwargs):
    """Read-only. Returns a dict of what *would* be cancelled."""
    refund_token = bool(kwargs.pop('refund_token', False))
    resolved = resolve_scope(student, scope, **kwargs)
    trophy_ids = _compute_trophy_cancellations(student, resolved)
    token_ids = _compute_token_ids(student, resolved['attempt_ids']) if refund_token else []
    return {
        'attempt_count': resolved['attempt_count'],
        'attempt_ids': resolved['attempt_ids'],
        'trophy_count': len(trophy_ids),
        'trophy_ids': trophy_ids,
        'token_count': len(token_ids),
        'token_ids': token_ids,
        'day_set': sorted(resolved['day_set']),
        'day_from': resolved['day_from'],
        'day_to': resolved['day_to'],
        'date_range': resolved['date_range'],
        'subject_filter': resolved['subject_filter'],
        'scope': scope,
    }


def _write_notification(student, day_range_label, reason):
    """Create a StudentNotification on the student's mission page."""
    expires = timezone.now() + timedelta(days=30)
    StudentNotification.objects.create(
        student=student,
        title='Paper Cancelled — Manual Review',
        message=(
            'Aap ka %s paper manually review ke baad cancel kar diya gaya. '
            'Wajah: %s. Behas ke liye apne teacher se rabta karein.'
            % (day_range_label, reason or '(no reason provided)')
        ),
        shift='general',
        expires_at=expires,
    )


def _day_range_label(resolved):
    if resolved['scope'] == 'SINGLE':
        return 'ek paper'
    if resolved['scope'] == 'DAY':
        return 'Day %d' % resolved['day_from'] if resolved['day_from'] else 'ek din'
    if resolved['scope'] == 'DAY_RANGE':
        return 'Day %d-%d' % (resolved['day_from'], resolved['day_to'])
    if resolved['scope'] == 'MONTH':
        return 'Month %d' % ((resolved['day_from'] - 1) // _MONTH_DAYS + 1)
    if resolved['date_range']:
        return '%s — %s' % (resolved['date_range'][0].isoformat(),
                            resolved['date_range'][1].isoformat())
    return 'kuch papers'


@transaction.atomic
def apply_cancel(teacher, student, scope, reason, evidence_url='',
                 refund_token=False, **kwargs):
    """Cancel attempts/trophies atomically and write the audit record."""
    from exams.models import FraudCancellation

    if not reason or not reason.strip():
        raise ValueError('reason is required')

    resolved = resolve_scope(student, scope, **kwargs)
    attempt_ids = resolved['attempt_ids']
    if not attempt_ids:
        raise ValueError('No active attempts matched the selected scope')

    trophy_ids = _compute_trophy_cancellations(student, resolved)
    token_ids = _compute_token_ids(student, attempt_ids) if refund_token else []

    now = timezone.now()

    fraud = FraudCancellation.objects.create(
        student=student,
        cancelled_by=teacher,
        scope=scope,
        day_from=resolved['day_from'],
        day_to=resolved['day_to'],
        subject_filter=resolved['subject_filter'],
        reason=reason.strip(),
        evidence_url=(evidence_url or '').strip(),
        affected_attempt_ids=attempt_ids,
        trophy_events_cancelled=trophy_ids,
        token_uses_refunded=len(token_ids),
        token_ids_refunded=token_ids,
    )

    AttemptLog.objects.filter(id__in=attempt_ids).update(
        cancelled_at=now,
        cancelled_by=teacher,
        cancel_reason=reason.strip(),
        cancel_evidence_url=(evidence_url or '').strip(),
    )

    if trophy_ids:
        TrophyEvent.objects.filter(id__in=trophy_ids).update(
            cancelled_at=now,
            cancelled_by=teacher,
        )

    if token_ids:
        ExamToken.objects.filter(id__in=token_ids).update(
            uses_remaining=F('uses_remaining') + 1,
        )

    _write_notification(student, _day_range_label(resolved), reason)

    from exams.mizan_algorithm import recompute
    recompute(student, write=True)

    return fraud


@transaction.atomic
def apply_reversal(fraud, superuser):
    """Reverse a fraud cancellation. Superuser-only, called from view layer."""
    from exams.models import FraudCancellation

    if fraud.is_reversed:
        raise ValueError('This cancellation is already reversed')
    if not getattr(superuser, 'is_superuser', False):
        raise PermissionError('Only superuser can reverse a fraud cancellation')

    attempt_ids = fraud.affected_attempt_ids or []
    trophy_ids = fraud.trophy_events_cancelled or []
    token_ids = fraud.token_ids_refunded or []

    # Un-cancel attempts
    AttemptLog.objects.filter(id__in=attempt_ids).update(
        cancelled_at=None,
        cancelled_by=None,
        cancel_reason='',
        cancel_evidence_url='',
    )

    # Un-cancel trophies — defensive collision check, bypass append-only save()
    if trophy_ids:
        reactivated = 0
        for te in TrophyEvent.objects.filter(id__in=trophy_ids):
            collides = TrophyEvent.objects.filter(
                event_key=te.event_key, cancelled_at__isnull=True,
            ).exclude(id=te.id).exists()
            if collides:
                continue
            TrophyEvent.objects.filter(id=te.id).update(cancelled_at=None, cancelled_by=None)
            reactivated += 1
    else:
        reactivated = 0

    # Un-refund tokens
    if token_ids:
        ExamToken.objects.filter(id__in=token_ids, uses_remaining__gt=0).update(
            uses_remaining=F('uses_remaining') - 1,
        )

    fraud.is_reversed = True
    fraud.reversed_at = timezone.now()
    fraud.reversed_by = superuser
    fraud.save(update_fields=['is_reversed', 'reversed_at', 'reversed_by'])

    from exams.mizan_algorithm import recompute
    recompute(fraud.student, write=True)

    return {
        'attempts_restored': len(attempt_ids),
        'trophies_restored': reactivated,
        'tokens_unrefunded': len(token_ids),
    }
