from django.core.management.base import BaseCommand, CommandError
from exams.models import Student, ModelQuestion, StageUngate

class Command(BaseCommand):
    help = 'Force ungate a stage for a specific student and question.'

    def add_arguments(self, parser):
        parser.add_argument('--student-code', required=True, help='e.g., S-0006')
        parser.add_argument('--qid', required=True, type=int, help='Question ID')
        parser.add_argument('--stage', required=True, help='STUDY, ATTEMPT, VERIFY, etc.')

    def handle(self, *args, **options):
        code = options['student_code']
        qid = options['qid']
        stage = options['stage'].upper()

        student = Student.objects.filter(code=code).first()
        if not student:
            raise CommandError(f"Student {code} not found.")

        q = ModelQuestion.objects.filter(id=qid).first()
        if not q:
            raise CommandError(f"Question {qid} not found.")

        obj, created = StageUngate.objects.get_or_create(
            student=student, 
            question=q, 
            stage=stage,
            defaults={'ungated_by': None} # Admin/Teacher system
        )

        if created:
            self.stdout.write(self.style.SUCCESS(f"✓ Ungated {stage} for {code} on Q{qid}."))
        else:
            self.stdout.write(self.style.WARNING(f"Already ungated {stage} for {code} on Q{qid}."))
