from django.core.management.base import BaseCommand
from exams.models import Student
from exams.models_day_mission import StudentDayMission
from exams.mizan_algorithm import compute, MIZAN_RESET_DATE
from django.utils import timezone

class Command(BaseCommand):
    help = "Weekly audit: verify SDM DB matches calendar-derived expected workload."

    def handle(self, *args, **options):
        today = timezone.localdate()
        days_elapsed = max(0, (today - MIZAN_RESET_DATE).days + 1)  # +1 because Nov 1 is Day 1
        print(f"Days elapsed since Nov 1: {days_elapsed}")

        students = Student.objects.filter(is_active=True, student_class__startswith='9')
        drift_count = 0
        for s in students:
            pace = s.daily_question_count or 1
            books = 8
            expected = days_elapsed * pace * books
            actual = StudentDayMission.objects.filter(student=s).count()
            drift = expected - actual
            if abs(drift) > 5:
                drift_count += 1
                print(f"  DRIFT {s.code} {s.name}: expected={expected} actual={actual} diff={drift:+d}")

        if drift_count == 0:
            print("✅ All students reconciled. No drift.")
        else:
            print(f"⚠️ {drift_count} students have drift >5. Run: python manage.py ensure_sdm_for_all")
