"""
Physical test appointment queue service — FIFO token system.

Standards: hospital bari queue (FIFO), bank ticketing, DMV appointment.
All state transitions logged with actor + timestamp (SOX 404, ISO 27001 A.8.15).
All issuance wrapped in select_for_update to prevent race conditions (NIST SI-10).
"""
import logging
from django.db import transaction
from django.db.models import Max
from django.utils import timezone
from exams.models import ExamToken, Student, AttemptLog

logger = logging.getLogger(__name__)

ACTIVE_STATUSES = ('PENDING', 'CALLED', 'IN_PROGRESS')


def issue_token(student, uses=1):
    """Issue a new PENDING token for today. Returns (token, created).

    - If student already has an active token today, returns (existing, False).
    - Token number = max(existing today) + 1, never reused.
    - Wrapped in select_for_update for concurrent-safety.
    """
    today = timezone.localdate()
    with transaction.atomic():
        existing = ExamToken.objects.select_for_update().filter(
            student=student, status__in=ACTIVE_STATUSES,
        ).first()
        if existing:
            logger.info("QUEUE_DUPLICATE student=%s existing_token=%s",
                        student.code, existing.token_number)
            return existing, False

        max_num = ExamToken.objects.filter(date=today).aggregate(
            m=Max('token_number'))['m'] or 0
        token = ExamToken.objects.create(
            student=student, date=today, token_number=max_num + 1,
            status='PENDING', uses_remaining=uses,
        )
        logger.info("QUEUE_ISSUED student=%s token=%s date=%s",
                    student.code, token.token_number, today)
        return token, True


def cancel_token(student):
    """Student cancels their own PENDING token. Only allowed from PENDING."""
    with transaction.atomic():
        token = ExamToken.objects.select_for_update().filter(
            student=student, status='PENDING',
        ).first()
        if not token:
            logger.info("QUEUE_CANCEL_NOOP student=%s (no pending)", student.code)
            return None
        token.status = 'CANCELLED'
        token.save(update_fields=['status'])
        logger.info("QUEUE_CANCELLED student=%s token=%s", student.code, token.token_number)
        return token


def get_queue_for_student(student):
    """Return the student's active token (today only) and total waiting ahead."""
    today = timezone.localdate()
    token = ExamToken.objects.filter(
        student=student, 
        status__in=ACTIVE_STATUSES,
        date=today,  # Safety net: ignore previous-day tokens
    ).first()
    if not token:
        return None, 0
    ahead = ExamToken.objects.filter(
        date=token.date, status='PENDING', token_number__lt=token.token_number,
    ).count()
    return token, ahead


def call_next(count=1, user=None):
    """Teacher calls the next `count` PENDING tokens -> CALLED.

    Returns list of called ExamToken objects.
    """
    today = timezone.localdate()
    called = []
    with transaction.atomic():
        pending = list(ExamToken.objects.select_for_update().filter(
            date=today, status='PENDING',
        ).order_by('token_number')[:count])

        for token in pending:
            token.status = 'CALLED'
            token.called_at = timezone.now()
            token.called_by = user
            token.save(update_fields=['status', 'called_at', 'called_by'])
            called.append(token)

        if called:
            logger.info("QUEUE_CALLED count=%d by=%s tokens=%s",
                        len(called), getattr(user, 'username', '?'),
                        [t.token_number for t in called])
    return called


def mark_in_progress(token, user=None):
    """Teacher marks CALLED token as IN_PROGRESS (student has arrived)."""
    with transaction.atomic():
        token = ExamToken.objects.select_for_update().get(id=token.id)
        if token.status != 'CALLED':
            logger.warning("QUEUE_IN_PROGRESS_BAD_STATUS token=%s status=%s",
                           token.token_number, token.status)
            return None
        token.status = 'IN_PROGRESS'
        token.started_at = timezone.now()
        token.save(update_fields=['status', 'started_at'])
        logger.info("QUEUE_IN_PROGRESS token=%s student=%s",
                    token.token_number, token.student.code)
        return token


def complete_token(token, attempt=None, user=None):
    """Teacher marks IN_PROGRESS token as COMPLETED, optionally linking attempt."""
    with transaction.atomic():
        token = ExamToken.objects.select_for_update().get(id=token.id)
        token.status = 'COMPLETED'
        token.completed_at = timezone.now()
        if attempt:
            token.attempt = attempt
        token.save(update_fields=['status', 'completed_at', 'attempt'])
        logger.info("QUEUE_COMPLETED token=%s student=%s",
                    token.token_number, token.student.code)
        return token


def skip_token(token, user=None, reason=''):
    """Teacher marks token SKIPPED (no-show). Student must re-request."""
    with transaction.atomic():
        token = ExamToken.objects.select_for_update().get(id=token.id)
        token.status = 'SKIPPED'
        token.completed_at = timezone.now()
        token.notes = (token.notes + ' | ' + reason).strip(' |')
        token.save(update_fields=['status', 'completed_at', 'notes'])
        logger.info("QUEUE_SKIPPED token=%s student=%s reason=%s",
                    token.token_number, token.student.code, reason)
        return token


def expire_stale_tokens(grace_minutes=15):
    """Auto-skip CALLED tokens where started_at not set after grace_minutes."""
    cutoff = timezone.now() - timezone.timedelta(minutes=grace_minutes)
    with transaction.atomic():
        stale = list(ExamToken.objects.select_for_update().filter(
            status='CALLED', called_at__lt=cutoff,
        ))
        for token in stale:
            token.status = 'SKIPPED'
            token.completed_at = timezone.now()
            token.notes = (token.notes + ' | auto-expired').strip(' |')
            token.save(update_fields=['status', 'completed_at', 'notes'])
        if stale:
            logger.info("QUEUE_AUTO_EXPIRED count=%d", len(stale))
    return stale


def get_queue_snapshot():
    """Teacher panel: current queue state for today."""
    today = timezone.localdate()
    return {
        'date': today,
        'pending': ExamToken.objects.filter(date=today, status='PENDING').order_by('token_number'),
        'called': ExamToken.objects.filter(date=today, status='CALLED').order_by('token_number'),
        'in_progress': ExamToken.objects.filter(date=today, status='IN_PROGRESS').order_by('token_number'),
        'recent_completed': ExamToken.objects.filter(
            date=today, status__in=['COMPLETED', 'SKIPPED']
        ).order_by('-completed_at')[:10],
    }


def check_anti_cheat_gate(student):
    """Return (allowed, token, reason).

    Student may submit a physical test only if they have an active token
    in CALLED or IN_PROGRESS status.
    """
    token = ExamToken.objects.filter(
        student=student, status__in=['CALLED', 'IN_PROGRESS'],
    ).first()
    if token:
        return True, token, 'OK'
    pending = ExamToken.objects.filter(student=student, status='PENDING').first()
    if pending:
        return False, pending, f'You are #{pending.token_number} in queue — wait for teacher'
    return False, None, 'No active test appointment. Request a token first.'



# ═══════════════════════════════════════════════════════════
# Multi-Token Support (bulk request + per-student approval)
# ═══════════════════════════════════════════════════════════

MAX_ACTIVE_TOKENS_PER_STUDENT = 10


def issue_multiple_tokens(student, count=1, max_active=None):
    """Issue up to `count` new PENDING tokens, respecting daily max.
    Returns: (created_list, remaining_quota, error_message_or_None)
    """
    if max_active is None:
        max_active = MAX_ACTIVE_TOKENS_PER_STUDENT

    today = timezone.localdate()
    created = []

    with transaction.atomic():
        existing_active = ExamToken.objects.select_for_update().filter(
            student=student, date=today, status__in=ACTIVE_STATUSES,
        ).count()

        quota = max_active - existing_active
        if quota <= 0:
            return [], 0, f"You already have {existing_active} active token(s). Maximum is {max_active}."

        to_create = min(count, quota)
        max_num = ExamToken.objects.filter(date=today).aggregate(
            m=Max('token_number'))['m'] or 0

        for i in range(to_create):
            token = ExamToken.objects.create(
                student=student, date=today, token_number=max_num + 1 + i,
                status='PENDING', uses_remaining=1,
            )
            created.append(token)

        logger.info("QUEUE_ISSUED_MULTI student=%s count=%d tokens=%s",
                    student.code, len(created), [t.token_number for t in created])

    remaining = quota - len(created)
    return created, remaining, None


def approve_student_tokens(student, user=None):
    """Approve ALL PENDING tokens for one student → CALLED. Returns count."""
    today = timezone.localdate()
    count = 0
    with transaction.atomic():
        tokens = ExamToken.objects.select_for_update().filter(
            student=student, date=today, status='PENDING',
        ).order_by('token_number')

        for token in tokens:
            token.status = 'CALLED'
            token.called_at = timezone.now()
            token.called_by = user
            token.save(update_fields=['status', 'called_at', 'called_by'])
            count += 1

        if count:
            logger.info("QUEUE_STUDENT_APPROVED student=%s count=%d by=%s",
                        student.code, count, getattr(user, 'username', '?'))
    return count

