"""Peer review delegation service.

Allows a teacher to assign any physical paper (AttemptLog) to any student
for first-pass review. Reviewer flags → teacher approves (COPE standard).

Key invariants:
- Reviewer CANNOT cancel — only teacher can apply cancellation
- Paper's own author CANNOT be a reviewer
- Every delegation is auditable via TaskDelegation row (FK to AttemptLog)
- Fraud cancellation only fires after teacher_approve_flag()
"""
from datetime import timedelta

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

from exams.models import Student, FraudCancellation
from exams.models_delegation import TaskDelegation


VALID_VERDICTS = ['VERIFIED', 'FLAGGED']


def create_peer_review(teacher, attempt, reviewer_user, notes='', deadline_hours=24):
    """Assign an attempt to a student reviewer. Returns TaskDelegation."""
    if not attempt:
        raise ValueError('attempt is required')
    if not reviewer_user:
        raise ValueError('reviewer_user is required')

    reviewer_student = Student.objects.filter(student_user=reviewer_user, is_active=True).first()
    if not reviewer_student:
        raise ValueError('Reviewer must be an active student with a user account')

    if reviewer_student.id == attempt.student_id:
        raise ValueError('Cannot assign review to the paper owner')

    # Prevent duplicate live delegations for the same (reviewer, attempt)
    existing = TaskDelegation.objects.filter(
        assignee=reviewer_user,
        task_type='PEER_REVIEW',
        attempt_log=attempt,
        review_verdict='PENDING',
    ).exists()
    if existing:
        raise ValueError('This paper is already assigned to this reviewer')

    expires = timezone.now() + timedelta(hours=int(deadline_hours or 24))

    delegation = TaskDelegation.objects.create(
        assignee=reviewer_user,
        task_type='PEER_REVIEW',
        target_class=attempt.student.student_class or '',
        delegation_mode='INDIVIDUAL',
        custom_url=f'/api/portal/my-reviews/{attempt.id}/',
        notes=notes or '',
        uses_remaining=1,
        expires_at=expires,
        created_by=teacher,
        attempt_log=attempt,
        review_verdict='PENDING',
    )
    return delegation


def get_review_queue(user, include_completed=False):
    """Live peer reviews assigned to a user."""
    qs = TaskDelegation.objects.filter(
        assignee=user,
        task_type='PEER_REVIEW',
        expires_at__gt=timezone.now(),
    ).select_related('attempt_log', 'attempt_log__student', 'attempt_log__question', 'created_by')

    if not include_completed:
        qs = qs.filter(review_verdict='PENDING')

    return qs.order_by('-created_at')


def get_eligible_reviewers(attempt, exclude_self=True):
    """List of users eligible to review this paper."""
    qs = Student.objects.filter(
        is_active=True, student_user__isnull=False,
    ).select_related('student_user')

    if exclude_self:
        qs = qs.exclude(id=attempt.student_id)

    return qs.order_by('code')


@transaction.atomic
def submit_review(delegation, reviewer_user, verdict, comment=''):
    """Submit a review verdict. Does NOT auto-apply cancellation."""
    if delegation.review_verdict != 'PENDING':
        raise ValueError('This review has already been submitted')
    if delegation.assignee_id != reviewer_user.id:
        raise PermissionError('You are not the assigned reviewer')

    if verdict not in VALID_VERDICTS:
        raise ValueError(f'Invalid verdict {verdict!r}. Must be one of {VALID_VERDICTS}')

    delegation.review_verdict = verdict
    delegation.review_comment = (comment or '').strip()
    delegation.reviewed_at = timezone.now()
    delegation.reviewed_by = reviewer_user
    delegation.save(update_fields=[
        'review_verdict', 'review_comment', 'reviewed_at', 'reviewed_by',
    ])
    return delegation


def get_pending_flags():
    """All flagged reviews awaiting teacher approval."""
    return TaskDelegation.objects.filter(
        task_type='PEER_REVIEW',
        review_verdict='FLAGGED',
    ).select_related(
        'attempt_log', 'attempt_log__student', 'reviewed_by', 'created_by',
    ).order_by('-reviewed_at')


@transaction.atomic
def teacher_approve_flag(delegation, teacher_user, override_reason=''):
    """Teacher APPROVES a flagged review -> fraud cancellation is applied."""
    if delegation.review_verdict != 'FLAGGED':
        raise ValueError('This delegation is not in FLAGGED state')
    if not (getattr(teacher_user, 'is_staff', False) or getattr(teacher_user, 'is_superuser', False)):
        raise PermissionError('Only teachers can approve flags')
    if not delegation.attempt_log_id:
        raise ValueError('No attempt linked')

    attempt = delegation.attempt_log
    reviewer_label = delegation.reviewed_by.username if delegation.reviewed_by else 'unknown'
    reason = override_reason.strip() or delegation.review_comment or f'Flagged by peer reviewer {reviewer_label}'

    from exams.services import fraud_cancellation as fc
    fraud = fc.apply_cancel(
        teacher=teacher_user,
        student=attempt.student,
        scope='SINGLE',
        reason=reason,
        evidence_url=f'Peer review by {reviewer_label}',
        attempt_ids=[attempt.id],
    )

    delegation.pending_fraud_id = fraud.id
    delegation.review_verdict = 'CANCELLED'
    delegation.review_comment = (
        (delegation.review_comment or '') +
        f'\n\n[Teacher {teacher_user.username} approved — FraudCancellation #{fraud.id}]'
    )
    delegation.save(update_fields=['pending_fraud_id', 'review_verdict', 'review_comment'])
    return fraud


@transaction.atomic
def teacher_dismiss_flag(delegation, teacher_user, comment=''):
    """Teacher DISMISSES a flagged review -> paper accepted as legitimate."""
    if delegation.review_verdict != 'FLAGGED':
        raise ValueError('This delegation is not in FLAGGED state')
    if not (getattr(teacher_user, 'is_staff', False) or getattr(teacher_user, 'is_superuser', False)):
        raise PermissionError('Only teachers can dismiss flags')

    delegation.review_verdict = 'VERIFIED'
    delegation.review_comment = (
        (delegation.review_comment or '') +
        f'\n\n[Teacher {teacher_user.username} dismissed]: {comment or "accepted as legitimate"}'
    )
    delegation.save(update_fields=['review_verdict', 'review_comment'])
    return delegation


def get_active_delegation_for_attempt(attempt_id, reviewer_user_id):
    """Find the live delegation for (attempt, reviewer), if any."""
    return TaskDelegation.objects.filter(
        task_type='PEER_REVIEW',
        attempt_log_id=attempt_id,
        assignee_id=reviewer_user_id,
    ).first()
