from django.core.management.base import BaseCommand
from django.db import transaction
from django.db.models import Max
from exams.models import Student, ModelPaper, ModelQuestion, StudentQuestionLock

class Command(BaseCommand):
    help = 'Seed Mizan pipeline (CUSTOM papers + first question) for all non-9th students.'

    def handle(self, *args, **options):
        non9_students = Student.objects.filter(is_active=True).exclude(
            student_class__in=['9', '9th', '9th class']
        )
        
        count = 0
        for student in non9_students:
            paper_code = f'CUSTOM-{student.code}'
            
            with transaction.atomic():
                # 1. Create Paper
                paper, paper_created = ModelPaper.objects.get_or_create(
                    code=paper_code,
                    defaults={
                        'subject': student.student_class or 'Custom',
                        'medium': 'EN',
                        'title': f'{student.name} - Custom Questions',
                        'total_questions': 0
                    }
                )
                
                # 2. Create First Question (if paper has 0 questions)
                if paper.total_questions == 0:
                    q = ModelQuestion.objects.create(
                        paper=paper,
                        question_index=1,
                        question_text=f"Welcome {student.name}! Write your first question here.",
                        model_answer="This is a placeholder answer. You will replace this with your own questions.",
                        marks=2,
                        chapter='Custom',
                        kc_code=''
                    )
                    
                    # 3. Create Lock
                    StudentQuestionLock.objects.get_or_create(
                        student=student, question=q, defaults={'is_active': True}
                    )
                    
                    paper.total_questions = 1
                    paper.save(update_fields=['total_questions'])
                    
                    self.stdout.write(self.style.SUCCESS(f"✓ Seeded pipeline for {student.code} ({student.name})"))
                    count += 1
                else:
                    self.stdout.write(f"  - {student.code} already has a pipeline. Skipping.")

        self.stdout.write(self.style.SUCCESS(f"\nDone. {count} new pipelines created."))
