"""Workshop models -- MDD Phase 1 scaffolding + Phase 2 review queue."""
from django.conf import settings
from django.db import models


class QuestionBlueprint(models.Model):
    """Declares acceptable question types/difficulty for a KC at a pipeline stage."""
    STAGES = [
        ('SELECT', 'Select'),
        ('STUDY', 'Study'),
        ('ATTEMPT', 'Attempt'),
        ('REMEDIATION', 'Remediation'),
        ('VERIFY', 'Verify'),
        ('SAFAR', 'Safar'),
    ]
    QUESTION_TYPES = [
        ('MCQ', 'Multiple Choice'),
        ('FILL_BLANK', 'Fill in the Blank'),
        ('MATCHING', 'Matching'),
        ('REORDER', 'Reorder Sentences'),
        ('STORY_COMP', 'Story Comprehension'),
    ]

    kc = models.ForeignKey(
        'exams.KnowledgeComponent',
        on_delete=models.CASCADE,
        related_name='blueprints',
    )
    stage = models.CharField(max_length=20, choices=STAGES)
    question_type = models.CharField(max_length=20, choices=QUESTION_TYPES)
    difficulty_tier = models.PositiveSmallIntegerField(
        choices=[(1, 'Basic'), (2, 'Standard'), (3, 'Advanced')],
        default=2,
    )
    is_active = models.BooleanField(default=True)
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)

    class Meta:
        unique_together = ('kc', 'stage', 'question_type', 'difficulty_tier')
        ordering = ['kc_id', 'stage', 'difficulty_tier']
        indexes = [
            models.Index(fields=['kc', 'stage']),
            models.Index(fields=['stage', 'question_type']),
        ]

    def __str__(self):
        return f'{self.kc_id} | {self.stage} | {self.question_type} | T{self.difficulty_tier}'


class ConceptScaffold(models.Model):
    """Roman Urdu scaffolding to bridge the language gap before the English question."""
    kc = models.OneToOneField(
        'exams.KnowledgeComponent',
        on_delete=models.CASCADE,
        related_name='scaffold',
    )
    roman_urdu_intro = models.TextField(
        help_text='e.g., Metabolism kya hai? Yeh anabolism aur catabolism ka sum hai.'
    )
    vocabulary_bridge = models.JSONField(
        default=dict, blank=True,
        help_text='Map English term -> Roman Urdu equivalent.',
    )
    socratic_hints_ur = models.JSONField(
        default=list, blank=True,
        help_text='Ordered list of Roman Urdu hints for progressive disclosure.',
    )
    is_approved = models.BooleanField(
        default=False,
        help_text='Teacher must approve before students see it.',
    )
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)

    class Meta:
        verbose_name = 'Concept Scaffold (Roman Urdu)'
        verbose_name_plural = 'Concept Scaffolds (Roman Urdu)'

    def __str__(self):
        return f'Scaffold({self.kc_id}) [{"approved" if self.is_approved else "pending"}]'


class SystemImprovementTask(models.Model):
    """Student feedback / AI drafts awaiting teacher review."""
    STATUS_CHOICES = [
        ('PENDING', 'Pending Review'),
        ('APPROVED', 'Approved & Implemented'),
        ('REJECTED', 'Rejected'),
    ]

    student = models.ForeignKey(
        'exams.Student',
        on_delete=models.SET_NULL, null=True, blank=True,
        related_name='improvement_suggestions',
    )
    kc = models.ForeignKey(
        'exams.KnowledgeComponent',
        on_delete=models.SET_NULL, null=True, blank=True,
        related_name='improvement_tasks',
    )
    content = models.TextField(
        help_text="Student comment, requested question type, or AI-generated content."
    )
    status = models.CharField(
        max_length=20, choices=STATUS_CHOICES, default='PENDING', db_index=True,
    )
    created_at = models.DateTimeField(auto_now_add=True)
    reviewed_by = models.ForeignKey(
        settings.AUTH_USER_MODEL,
        on_delete=models.SET_NULL, null=True, blank=True,
        related_name='reviewed_tasks',
    )
    review_notes = models.TextField(blank=True)
    reviewed_at = models.DateTimeField(null=True, blank=True)

    class Meta:
        ordering = ['-created_at']
        indexes = [
            models.Index(fields=['status', '-created_at']),
            models.Index(fields=['student', '-created_at']),
        ]

    def __str__(self):
        return f'Task #{self.pk} [{self.status}] {self.content[:40]}'
