"""
apply_overdue_penalties - Enforces MTSS-style tiered penalties for overdue tasks.
Standards: MTSS Tier 1/2/3, Moodle late penalty, Monash automated penalties.
"""
from django.core.management.base import BaseCommand
from django.utils import timezone
from datetime import timedelta
from exams.models import Student, EngineState, SupportTicket, ParentReport
from exams.models_overdue_penalty import OverduePenalty
from exams.models_day_mission import StudentDayMission
from exams.models import Submission

class Command(BaseCommand):
    help = 'Applies tiered penalties for overdue tasks based on MTSS framework.'

    def add_arguments(self, parser):
        parser.add_argument('--student', type=str, help='Run for a specific student code')

    def handle(self, *args, **opts):
        engine = EngineState.objects.filter(id=1).first()
        if not engine or not engine.has_started:
            self.stdout.write("Engine not started. Nothing to do.")
            return

        base_day = engine.get_current_day()
        if base_day <= 1:
            self.stdout.write(f"Engine day {base_day}. No past days yet.")
            return

        students = Student.objects.filter(is_active=True)
        if opts['student']:
            students = students.filter(code=opts['student'])

        total_created = 0
        students_affected = 0

        for student in students:
            # Find all past-day ungraded questions
            # Robust loop to find actual ungraded overdue questions
            overdue_qs = []
            past_missions = StudentDayMission.objects.filter(student=student, day_number__lt=base_day).select_related('question')
            for entry in past_missions:
                has_submission = Submission.objects.filter(
                    exam__student=student,
                    exam__model_question=entry.question,
                    status__in=['graded', 'reviewed']
                ).exists()
                if not has_submission:
                    overdue_qs.append(entry)

            if not overdue_qs:
                continue

            overdue_count = len(overdue_qs)

            # MTSS Tiered Escalation
            if overdue_count >= 6:
                # Tier 3: Intensive (Parent Report)
                penalty_points = -2.0
                # Create a ParentReport if not exists for this month
                month_start = timezone.now().replace(day=1).date()
                ParentReport.objects.get_or_create(
                    student=student,
                    date_from=month_start,
                    date_to=timezone.now().date(),
                    defaults={
                        'period_kind': 'MONTH',
                        'week_number': 1,
                        'overall_progress': f'Aap ke bachay ke {overdue_count} kaam overdue hain.',
                        'action_items': 'Baraye meharbani ghar par check karein aur teacher se rabta karein.'
                    }
                )
                self.stdout.write(self.style.WARNING(f"Tier 3: {student.code} - Parent Report created."))
            elif overdue_count >= 3:
                # Tier 2: Targeted (Teacher Ticket)
                penalty_points = -1.0
                SupportTicket.objects.get_or_create(
                    student=student,
                    subject='Overdue Work - Tier 2',
                    defaults={
                        'category': 'ACADEMIC',
                        'priority': 'HIGH',
                        'status': 'OPEN',
                        'body': f'{overdue_count} tasks overdue. Please check.'
                    }
                )
                self.stdout.write(self.style.WARNING(f"Tier 2: {student.code} - Teacher ticket created."))
            else:
                # Tier 1: Universal (Notification only)
                penalty_points = -0.5
                # No extra action, just penalty.

            # Create penalties for each overdue question
            for entry in overdue_qs:
                penalty, created = OverduePenalty.objects.get_or_create(
                    student=student,
                    question=entry.question,
                    defaults={
                        'penalty_points': penalty_points,
                        'status': 'ACTIVE',
                    }
                )
                if created:
                    total_created += 1
                    students_affected += 1

        self.stdout.write(self.style.SUCCESS(
            f'Created {total_created} penalties for {students_affected} students.'
        ))
