"""Attempt policy resolution for past/future day uploads (Phase 4b).

Standards:
  - ISO 27001 A.12.1.4 (change control)
  - MTSS Tier 2 (targeted re-teach)
  - Moodle/Canvas "late submission" pattern (10% penalty, max attempts)
"""
from datetime import timedelta


def resolve_attempt_context(student, question):
    """Determine the target day and policy for an attempt.

    Returns dict:
        {
            'target_day': int or None,
            'target_date': date or None,
            'policy': DayAttemptPolicy or None,
            'is_late': bool,
            'is_practice': bool,
            'error': str or None,   # If set, the attempt must be rejected
        }
    """
    from exams.models import EngineState, AttemptLog
    from exams.models_day_mission import StudentDayMission, DayAttemptPolicy

    eng = EngineState.objects.filter(id=1).first()
    if not eng or not eng.has_started or not eng.start_date:
        # Engine not started - normal flow
        return {
            'target_day': None,
            'target_date': None,
            'policy': None,
            'is_late': False,
            'is_practice': False,
            'error': None,
        }

    current_day = eng.get_current_day()

    # Find which day this question is assigned to
    sdm = StudentDayMission.objects.filter(student=student, question=question).first()
    if not sdm:
        # Not in SDM - could be a SELF-/CUSTOM- question (self-authored)
        return {
            'target_day': current_day,
            'target_date': None,
            'policy': None,
            'is_late': False,
            'is_practice': False,
            'error': None,
        }

    target_day = sdm.day_number
    target_date = eng.start_date + timedelta(days=target_day - 1)

    if target_day == current_day:
        # Current day - normal flow
        return {
            'target_day': target_day,
            'target_date': target_date,
            'policy': None,
            'is_late': False,
            'is_practice': False,
            'error': None,
        }

    # Past or future - check policy
    policy = DayAttemptPolicy.objects.filter(date=target_date).first()

    if target_day < current_day:
        # PAST day — MANDATORY per-student teacher approval via RetakeRequest
        from exams.models import RetakeRequest
        subject = question.paper.subject if question.paper else ''

        approved_retake = RetakeRequest.objects.filter(
            student=student,
            day_number=target_day,
            subject=subject,
            status='APPROVED',
        ).order_by('-processed_at').first()

        if not approved_retake:
            return {
                'target_day': target_day,
                'target_date': target_date,
                'policy': policy,
                'is_late': False,
                'is_practice': False,
                'error': f'Day {target_day} ({target_date.strftime("%d %b")}) ke liye teacher ki approval zaroori hai. Pehle "Request Retake" button dabayein.',
            }

        # Attempt limit: 1 original + granted retakes
        max_attempts = 1 + (approved_retake.attempts_granted or 0)

        existing_count = AttemptLog.objects.filter(
            student=student,
            question=question,
            is_physical=True,
            target_day_number=target_day,
            cancelled_at__isnull=True,
        ).count()

        if existing_count >= max_attempts:
            return {
                'target_day': target_day,
                'target_date': target_date,
                'policy': policy,
                'is_late': False,
                'is_practice': False,
                'error': f'Aap ne {max_attempts} attempts use kar liye hain. Aur retake ke liye dobara "Request Retake" karein.',
            }

        return {
            'target_day': target_day,
            'target_date': target_date,
            'policy': policy,
            'is_late': True,
            'is_practice': False,
            'error': None,
        }

    # FUTURE day - must have FUTURE_PRACTICE policy
    if not policy or policy.status != 'FUTURE_PRACTICE':
        return {
            'target_day': target_day,
            'target_date': target_date,
            'policy': policy,
            'is_late': False,
            'is_practice': False,
            'error': f'Day {target_day} ({target_date.strftime("%d %b")}) is locked. Ask your teacher to open early practice.',
        }

    return {
        'target_day': target_day,
        'target_date': target_date,
        'policy': policy,
        'is_late': False,
        'is_practice': True,
        'error': None,
    }
