from django.shortcuts import render, redirect
from django.contrib.auth.decorators import login_required
from django.contrib import messages
from django.db import transaction
from django.db.models import Max
from django.utils import timezone
from exams.models import Student, ModelPaper, ModelQuestion, StudentQuestionLock
from exams.models_day_mission import StudentDayMission
from exams.models import EngineState
import uuid

@login_required
def non_9th_write_question(request):
    student = Student.objects.filter(student_user=request.user, is_active=True).first()
    if not student and request.user.is_superuser:
        student = Student.objects.filter(is_active=True).first()
    if not student:
        return redirect('portal-dashboard')

    today = timezone.localdate()
    today_count = StudentQuestionLock.objects.filter(
        student=student, locked_at__date=today
    ).count()
    pace = student.daily_question_count or 4

    if request.method == 'POST':
        q_text = (request.POST.get('question_text') or '').strip()
        a_text = (request.POST.get('model_answer') or '').strip()
        subject = (request.POST.get('subject') or '').strip()
        selected_class = (request.POST.get('student_class') or '').strip()

        if not subject or not selected_class:
            messages.error(request, 'Class aur Subject dono chunna zaroori hai.')
            return redirect('non_9th:write_question')

        if len(q_text) < 15:
            messages.error(request, 'Question must be at least 15 characters.')
            return redirect('non_9th:write_question')
        if a_text and len(a_text) < 15:
            messages.error(request, 'Answer must be at least 15 characters if provided.')
            return redirect('non_9th:write_question')

        with transaction.atomic():
            # Create a unique paper for this exact class and subject
            paper_code = f"SELF-{student.code}-{uuid.uuid4().hex[:6].upper()}"
            paper = ModelPaper.objects.create(
                code=paper_code,
                subject=subject[:50],
                student_class=selected_class, # Tagged with selected class
                medium='EN',
                title=f'{student.name} - Personalized {subject}'
            )

            q = ModelQuestion.objects.create(
                paper=paper,
                question_index=1,
                question_text=q_text,
                model_answer=a_text,
                marks=2,
                chapter='Personalized',
                kc_code=''
            )

            StudentQuestionLock.objects.get_or_create(
                student=student, question=q, defaults={'is_active': True}
            )

            # Add to StudentDayMission so it appears on the dashboard
            engine = EngineState.objects.filter(id=1).first()
            current_day = engine.get_current_day() if engine and engine.has_started else 1

            StudentDayMission.objects.get_or_create(
                student=student,
                day_number=current_day,
                question=q,
                defaults={'subject': subject}
            )

            paper.total_questions = 1
            paper.save(update_fields=['total_questions'])

        messages.success(request, f'✓ Question added to {subject} ({selected_class}) successfully!')

        if today_count + 1 >= pace:
            return redirect('portal-daily-mission-v3')
        return redirect('non_9th:write_question')

    class_choices = Student.CLASS_CHOICES

    return render(request, 'non_9th/write_question.html', {
        'student': student,
        'today_count': today_count,
        'pace': pace,
        'class_choices': class_choices,
    })
