"""StudentDayMission - permanent record of questions assigned per day per student.

Enables "past days archive": after engine advances to Day N, questions from
Days < N remain visible and attemptable via collapsible archive UI.

Standards: Event Log pattern (Hephaestus, Rewardify);
ISO 27001 A.8.15 (immutable audit log); append-only; mirrors StudentQuestionLock.
"""
from django.db import models


class StudentDayMission(models.Model):
    """Permanent ledger: which questions belonged to which day for a student."""
    student = models.ForeignKey(
        'exams.Student', on_delete=models.CASCADE,
        related_name='day_missions',
    )
    day_number = models.PositiveIntegerField(db_index=True)
    subject = models.CharField(max_length=50)
    question = models.ForeignKey(
        'exams.ModelQuestion', on_delete=models.CASCADE,
        related_name='day_mission_entries',
    )
    position = models.PositiveSmallIntegerField(null=True, blank=True, db_index=True)
    locked_at = models.DateTimeField(auto_now_add=True)

    # PROVENANCE — where this mission row came from
    original_question = models.ForeignKey(
        'exams.ModelQuestion', null=True, blank=True,
        on_delete=models.SET_NULL, related_name='sdm_original_for',
        help_text='If MANUAL_OVERRIDE, the auto-assigned question it replaced (for clean revert).'
    )
    SOURCE_CHOICES = [
        ('AUTO', 'Auto-assigned'),
        ('STUDENT_CHOICE', 'Student selected before 8 AM'),
        ('STUDENT_CUSTOM', 'Student uploaded own question'),
        ('MANUAL_OVERRIDE', 'Manually overridden'),
        ('MANUAL_FULL', 'Fully manually assigned'),
    ]
    source = models.CharField(
        max_length=20, choices=SOURCE_CHOICES,
        default='AUTO', db_index=True,
        help_text='AUTO = system assigned. MANUAL_* = teacher override.'
    )

    class Meta:
        constraints = [models.UniqueConstraint(fields=['student', 'question'], name='unique_question_per_student')]
        unique_together = ('student', 'day_number', 'question')
        ordering = ['-day_number', 'subject', 'question__question_index']
        indexes = [
            models.Index(fields=['student', 'day_number']),
            models.Index(fields=['student', 'subject']),
        ]

    def __str__(self):
        return f"{self.student.code} D{self.day_number} Q{self.question_id}"



class QuestionReasoning(models.Model):
    STAGE_CHOICES = [
        ('ENGAGE', 'Engage (Hook & Prior Knowledge)'),
        ('EXPLORE', 'Explore (Inquiry & Discovery)'),
        ('EXPLAIN', 'Explain (Concept & Terminology)'),
        ('ELABORATE', 'Elaborate (Application & Transfer)'),
        ('APPLY', 'Apply (Guided Practice)'),
        ('ANALYZE', 'Analyze (Deconstruction)'),
        ('EVALUATE', 'Evaluate (Self-Assessment)'),
        ('REMEDIATE', 'Remediate (Targeted Fixes)'),
        ('EXTEND', 'Extend (Deep Mastery)'),
        ('REFLECT', 'Reflect (Metacognition)'),
    ]

    """Pro Learning: Multi-Modal Socratic Steps"""
    QUESTION_TYPES = [
        ('MCQ', 'Multiple Choice'),
        ('FILL_BLANK', 'Fill in the Blank'),
        ('SHORT_TEXT', 'Short Answer'),
        ('SEQUENCE', 'Sequence Ordering'),
        ('TRUE_FALSE', 'True / False'),
        ('MATCHING', 'Matching Pairs'),
    ]
    question = models.ForeignKey('exams.ModelQuestion', on_delete=models.CASCADE, related_name='reasoning_steps')
    step_number = models.PositiveIntegerField(default=1)
    step_type = models.CharField(max_length=20, choices=QUESTION_TYPES, default='SHORT_TEXT')
    stage = models.CharField(max_length=20, choices=STAGE_CHOICES, default='ENGAGE', help_text='Pedagogical stage')
    title = models.CharField(max_length=150, help_text="e.g., Step 1: Identify given values")
    prompt = models.TextField(help_text="The question or instruction.")
    options = models.JSONField(default=list, blank=True, help_text="For MCQ or Sequence")
    correct_answer = models.TextField(blank=True, help_text="The exact correct answer")
    explanation = models.TextField(blank=True, help_text="Why this is correct")
    hint = models.TextField(blank=True, help_text="Optional hint")

    class Meta:
        ordering = ['step_number']
        unique_together = ('question', 'step_number')

    def __str__(self):
        return f"Q{self.question.id} - Step {self.step_number} ({self.step_type})"

class DailyCodeVisibility(models.Model):
    """Per-day publication flag for daily test codes (Phase 2 - Teacher Control).

    Teacher has ultimate authority: codes are HIDDEN by default.
    Teacher explicitly publishes (reveals) them to students.

    Standards: ISO 27001 A.8.15 (immutable audit log),
    COPPA/FERPA (student privacy - codes not exposed until authorized),
    NIST SP 800-63B (authentication gatekeeping).
    """
    date = models.DateField(db_index=True, help_text="Calendar date")
    target_student = models.ForeignKey(
        'exams.Student',
        null=True, blank=True,
        on_delete=models.CASCADE,
        related_name='code_overrides',
        help_text='NULL = no student-specific override.',
    )
    target_class = models.CharField(
        max_length=20, blank=True, default='', db_index=True,
        help_text='Class scope. Empty = no class restriction.',
    )
    target_shift = models.CharField(
        max_length=10, blank=True, default='', db_index=True,
        help_text='Shift scope: "morning", "evening", or empty for all shifts.',
    )
    is_visible = models.BooleanField(default=False, db_index=True)
    morning_visible = models.BooleanField(default=False, db_index=True)
    evening_visible = models.BooleanField(default=False, db_index=True)
    published_at = models.DateTimeField(null=True, blank=True)
    published_by = models.ForeignKey(
        'auth.User', null=True, blank=True,
        on_delete=models.SET_NULL, related_name='code_publications'
    )
    hidden_at = models.DateTimeField(null=True, blank=True)
    hidden_by = models.ForeignKey(
        'auth.User', null=True, blank=True,
        on_delete=models.SET_NULL, related_name='code_hides'
    )
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)

    class Meta:
        ordering = ['-date']
        indexes = [models.Index(fields=['date', 'is_visible'])]

    def __str__(self):
        return f"{self.date} - {'VISIBLE' if self.is_visible else 'HIDDEN'}"

class DayAttemptPolicy(models.Model):
    """Teacher-controlled per-day policy for past-day re-attempts or future-day practice.

    Default state: LOCKED (only current day uploads allowed).

    Standards:
      - ISO 27001 A.12.1.4 (change control with audit trail)
      - MTSS Tier 2 (targeted re-teach/re-attempt)
      - "10% per day late penalty" (common academic policy)
      - "Max 2 resubmissions" (Georgia K-12 standard)
    """
    STATUS_CHOICES = [
        ('LOCKED', 'Locked - Retakes Disabled'),
        ('OPEN', 'Open - Retakes Allowed'),
        ('PAST_REATTEMPT', 'Past Day Re-attempts (Legacy)'),
        ('FUTURE_PRACTICE', 'Future Day Practice (Legacy)'),
    ]
    date = models.DateField(db_index=True, help_text="Calendar date this policy applies to")
    target_student = models.ForeignKey(
        'exams.Student',
        null=True, blank=True,
        on_delete=models.CASCADE,
        related_name='retake_policies',
        help_text='NULL = no student-specific override.',
    )
    target_class = models.CharField(
        max_length=20, blank=True, default='', db_index=True,
        help_text='Class scope (e.g. "9A"). Empty = no class restriction.',
    )
    target_shift = models.CharField(
        max_length=10, blank=True, default='', db_index=True,
        help_text='Shift scope: "morning", "evening", or empty for all shifts.',
    )
    status = models.CharField(max_length=20, choices=STATUS_CHOICES, default='LOCKED')
    max_attempts = models.PositiveSmallIntegerField(default=2, help_text="Legacy field - logic moved to RetakeRequest")
    late_penalty_pct = models.DecimalField(max_digits=5, decimal_places=2, default=10.00, help_text="Score reduction per re-attempt (%)")
    opened_by = models.ForeignKey('auth.User', null=True, blank=True, on_delete=models.SET_NULL, related_name='+')
    opened_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)
    notes = models.TextField(blank=True, default='')

    class Meta:
        ordering = ['-date']
        verbose_name_plural = 'Day attempt policies'
        # Composite index; MySQL nulls are distinct so this is a soft hint.
        unique_together = [('date', 'target_student', 'target_class', 'target_shift')]

    def __str__(self):
        return f"{self.date} - {self.status}"


class QuestionAssignment(models.Model):
    """Teacher-authored override of auto-assigned questions per date.

    SCOPED PATTERN (same as DayAttemptPolicy/DailyCodeVisibility):
      - target_student: X = one specific student
      - target_class: '9' = whole class
      - target_shift: 'morning' = whole shift
      - all NULL/empty = entire academy

    POSITION-BASED:
      Replaces the question at a specific position (1..pace) on the given
      date for the matching scope. Other positions stay auto-assigned.

    RESOLUTION (most-specific wins):
      Student > Class+Shift > Class > Shift > Global > Auto

    Standards:
      - MTSS Tier 2 (targeted differentiation)
      - Canvas "differentiated assignment" pattern
      - Moodle "user override" pattern
      - ISO 9001:2015 7.5.3 (documented control)
    """
    date = models.DateField(db_index=True, help_text="Calendar date the override applies to")
    target_student = models.ForeignKey(
        'exams.Student', null=True, blank=True,
        on_delete=models.CASCADE, related_name='question_assignments',
        help_text='Specific student override. NULL = class/shift/global scope.'
    )
    target_class = models.CharField(
        max_length=20, blank=True, default='', db_index=True,
        help_text='Class scope (e.g. "9"). Empty = no class restriction.'
    )
    target_shift = models.CharField(
        max_length=10, blank=True, default='', db_index=True,
        help_text='Shift scope: "morning", "evening", or empty.'
    )
    subject = models.CharField(
        max_length=50, db_index=True, blank=True, default='',
        help_text='Subject this override replaces (e.g. "Urdu", "Chemistry").'
    )
    position = models.PositiveSmallIntegerField(
        help_text="Position within the subject's question list (1..pace). Replaces only this slot."
    )
    question = models.ForeignKey(
        'exams.ModelQuestion', on_delete=models.CASCADE,
        related_name='manual_assignments',
        help_text='The question to assign at this position.'
    )
    assigned_by = models.ForeignKey(
        'auth.User', on_delete=models.SET_NULL, null=True, blank=True,
        related_name='question_assignments_created'
    )
    assigned_at = models.DateTimeField(auto_now_add=True)
    notes = models.TextField(blank=True, default='')
    is_active = models.BooleanField(default=True, db_index=True)

    class Meta:
        ordering = ['-date', 'position']
        unique_together = [('date', 'target_student', 'target_class', 'target_shift', 'subject', 'position')]
        indexes = [
            models.Index(fields=['date', 'is_active']),
            models.Index(fields=['date', 'target_class', 'target_shift']),
        ]

    def __str__(self):
        scope = 'ALL'
        if self.target_student:
            scope = self.target_student.code
        elif self.target_class and self.target_shift:
            scope = f"{self.target_class}·{self.target_shift}"
        elif self.target_class:
            scope = self.target_class
        elif self.target_shift:
            scope = self.target_shift
        return f"{self.date} {scope} pos{self.position} → Q{self.question_id}"


# ═══════════════════════════════════════════════════════════════
# QUESTION ASSIGNMENT SIGNALS — materialize overrides to SDM
# ═══════════════════════════════════════════════════════════════
from django.db.models.signals import post_save as _post_save, post_delete as _post_delete
from django.dispatch import receiver as _receiver


@_receiver(_post_save, sender=QuestionAssignment)
def _on_question_assignment_saved(sender, instance, created, **kwargs):
    if not instance.is_active:
        return
    try:
        from exams.services.question_assignment import apply_assignment
        apply_assignment(instance)
    except Exception as _e:
        import logging
        logging.getLogger(__name__).error(
            "question_assignment_signal_save_fail id=%s err=%s", instance.id, _e
        )


@_receiver(_post_delete, sender=QuestionAssignment)
def _on_question_assignment_deleted(sender, instance, **kwargs):
    try:
        from exams.services.question_assignment import revoke_assignment
        revoke_assignment(instance)
    except Exception as _e:
        import logging
        logging.getLogger(__name__).error(
            "question_assignment_signal_delete_fail id=%s err=%s", instance.id, _e
        )


class PoolExhaustionAlert(models.Model):
    """
    Human-in-the-Loop alert when a subject's question pool runs low or exhausts.

    The engine NEVER silently reuses questions. When a book runs out,
    an alert is created and the teacher must decide:
      - LOOP_BACK: restart this book from question 1 (reuse allowed)
      - EXTENDED: teacher will add more questions manually
      - SKIPPED: skip this book for remaining days

    Until the teacher decides, the engine halts question assignment for
    that book, leaving the SDM empty for that subject.
    """
    ALERT_TYPES = [
        ('WARNING', 'Running Low (below threshold)'),
        ('EXHAUSTED', 'Fully Exhausted'),
    ]
    DECISION_CHOICES = [
        ('OPEN', 'Needs Decision'),
        ('LOOP_BACK', 'Loop Back — restart this book from Q1'),
        ('EXTENDED', 'Extended — teacher will add more questions'),
        ('SKIPPED', 'Skipped — this book is paused'),
    ]

    book = models.CharField(max_length=50, db_index=True)
    student_class = models.CharField(max_length=50, db_index=True)
    alert_type = models.CharField(max_length=20, choices=ALERT_TYPES, default='WARNING')
    remaining_questions = models.IntegerField(default=0)
    pace_needed = models.IntegerField(default=0)
    days_of_buffer = models.IntegerField(default=0)
    decision = models.CharField(max_length=20, choices=DECISION_CHOICES, default='OPEN', db_index=True)
    decided_by = models.ForeignKey(
        'auth.User', null=True, blank=True,
        on_delete=models.SET_NULL, related_name='pool_decisions'
    )
    decided_at = models.DateTimeField(null=True, blank=True)
    notes = models.TextField(blank=True, default='')
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)

    class Meta:
        ordering = ['-created_at']
        unique_together = ('book', 'student_class')
        indexes = [
            models.Index(fields=['decision', 'student_class']),
        ]

    def __str__(self):
        return f"{self.student_class} {self.book} — {self.alert_type} ({self.decision})"
