"""
Pilot command: create a student-authored CUSTOM question.

Verified against live schema (2026-10-28):
- ModelPaper: code CharField(no unique), subject CharField(no choices),
  medium EN/UR, total_questions PSInt default=0
- ModelQuestion: paper FK required, question_index PSInt required
  (unique_together with paper), question_text/model_answer TextField required,
  marks PSInt default=2, chapter/kc_code CharField blank=True,
  needs_teacher_review Boolean default=False, review_status CharField default='unreviewed'
- StudentQuestionLock: student FK, question FK, is_active Boolean default=True
  (unique_together student+question)

Safety:
- Only runs for students whose code starts with 'TEST-'
- --dry-run rolls back everything
- Idempotent: same question_text in same paper → no duplicate
"""
from django.core.management.base import BaseCommand, CommandError
from django.db import transaction
from django.db.models import Max
from exams.models import Student, ModelPaper, ModelQuestion, StudentQuestionLock


class Command(BaseCommand):
    help = 'Create a student-authored CUSTOM question (non-9th pilot).'

    def add_arguments(self, parser):
        parser.add_argument('--student-code', required=True)
        parser.add_argument('--question', required=True)
        parser.add_argument('--answer', required=True)
        parser.add_argument('--marks', type=int, default=2)
        parser.add_argument('--chapter', default='Custom')
        parser.add_argument('--dry-run', action='store_true')

    def handle(self, *args, **opts):
        code = opts['student_code'].strip()
        q_text = opts['question'].strip()
        a_text = opts['answer'].strip()

        if not code.startswith('TEST-'):
            raise CommandError(f"Refusing: code must start with TEST-. Got: {code}")
        if len(q_text) < 15:
            raise CommandError("Question must be >= 15 chars.")
        if len(a_text) < 15:
            raise CommandError("Answer must be >= 15 chars.")

        try:
            student = Student.objects.get(code=code, is_active=True)
        except Student.DoesNotExist:
            raise CommandError(f"No active student with code={code}")

        if not student.student_user:
            self.stdout.write(self.style.WARNING(
                f"  WARN: {student.code} has no user account — login will fail."
            ))

        paper_code = f'CUSTOM-{student.code}'
        prefix = '[DRY] ' if opts['dry_run'] else ''

        with transaction.atomic():
            paper = ModelPaper.objects.filter(code=paper_code).first()
            if paper:
                self.stdout.write(f"{prefix}Paper: code={paper.code} pk={paper.pk} (existing)")
            else:
                paper = ModelPaper.objects.create(
                    code=paper_code, subject='Custom', medium='EN',
                    title=f'{student.name} - Custom Questions',
                    total_questions=0,
                )
                self.stdout.write(f"{prefix}Paper: code={paper.code} pk={paper.pk} (CREATED)")

            dup = ModelQuestion.objects.filter(paper=paper, question_text=q_text).first()
            if dup:
                self.stdout.write(f"{prefix}Question exists pk={dup.pk} — ensuring lock.")
                q = dup
            else:
                max_idx = (ModelQuestion.objects.filter(paper=paper)
                           .aggregate(m=Max('question_index'))['m'] or 0)
                new_idx = max_idx + 1
                q = ModelQuestion.objects.create(
                    paper=paper, question_index=new_idx,
                    question_text=q_text, model_answer=a_text,
                    marks=opts['marks'], chapter=opts['chapter'],
                    kc_code='', needs_teacher_review=False,
                    review_status='unreviewed',
                )
                self.stdout.write(
                    f"{prefix}Question: pk={q.pk} idx={new_idx} "
                    f"marks={q.marks} chapter='{q.chapter}' kc_code=''"
                )

            lock, lock_created = StudentQuestionLock.objects.get_or_create(
                student=student, question=q, defaults={'is_active': True},
            )
            self.stdout.write(
                f"{prefix}Lock: pk={lock.pk} ({'CREATED' if lock_created else 'existing'})"
            )

            count = ModelQuestion.objects.filter(paper=paper).count()
            if paper.total_questions != count:
                paper.total_questions = count
                paper.save(update_fields=['total_questions'])
                self.stdout.write(f"{prefix}Paper.total_questions → {count}")

            if opts['dry_run']:
                transaction.set_rollback(True)
                self.stdout.write(self.style.WARNING(f"{prefix}DRY-RUN — rolled back."))
                return

        self.stdout.write(self.style.SUCCESS(
            f"\n✓ Done. {student.code} now has a question at STUDY.\n"
            f"  Question pk: {q.pk}\n"
            f"  Next: login as {student.code} → GET /api/portal/daily-mission-v3/\n"
            f"  Cleanup: python manage.py shell -c \"from exams.models import "
            f"ModelPaper; ModelPaper.objects.filter(code='{paper.code}').delete()\""
        ))
