from django.core.management.base import BaseCommand
from exams.models import Student, ModelQuestion
from exams.services.master_plan_panel import get_missed_questions, get_or_create_memorization_flow

class Command(BaseCommand):
    help = 'Auto-builds memorization flows for all students missed questions.'

    def handle(self, *args, **kwargs):
        students = Student.objects.filter(is_active=True)
        total_built = 0
        for s in students:
            buckets = get_missed_questions(s)
            for cat in ('failed', 'not_attempted'):
                for subj in buckets[cat]:
                    for item in buckets[cat][subj]:
                        q = ModelQuestion.objects.get(pk=item['qid'])
                        flow, created = get_or_create_memorization_flow(s, q)
                        if created:
                            total_built += 1
        self.stdout.write(self.style.SUCCESS(f'Successfully built {total_built} new flows.'))
