"""Data models for the Idealogy exam grading system."""
from django.conf import settings
import secrets

from django.db import models


class Student(models.Model):
    # Map of day_number (as string) to Google Drive folder URL for that day
    drive_evidence_links = models.JSONField(default=dict, blank=True, help_text="Map of day numbers to Drive folder URLs")

    TIER_CHOICES = [
        (1, "Tier 1 - Strong"),
        (2, "Tier 2 - Medium"),
        (3, "Tier 3 - Borderline Weak"),
        (4, "Tier 4 - Weak"),
        (5, "Tier 5 - Lowest"),
    ]
    CLASS_CHOICES = [
        ("play group", "Play Group"),
        ("nursery", "Nursery"),
        ("prep", "Prep"),
        ("1", "Class 1"),
        ("2", "Class 2"),
        ("3", "Class 3"),
        ("4", "Class 4"),
        ("5", "Class 5"),
        ("6", "Class 6"),
        ("7", "Class 7"),
        ("8", "Class 8"),
        ("9", "Class 9"),
        ("10", "Class 10"),
        ("11", "Class 11"),
        ("12", "Class 12"),
    ]
    SHIFT_CHOICES = [
        ("morning", "Morning"),
        ("afternoon", "Afternoon"),
    ]

    code = models.CharField(max_length=20, unique=True, help_text="e.g. S-0001")
    name = models.CharField(max_length=200)
    first_name = models.CharField(max_length=100, blank=True, default='')
    last_name = models.CharField(max_length=100, blank=True, default='')
    GENDER_CHOICES = [("M", "Male"), ("F", "Female")]
    gender = models.CharField(max_length=1, choices=GENDER_CHOICES, default="M", help_text="Student gender for AI personalization")
    student_class = models.CharField(max_length=50, choices=CLASS_CHOICES, default="9")
    tier = models.PositiveSmallIntegerField(choices=TIER_CHOICES, default=3)
    shift = models.CharField(max_length=20, choices=SHIFT_CHOICES, default="morning")
    father_name = models.CharField(max_length=200, blank=True)
    whatsapp_student = models.CharField(max_length=30, blank=True)
    whatsapp_parent = models.CharField(max_length=30, blank=True)
    whatsapp_consent = models.BooleanField(default=False, help_text='Parent has consented to WhatsApp alerts')
    notes = models.TextField(blank=True, help_text="Teacher notes about this student")
    parent_phone = models.CharField(max_length=20, blank=True, default="", help_text="WhatsApp number with country code (e.g., 923001234567)")
    is_active = models.BooleanField(default=True)

    # Book assignment (2026-10-13, session 17)
    assigned_subject = models.CharField(max_length=32, blank=True, default="")
    assigned_book_code = models.CharField(max_length=64, blank=True, default="")
    assigned_at = models.DateTimeField(null=True, blank=True)
    assigned_by = models.CharField(max_length=150, blank=True, default="")

    # Medium of instruction (Session 8: for reasoning-answer language)
    MEDIUM_CHOICES = [("EN", "English"), ("UR", "Urdu / Roman Urdu")]
    medium = models.CharField(
        max_length=2, choices=MEDIUM_CHOICES, default="EN",
        help_text="EN: corrections in English. UR: corrections in Urdu (Roman Urdu in inputs, Urdu script in display where supported).",
    )

    # Magic-link token for parent portal access
    portal_token = models.CharField(max_length=64, unique=True, blank=True)

    # Login accounts (Django User). Nullable until teacher provisions them.
    parent_user = models.OneToOneField(
        "auth.User", on_delete=models.SET_NULL, null=True, blank=True,
        related_name="student_as_parent",
        help_text="Login for the parent."
    )
    student_user = models.OneToOneField(
        "auth.User", on_delete=models.SET_NULL, null=True, blank=True,
        related_name="student_self",
        help_text="Login for the student."
    )

    enrolled_subjects = models.JSONField(
        default=list, blank=True,
        help_text="Declared subject prefixes: MT PH CH BI EN UR IS CS TQ.",
    )
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)


    # Pacing fields
    daily_question_count = models.PositiveSmallIntegerField(default=1)
    daily_question_code = models.PositiveSmallIntegerField(default=0, help_text="Randomly generated daily question number based on pace.")
    pacing_locked_until = models.DateField(null=True, blank=True)
    parent_pacing_locked_until = models.DateField(null=True, blank=True)
    class Meta:
        ordering = ["code"]

    def __str__(self):
        return f"{self.code} - {self.name}"

    def get_current_day(self):
        """Calendar-based day counter. Day 1 = start_date. Ticks at midnight."""
        if not self.has_started:
            return 0
        if not self.start_date:
            return self.start_day or 1
        from django.utils import timezone
        delta = (timezone.localdate() - self.start_date).days
        return max(1, (self.start_day or 1) + delta)

    def save(self, *args, **kwargs):
        if not self.portal_token:
            self.portal_token = secrets.token_urlsafe(32)
        super().save(*args, **kwargs)


class Exam(models.Model):
    """A single test/quiz session. One exam = one question + one subject + one date."""
    student = models.ForeignKey(Student, on_delete=models.CASCADE, related_name="exams")
    subject = models.CharField(max_length=50)
    topic = models.CharField(max_length=200, blank=True)
    question_text = models.TextField(help_text="The question the student answered")
    expected_answer = models.TextField(blank=True)
    rubric = models.TextField(blank=True, help_text="Free-text rubric for the AI")
    max_marks = models.DecimalField(max_digits=5, decimal_places=2, default=10)
    exam_date = models.DateField()
    question_index = models.PositiveSmallIntegerField(
        null=True, blank=True,
        help_text="Order of this question on the paper (1-based)."
    )
    kc_code = models.CharField(
        max_length=30, blank=True, db_index=True,
        help_text="KnowledgeComponent.code (Q-matrix link). AERA Std 13.7.")
    model_question = models.ForeignKey(
        "ModelQuestion", on_delete=models.SET_NULL, null=True, blank=True,
        related_name="exam_attempts",
        help_text="RPS Phase 3.5: deterministic link to the source bank question.",
    )
    created_at = models.DateTimeField(auto_now_add=True)

    TEST_MODE_CHOICES = [
        ('INDIVIDUAL', 'Individual (1 trophy per question)'),
        ('DAILY_QUOTA', 'Daily Quota (pace trophies per question)'),
    ]
    test_mode = models.CharField(
        max_length=20, choices=TEST_MODE_CHOICES, default='INDIVIDUAL',
        db_index=True,
        help_text='Controls trophy multiplier: DAILY_QUOTA uses pace, INDIVIDUAL uses 1.',
    )

    class Meta:
        ordering = ["-exam_date", "-created_at"]

    def __str__(self):
        return f"{self.student.code} - {self.subject} - {self.exam_date}"


class Submission(models.Model):
    panel_verdict = models.JSONField(default=dict, blank=True, help_text='Expert panel verdict')
    STATUS_CHOICES = [
        ("pending", "Pending"),
        ("graded", "Graded"),
        ("reviewed", "Reviewed by teacher"),
        ("failed", "Failed"),
    ]

    exam = models.ForeignKey(Exam, on_delete=models.CASCADE, related_name="submissions")
    image = models.ImageField(upload_to="submissions/%Y/%m/", blank=True, null=True)
    ocr_text = models.TextField(blank=True)
    ai_score = models.DecimalField(max_digits=5, decimal_places=2, null=True, blank=True)
    ai_confidence = models.DecimalField(max_digits=4, decimal_places=3, null=True, blank=True)
    ai_rationale = models.TextField(blank=True)
    ai_mistakes = models.JSONField(default=list, blank=True)
    ai_recommendations = models.JSONField(default=list, blank=True)
    ai_raw = models.JSONField(default=dict, blank=True)
    teacher_score = models.DecimalField(max_digits=5, decimal_places=2, null=True, blank=True)
    teacher_notes = models.TextField(blank=True)
    status = models.CharField(max_length=20, choices=STATUS_CHOICES, default="pending")
    error_message = models.TextField(blank=True)
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)

    class Meta:
        ordering = ["-created_at"]

    def __str__(self):
        return f"Submission {self.pk} - {self.exam}"


class CorrectionEntry(models.Model):
    """Append-only record of a student correcting a graded submission.

    One row per correction event. A student who corrects the same submission
    multiple times produces multiple rows; the append-only log is the
    authoritative record (Rule 9).

    Display state is derived at read time:
      - CorrectionEntry row exists           -> SAHI (corrected)
      - ai_raw.band in {Excellent, Good}     -> SAHI (correct on first attempt)
      - ai_raw.band in {Fair, Average}       -> SUDHAAR
      - ai_raw.band in {Below Average, Wrong, Not Attempted} -> DOBARA

    Standards: Bloom 1968 (mastery learning; parallel second assessment);
    Guskey 1997 (feedback + individualised correctives); NCTQ Correctives
    Indicator (moderate/high correctives); Ericsson / RCPD (interrupt error,
    re-attempt until mastery); Zimmerman SRL (performance-phase error detection);
    AERA/APA/NCME 2014 Std 1.0 (construct named); Rule 9 (append-only);
    Rule 10 (one canonical writer); Rule 14 (student's own task).
    """
    submission = models.ForeignKey(Submission, on_delete=models.CASCADE,
                                   related_name="corrections")
    student = models.ForeignKey(Student, on_delete=models.CASCADE,
                                related_name="correction_entries")
    note = models.CharField(max_length=200, blank=True)
    marked_at = models.DateTimeField(auto_now_add=True, db_index=True)

    class Meta:
        ordering = ["-marked_at"]
        indexes = [models.Index(fields=["student", "submission"])]

    def __str__(self):
        return "Correction sub#%s by %s" % (self.submission_id, self.student.code)


class Attendance(models.Model):
    """Derived from test presence: if no exam submitted on a date, student is absent."""
    student = models.ForeignKey(Student, on_delete=models.CASCADE, related_name="attendance")
    date = models.DateField()
    present = models.BooleanField(default=True)
    reason = models.CharField(max_length=200, blank=True)
    # v2.3 attendance state model (2026-10-09).
    # Standards: ISO 8601-1:2019 (duration in minutes); Wallington Girls
    # 2025-26 Attendance Procedure (late = 'L' code; minutes recorded;
    # unauthorised absence != authorised); AERA/APA/NCME 2014 Std 1.0
    # (each value names its construct); Rule 14 (teacher-only).
    state = models.CharField(max_length=10, default="PRESENT", choices=[
        ("PRESENT", "Present"),
        ("ABSENT", "Absent (unexcused)"),
        ("LATE", "Late"),
        ("EXCUSED", "Excused (authorised)"),
    ], db_index=True)
    late_minutes = models.PositiveSmallIntegerField(default=0)
    recorded_by = models.ForeignKey(
        "auth.User", on_delete=models.SET_NULL, null=True, blank=True,
        related_name="attendance_recorded")

    class Meta:
        unique_together = [("student", "date")]
        ordering = ["-date"]

    def __str__(self):
        return f"{self.student.code} - {self.date} - {'P' if self.present else 'A'}"


class DailyTask(models.Model):
    """Task assigned to a student for a specific day."""
    student = models.ForeignKey(Student, on_delete=models.CASCADE, related_name="tasks")
    date_assigned = models.DateField()
    date_due = models.DateField()
    subject = models.CharField(max_length=50, blank=True)
    description = models.TextField()
    completed = models.BooleanField(default=False)
    completed_at = models.DateTimeField(null=True, blank=True)
    created_at = models.DateTimeField(auto_now_add=True)

    class Meta:
        ordering = ["date_due", "student__code"]

    def __str__(self):
        return f"{self.student.code} - {self.date_due}"


class ParentReport(models.Model):
    """Period parent report (weekly or monthly).

    Standards: Guskey 2024 (communication device); NSW DoE plain
    language; ESSA Report Card Design; DBI/MTSS period progress.
    """
    PERIOD_CHOICES = [("WEEK", "Week"), ("MONTH", "Month")]
    student = models.ForeignKey(Student, on_delete=models.CASCADE, related_name="parent_reports")
    period_kind = models.CharField(max_length=6, choices=PERIOD_CHOICES,
                                   default="WEEK", db_index=True)
    week_number = models.PositiveSmallIntegerField(
        null=True, blank=True,
        help_text="ISO week 1-53 for WEEK rows; null for MONTH rows.")
    date_from = models.DateField()
    date_to = models.DateField()
    overall_progress = models.CharField(max_length=50, blank=True)
    strengths = models.TextField(blank=True)
    weaknesses = models.TextField(blank=True)
    action_items = models.TextField(blank=True)
    hw_rd_summary = models.JSONField(default=dict, blank=True,
        help_text="Monthly Likhai aur Padhai summary (DASH-2 + Hasbrouck-Tindal counts). AERA Std 1.0.")
    # Kaifiyat_e_Mizan snapshot at report time (Rule I; AERA Std 1.0;
    # "a value names its construct" — the PDF reads the number that was
    # current when the report was built, not a value recomputed later).
    kzm_score = models.PositiveIntegerField(null=True, blank=True)
    kzm_band = models.CharField(max_length=20, blank=True)
    attendance_ratio = models.DecimalField(max_digits=5, decimal_places=2, null=True, blank=True)
    pdf_file = models.FileField(upload_to="parent_reports/", blank=True, null=True)
    sent_at = models.DateTimeField(null=True, blank=True)
    created_at = models.DateTimeField(auto_now_add=True)

    class Meta:
        ordering = ["-date_to"]

    def __str__(self):
        return f"{self.student.code} - Week {self.week_number}"


class WhatsAppLog(models.Model):
    """Track every report sent via WhatsApp (manual send, logged here for history)."""
    student = models.ForeignKey(Student, on_delete=models.CASCADE, related_name="whatsapp_logs")
    message_type = models.CharField(max_length=50)
    phone_number = models.CharField(max_length=30)
    message_preview = models.TextField(blank=True)
    sent_at = models.DateTimeField(auto_now_add=True)

    class Meta:
        ordering = ["-sent_at"]

    def __str__(self):
        return f"{self.student.code} - {self.message_type} - {self.sent_at:%Y-%m-%d}"


# ---------- Understanding Path (Section 9 of takeover guide) ----------


class StoryLecture(models.Model):
    """One story-lecture per tested question per subject per teaching day.

    All students in the class see the same 3 stories per subject.
    Story teaches the concept from zero, beginner level, Roman Urdu only.
    """
    student_class = models.CharField(max_length=50, db_index=True, default='9')
    subject = models.CharField(max_length=50, db_index=True)
    chapter = models.CharField(max_length=200, blank=True)
    question_text = models.TextField(help_text="The listed question this story teaches")
    question_index = models.PositiveSmallIntegerField(
        help_text="1, 2, or 3 - which of the three listed questions")
    story_text = models.TextField(help_text="Full story lecture in Roman Urdu")
    analogy_used = models.CharField(max_length=200, blank=True,
                                   help_text="The human analogy, e.g. bond = marriage")
    comprehension_question = models.TextField(
        help_text="One open question the student reflects on (3-line answer)")
    teaching_date = models.DateField(db_index=True)
    source_exam_date = models.DateField(help_text="Day 1 test that this story teaches")
    created_at = models.DateTimeField(auto_now_add=True)

    class Meta:
        ordering = ["teaching_date", "subject", "question_index"]
        unique_together = [("student_class", "subject", "question_index", "teaching_date")]

    def __str__(self):
        return f"{self.subject} Q{self.question_index} - {self.teaching_date}"


class StoryReflection(models.Model):
    """A student 3-line written reflection on one story-lecture."""
    student = models.ForeignKey(
        Student, on_delete=models.CASCADE, related_name="story_reflections")
    story = models.ForeignKey(
        StoryLecture, on_delete=models.CASCADE, related_name="reflections")
    reflection_text = models.TextField(help_text="Student 3-line answer in Roman Urdu")
    submitted_at = models.DateTimeField(auto_now_add=True)

    class Meta:
        ordering = ["-submitted_at"]
        unique_together = [("student", "story")]

    def __str__(self):
        return f"{self.student.code} - {self.story}"


class ReflectionScore(models.Model):
    """Teacher SOLO-taxonomy judgement of one reflection.

    SOLO levels (Biggs and Collis):
      0 Prestructural, 1 Unistructural, 2 Multistructural,
      3 Relational, 4 Extended abstract.
    """
    SOLO_CHOICES = [
        (0, "Prestructural - missing the point"),
        (1, "Unistructural - one relevant idea"),
        (2, "Multistructural - several ideas, unconnected"),
        (3, "Relational - ideas connected, explains why"),
        (4, "Extended abstract - generalizes"),
    ]
    reflection = models.OneToOneField(
        StoryReflection, on_delete=models.CASCADE, related_name="score")
    solo_level = models.PositiveSmallIntegerField(choices=SOLO_CHOICES)
    teacher_comment = models.TextField(blank=True)
    scored_at = models.DateTimeField(auto_now_add=True)

    class Meta:
        ordering = ["-scored_at"]

    def __str__(self):
        return f"{self.reflection.student.code} - SOLO {self.solo_level}"


# ---------- Student Profile (Section 10 - cumulative record) ----------


class StudentProfile(models.Model):
    """One cumulative record per student. Container, not content.

    Standards: Saskatchewan Ministry of Education Cumulative Record;
    Iowa Code r. 281-12.3(4); WIA-EDU-010 v2.0 privacy-first design.
    Append-only. Summary regenerated, never edited.
    """
    student = models.OneToOneField(
        Student, on_delete=models.CASCADE, related_name="profile")
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)

    class Meta:
        ordering = ["student__code"]

    def __str__(self):
        return f"Profile - {self.student.code}"


class ProfileEntry(models.Model):
    """A single dated concrete observation. Append-only.

    Standards: anecdotal record methodology (ERIC ED135174);
    BPS three-domain model; Date, student, observer mandatory.
    """
    DOMAIN_CHOICES = [
        ("BIO", "Biological - health, sleep, nutrition, energy"),
        ("PSY", "Psychological - emotion, confidence, motivation"),
        ("SOC", "Social - family, peers, home support, attendance pattern"),
        ("ACA", "Academic - learning, understanding, skill gaps"),
        ("CHR", "Character - grit, perseverance, honesty, self-discipline"),
    ]
    SOURCE_CHOICES = [
        ("T", "Teacher"),
        ("P", "Parent"),
        ("S", "Student"),
    ]
    profile = models.ForeignKey(
        StudentProfile, on_delete=models.CASCADE, related_name="entries")
    entry_date = models.DateField(db_index=True)
    domain = models.CharField(max_length=3, choices=DOMAIN_CHOICES, db_index=True)
    observed = models.TextField(
        help_text="What was seen or heard. No interpretation. No adjectives.")
    context = models.TextField(blank=True,
        help_text="Where, when, with whom.")
    source = models.CharField(max_length=1, choices=SOURCE_CHOICES, default="T")
    confidence = models.PositiveSmallIntegerField(default=3,
        help_text="1 low - 5 high. How sure are you of this observation?")
    parent_visible = models.BooleanField(default=False)
    shareable_with_student = models.BooleanField(default=False)
    created_at = models.DateTimeField(auto_now_add=True)

    class Meta:
        ordering = ["-entry_date", "-created_at"]
        indexes = [models.Index(fields=["profile", "domain", "entry_date"])]

    def __str__(self):
        return f"{self.profile.student.code} - {self.entry_date} - {self.domain}"


class ProfileSummary(models.Model):
    """Regenerated summary of a profile. One row per generation.

    Standard: derived artifact. Never edited by hand.
    The most recent row is what the portal shows.
    """
    profile = models.ForeignKey(
        StudentProfile, on_delete=models.CASCADE, related_name="summaries")
    generated_at = models.DateTimeField(auto_now_add=True)
    entry_count = models.PositiveIntegerField(default=0)
    biological_summary = models.TextField(blank=True)
    psychological_summary = models.TextField(blank=True)
    social_summary = models.TextField(blank=True)
    academic_summary = models.TextField(blank=True)
    character_summary = models.TextField(blank=True)
    action_plan = models.TextField(blank=True)

    class Meta:
        ordering = ["-generated_at"]

    def __str__(self):
        return f"Summary - {self.profile.student.code} - {self.generated_at:%Y-%m-%d}"


# ---------- Non-teaching days (holidays, vacations, exam weeks) ----------


class NonTeachingDay(models.Model):
    """A date on which no test is expected.

    Standards: ISO 8601-2 (dates as intervals); MTSS fidelity
    (attendance expectations are distinct from actual attendance);
    DBI (trend calculation must skip measurement gaps).
    """
    REASON_CHOICES = [
        ("HOL", "Holiday"),
        ("VAC", "Vacation / long break"),
        ("EXM", "Board / school exam week"),
        ("SICK", "Teacher unwell / unable to teach"),
        ("EMG", "Emergency / unplanned"),
        ("OTH", "Other"),
    ]
    date = models.DateField(unique=True, db_index=True)
    reason = models.CharField(max_length=4, choices=REASON_CHOICES, default="HOL")
    note = models.CharField(max_length=200, blank=True)
    created_at = models.DateTimeField(auto_now_add=True)

    class Meta:
        ordering = ["-date"]

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


# ---------- System state (hibernation) ----------


class SystemState(models.Model):
    """Singleton: current operating mode of the system.

    Standards: NIST SP 800-53 CM-2 (baseline config);
    AWS Well-Architected COST06 (idle resource management);
    ITIL 4 (service lifecycle states).
    """
    STATE_CHOICES = [
        ("ACTIVE", "Active - normal operation"),
        ("DORMANT", "Dormant - no work expected, cron idle"),
        ("MAINT", "Maintenance - teacher-set, cron idle"),
    ]
    state = models.CharField(max_length=8, choices=STATE_CHOICES, default="ACTIVE")
    last_activity = models.DateTimeField(null=True, blank=True,
        help_text="Last ingest, teacher command, or reflection.")
    dormant_since = models.DateTimeField(null=True, blank=True)
    idle_threshold_days = models.PositiveSmallIntegerField(default=14)
    note = models.CharField(max_length=200, blank=True)
    updated_at = models.DateTimeField(auto_now=True)

    class Meta:
        verbose_name_plural = "System state"

    def __str__(self):
        return "SystemState: " + self.state

    @classmethod
    def get(cls):
        obj, _ = cls.objects.get_or_create(pk=1)
        return obj


# ---------- Correction log (append-only amendment audit) ----------


class CorrectionLog(models.Model):
    """Every change to a Student record or a report field.

    Standards: HL7 FHIR Provenance; GDPR Art. 16 (rectification);
    FERPA 99.20 (amendment of education records);
    ISO 27001 A.8.15 (change logging); append-only.
    """
    KIND_CHOICES = [
        ("DEMO", "Student demographics (name, father, phone, tier, class)"),
        ("REPORT", "Report field correction (score, band, mistakes, reflection)"),
        ("ATTEND", "Attendance correction"),
        ("TASK", "Daily task correction"),
        ("STORY", "Story lecture correction"),
        ("PROFILE", "Student profile entry correction"),
        ("MODEL", "Model paper or model question correction"),
        ("FIREWALL", "KC pipeline firewall event"),
    ]
    kind = models.CharField(max_length=8, choices=KIND_CHOICES, db_index=True)
    target_model = models.CharField(max_length=40)
    target_id = models.PositiveIntegerField(db_index=True)
    student = models.ForeignKey(
        Student, on_delete=models.CASCADE, related_name="corrections",
        null=True, blank=True)
    field_name = models.CharField(max_length=60)
    old_value = models.TextField(blank=True)
    new_value = models.TextField(blank=True)
    reason = models.TextField(help_text="Why this correction was made.")
    actor = models.ForeignKey(
        "auth.User", on_delete=models.SET_NULL, null=True, blank=True,
        related_name="corrections_made",
        help_text="Who made the change. Null = system.")
    actor_label = models.CharField(max_length=60, blank=True,
        help_text="Fallback when actor FK is null, e.g. terminal:teacher")
    created_at = models.DateTimeField(auto_now_add=True, db_index=True)

    class Meta:
        ordering = ["-created_at"]
        indexes = [
            models.Index(fields=["target_model", "target_id"]),
            models.Index(fields=["kind", "created_at"]),
        ]

    def __str__(self):
        return f"{self.kind} {self.target_model}#{self.target_id} {self.field_name}"


# ---------- Model Papers (Q&A source library) ----------


class ModelPaper(models.Model):
    MEDIUM_CHOICES = [("EN", "English"), ("UR", "Urdu / Roman Urdu")]
    code = models.CharField(max_length=30, unique=True, db_index=True)
    subject = models.CharField(max_length=50, db_index=True)
    student_class = models.CharField(max_length=20, blank=True, null=True, db_index=True, help_text='9th, 10th, etc.')
    medium = models.CharField(max_length=2, choices=MEDIUM_CHOICES, default="EN")
    title = models.CharField(max_length=200, blank=True)
    total_questions = models.PositiveSmallIntegerField(default=0)
    source_note = models.CharField(max_length=200, blank=True)
    superseded_at = models.DateTimeField(null=True, blank=True, db_index=True)
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)

    @property
    def display_name(self):
        """Returns the friendly label, or the raw code if empty."""
        return self.display_code or self.code

    class Meta:
        ordering = ["subject", "code"]

    def __str__(self):
        return f"{self.code} - {self.subject}"


import re as _re_slug
from django.utils.text import slugify as _slugify


_SLUG_STOPWORDS = {
    "what", "is", "the", "of", "a", "an", "and", "or", "to", "in", "on",
    "for", "with", "define", "write", "explain", "differentiate", "give",
    "state", "describe", "how", "why", "which", "name", "list", "briefly",
    "brief", "short", "note", "discuss", "compare", "between", "does",
    "do", "are", "was", "were", "be", "been", "being", "with", "from",
    "into", "about", "also", "any", "some", "all", "each", "both",
}


def make_question_slug(question_text, existing_slugs):
    """Return a unique per-paper slug derived from the question text.

    Standards: 1EdTech QTI v3.0.1 (identifier is unique within a test);
    Open edX OEP-68 (Code identifier - semantically descriptive, locally
    scoped); Django slugify convention (append -N on collision).

    Examples:
      "What is a covalent bond? Give example."           -> covalent-bond-1
      "Differentiate between covalent and ionic bond."   -> covalent-ionic-bond-1
      "Define covalent bond."                            -> covalent-bond-2
    """
    text = (question_text or "").strip().lower()
    tokens = _re_slug.findall(r"[a-z0-9]+", text)
    content = [t for t in tokens if t not in _SLUG_STOPWORDS]
    if len(content) < 3:
        content = tokens
    content = content[:5]
    base = _slugify("-".join(content))[:70]
    if not base:
        base = "q"
    n = 1
    while f"{base}-{n}" in existing_slugs:
        n += 1
    return f"{base}-{n}"


class ModelQuestion(models.Model):
    translated_by = models.ForeignKey('auth.User', on_delete=models.SET_NULL, null=True, blank=True, related_name='translations_done', help_text='Which associate translated this')
    translated_at = models.DateTimeField(null=True, blank=True, help_text='When translated')

    translated_question_text = models.TextField(blank=True, null=True, help_text='Roman Urdu translation of question_text')
    translated_model_answer = models.TextField(blank=True, null=True, help_text='Roman Urdu translation of model_answer')

    explanation = models.TextField(blank=True, null=True, help_text='Explanation shown when student answers wrong')
    socratic_hint = models.TextField(blank=True, null=True, help_text='Hint shown when student clicks Need a Hint')

    paper = models.ForeignKey(ModelPaper, on_delete=models.CASCADE, related_name="questions")
    question_index = models.PositiveSmallIntegerField()
    question_text = models.TextField()
    question_slug = models.CharField(
        max_length=80, blank=True, db_index=True,
        help_text="Session 9: unique per paper. Derived from the question text; e.g. covalent-bond-1.",
    )
    model_answer = models.TextField()
    source_ref = models.CharField(max_length=200, blank=True)
    chapter = models.CharField(max_length=200, blank=True, db_index=True)
    marks = models.PositiveSmallIntegerField(default=2)
    kc_code = models.CharField(max_length=30, blank=True, db_index=True)
    kc = models.ForeignKey(
        'KnowledgeComponent',
        to_field='code',
        on_delete=models.PROTECT,
        related_name='questions',
        null=True, blank=True, db_index=True,
    )
    superseded_at = models.DateTimeField(
        null=True, blank=True, db_index=True,
        help_text="Set when a duplicate (same paper+question_text) is superseded. Mark, never delete (Rule 9).",
    )
    newman_focus = models.CharField(max_length=20, blank=True)
    reasoning_chain = models.JSONField(default=list, blank=True)
    socratic_ladder = models.JSONField(default=list, blank=True)
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)
    updated_by = models.ForeignKey('auth.User', null=True, blank=True,
                                   on_delete=models.SET_NULL, related_name='+')

    # Session 22 (C1a): provenance fields for link_provenance record linkage.
    # Standards: Fellegi & Sunter 1969; ISO 8000-110; ISO/IEC 19788-1;
    # ALCOA+ Original; ISO 15489-1:2016 5.4; Rule 9; Rule 10; Rule 28.
    MATCH_STATUS_CHOICES = [
        ('auto',      'Auto-matched (>= 0.90)'),
        ('queue',     'Queued for teacher review (0.70-0.89)'),
        ('unmatched', 'Unmatched (< 0.70)'),
    ]
    match_score = models.DecimalField(
        max_digits=3, decimal_places=2, null=True, blank=True,
        help_text="Fellegi-Sunter match score 0.00-1.00.",
    )
    matched_to = models.ForeignKey(
        'self', null=True, blank=True, on_delete=models.SET_NULL,
        related_name='matched_from',
        help_text="Canonical row this duplicate matched to (Rule 9: never delete).",
    )
    match_status = models.CharField(
        max_length=10, choices=MATCH_STATUS_CHOICES, blank=True, default='',
    )
    needs_teacher_review = models.BooleanField(default=False)
    teacher_reviewed_at = models.DateTimeField(null=True, blank=True)
    teacher_reviewed_by = models.ForeignKey(
        'auth.User', null=True, blank=True, on_delete=models.SET_NULL,
        related_name='+',
    )

    review_status = models.CharField(
        max_length=16,
        choices=[
            ('unreviewed', 'Unreviewed'),
            ('approved', 'Approved'),
            ('rejected', 'Rejected'),
            ('needs_fix', 'Needs fix'),
            ('disputed', 'Disputed'),
        ],
        default='unreviewed',
        db_index=True,
    )
    review_version = models.PositiveIntegerField(default=0)
    reviewed_at = models.DateTimeField(null=True, blank=True)
    reviewed_by = models.ForeignKey(
        'auth.User', null=True, blank=True,
        on_delete=models.SET_NULL, related_name='+',
    )
    review_notes = models.TextField(blank=True, default='')

    key_answer = models.TextField(
        blank=True,
        default='',
        help_text='4-8 word essence of model_answer, for MCQ option display',
    )
    ai_confidence = models.FloatField(
        null=True,
        blank=True,
        help_text='0.0-1.0 confidence of the AI that extracted key_answer',
    )

    class Meta:
        ordering = ["paper", "question_index"]
        unique_together = [("paper", "question_index")]

    def __str__(self):
        return f"{self.paper.code} Q{self.question_index}"

# ---------- Session Security (Section 11) ----------


class SessionEvent(models.Model):
    """One row per login. Tracks concurrent sessions and last-seen.

    Standards: OWASP ASVS 5.0 3.2.3 (session binding);
    NIST SP 800-63B 7.1 (session limits);
    NIST SP 800-207 (Zero Trust re-verification);
    ITIL 4 Incident Management (session kill is a logged action);
    ISO 27701 7.2.8 (proportionate IP logging).
    Retention: 90 days, purged by the daily cron.
    """
    ENDED_REASONS = [
        ("logout", "User logged out"),
        ("takeover", "Killed by concurrent-login rule"),
        ("teacher_kill", "Terminated by teacher"),
        ("expired", "Expired"),
    ]
    user = models.ForeignKey(
        "auth.User", on_delete=models.CASCADE, related_name="session_events",
        db_index=True)
    session_key = models.CharField(max_length=64, blank=True, db_index=True)
    ip = models.GenericIPAddressField(null=True, blank=True)
    user_agent = models.CharField(max_length=300, blank=True)
    country = models.CharField(max_length=2, blank=True)
    asn = models.CharField(max_length=40, blank=True)
    started_at = models.DateTimeField(auto_now_add=True, db_index=True)
    last_seen_at = models.DateTimeField(auto_now=True, db_index=True)
    ended_at = models.DateTimeField(null=True, blank=True)
    ended_reason = models.CharField(max_length=20, choices=ENDED_REASONS, blank=True)
    active = models.BooleanField(default=True, db_index=True)

    class Meta:
        ordering = ["-started_at"]
        indexes = [
            models.Index(fields=["user", "active"]),
            models.Index(fields=["ip"]),
        ]

    def __str__(self):
        return f"{self.user.username} @ {self.ip} ({'active' if self.active else 'ended'})"


class LoginAttempt(models.Model):
    """One row per login attempt, success or failure.

    Standards: OWASP ASVS 5.0 3.2 (authentication logging);
    NIST SP 800-63B 5.2.2 (rate-limit / lockout monitoring);
    ISO 27001 A.8.15 (log of authentication events).
    Retention: 30 days, purged by the daily cron.
    """
    user = models.ForeignKey(
        "auth.User", on_delete=models.SET_NULL, null=True, blank=True,
        related_name="login_attempts")
    username = models.CharField(max_length=150, db_index=True)
    ip = models.GenericIPAddressField(null=True, blank=True)
    user_agent = models.CharField(max_length=300, blank=True)
    success = models.BooleanField(default=False, db_index=True)
    reason = models.CharField(max_length=80, blank=True)
    created_at = models.DateTimeField(auto_now_add=True, db_index=True)

    class Meta:
        ordering = ["-created_at"]
        indexes = [
            models.Index(fields=["username", "created_at"]),
        ]

    def __str__(self):
        return f"{self.username} @ {self.ip} {'OK' if self.success else 'FAIL'}"

# ---------- Knowledge Components (P-A: Q-matrix attributes) ----------


class KnowledgeComponent(models.Model):
    """A concept, skill, or piece of knowledge that a ModelQuestion assesses.

    One KC may be assessed by many ModelQuestion rows. The link is
    ModelQuestion.kc_code -> KnowledgeComponent.code (Q-matrix,
    Tatsuoka 1983; the KC is the "attribute").

    misconceptions and socratic_ladder hold the output of the
    three-AI pipeline (Gemini generate -> ChatGPT validate via cycle
    consistency -> Claude rerank). Each list entry is a dict with
    exactly these keys:
        text              - the statement, Roman Urdu, Latin letters
        source            - which model drafted it (e.g. "gemini")
        confidence        - float 0.0-1.0 from the drafting model
        cycle_consistent  - bool; True if ChatGPT cycle-consistency passed
        validated_by      - which model validated (e.g. "chatgpt")
        teacher_approved  - bool; True only after the G5 gate

    Standards: AERA/APA/NCME 2014 Std 13.7 (a stored value names its
    construct); Tatsuoka 1983 (Q-matrix); Mislevy & Haertel
    (Evidence-Centered Design, student-model knowledge);
    Wiggins & McTighe, Understanding by Design (enduring
    understanding); Bloom's revised taxonomy; MISTAKE framework
    (Ross et al., arXiv 2025, cycle consistency); MiRAGE 2025
    (rerank); Finch-Zk (EMNLP 2025, cross-model validation);
    NIST AI RMF MEASURE 2.6; EU AI Act Article 14 (human oversight);
    ISO/IEC 42001; Django docs "Model field reference" (nullable
    when N/A); ISO 9001 7.5.3 (documented information).
    """

    COGNITIVE_CHOICES = [
        ("REM", "Remember"),
        ("UND", "Understand"),
        ("APP", "Apply"),
        ("ANA", "Analyze"),
        ("EVA", "Evaluate"),
        ("CRE", "Create"),
    ]

    code = models.CharField(
        max_length=30, unique=True, db_index=True,
        help_text="Stable KC identifier. Must match ModelQuestion.kc_code.")
    display_code = models.CharField(
        max_length=100, blank=True, null=True, db_index=True,
        help_text="Friendly label for students (e.g. Biology-Photosynthesis). Real code stays hidden.")
    subject = models.CharField(max_length=50, db_index=True)
    chapter = models.CharField(max_length=200, blank=True, db_index=True)
    title = models.CharField(
        max_length=200,
        help_text="Short human-readable name of the concept.")
    description = models.TextField(
        blank=True,
        help_text="What the KC is, in plain language (Roman Urdu).")
    cognitive_level = models.CharField(
        max_length=3, choices=COGNITIVE_CHOICES, blank=True,
        help_text="Bloom's revised taxonomy level this KC targets.")

    key_terms = models.JSONField(
        default=list, blank=True,
        help_text="Tier-3 vocabulary for this KC. Each entry is a dict "
                  "with keys: term, roman_urdu, definition, example, non_example. "
                  "Standards: Beck/McKeown/Kucan three-tier vocabulary; "
                  "Marzano Six-Step Process; Frayer Model.")
    prerequisite_kcs = models.JSONField(
        default=list, blank=True,
        help_text="List of KC codes that must be mastered before this KC. "
                  "Standards: Gagné Learning Hierarchy; Bloom Revised "
                  "prerequisite rules; Knowledge Space Theory (Falmagne "
                  "et al. 1990); Tatsuoka Q-matrix.")

    misconceptions = models.JSONField(
        default=list, blank=True,
        help_text="Three-AI pipeline output. Each entry is a dict; "
                  "see the class docstring for the exact keys.")
    socratic_ladder = models.JSONField(
        default=list, blank=True,
        help_text="Ordered Socratic prompts (Polya; Sweller). Each "
                  "entry is a dict; see the class docstring.")
    story = models.JSONField(default=list, blank=True)
    resource_links = models.JSONField(
        default=list, blank=True,
        help_text="External learning resources (Section 18). Each entry is a dict with keys kind, label, url. kind in youtube, spotify, pdf, image, whatsapp, other.")

    # --- Story Expert Panel fields (Phase 2) ---
    # --- Pokemon Lore Fields (Shared across all students) ---
    monster_name = models.CharField(max_length=60, blank=True, help_text="Pokemon-style name")
    monster_type = models.CharField(max_length=20, blank=True, choices=[
        ('Fire','Fire'),('Water','Water'),('Grass','Grass'),('Electric','Electric'),
        ('Psychic','Psychic'),('Rock','Rock'),('Ground','Ground'),('Flying','Flying'),
        ('Ice','Ice'),('Steel','Steel'),('Dark','Dark'),('Fairy','Fairy')
    ], help_text="Pokemon elemental type")
    monster_lore = models.JSONField(default=dict, blank=True, help_text="Bilingual lore (en/ur) and battle cry")

    story_status = models.CharField(
        max_length=20, default='EMPTY', db_index=True,
        choices=[
            ('EMPTY', 'Empty'),
            ('DRAFT', 'Draft'),
            ('PANEL_PASSED', 'Panel Passed'),
            ('PANEL_FLAGGED', 'Panel Flagged'),
            ('TEACHER_OVERRIDE', 'Teacher Override'),
        ],
        help_text="Lifecycle state of the story. Student-visible only when PANEL_PASSED or TEACHER_OVERRIDE.")
    story_panel_verdict = models.JSONField(
        default=dict, blank=True,
        help_text="Scores from the 5 local experts. Shape: {passed: bool, average: float, per_expert: {objective, relational, simplicity, productive, thematic}}.")

    ready_for_diagnosis = models.BooleanField(
        default=False, db_index=True,
        help_text="Gate G6. True only after all entries are approved at G5.")

    is_active = models.BooleanField(default=True)
    teacher_approved = models.BooleanField(default=False, db_index=True)
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)
    created_by  = models.ForeignKey('auth.User', null=True, blank=True,
                                     on_delete=models.SET_NULL, related_name='+')
    updated_by  = models.ForeignKey('auth.User', null=True, blank=True,
                                     on_delete=models.SET_NULL, related_name='+')
    validated_at = models.DateTimeField(null=True, blank=True)
    validated_by = models.ForeignKey('auth.User', null=True, blank=True,
                                     on_delete=models.SET_NULL, related_name='+')

    superseded_at = models.DateTimeField(null=True, blank=True, db_index=True)

    @property
    def display_name(self):
        """Returns the friendly label, or the raw code if empty."""
        return self.display_code or self.code

    class Meta:
        ordering = ["subject", "code"]
        indexes = [
            models.Index(fields=["subject", "chapter"]),
        ]

    def __str__(self):
        return f"{self.code} - {self.title}"


class LectureRequest(models.Model):
    # ON-DEMAND LECTURE REQUEST (Section 15.9 line 3286; Section 18.1).
    # Student flags a KC they still do not understand after the Socratic
    # ladder. Teacher attaches external resource links (YouTube/Spotify/
    # PDF/image/WhatsApp). Links only; no files hosted on the site.
    # Standards: Wiggins and McTighe 2005; Hattie and Timperley 2007;
    # EU AI Act Art.14; ISO 27701 7.2.8; WCAG 2.2 AA.

    STATUS_CHOICES = [
        ("OPEN", "Open"),
        ("RESOLVED", "Resolved"),
    ]

    student = models.ForeignKey(
        Student, on_delete=models.CASCADE, related_name="lecture_requests")
    kc = models.ForeignKey(
        KnowledgeComponent, on_delete=models.CASCADE, related_name="lecture_requests")
    note = models.TextField(blank=True)
    status = models.CharField(
        max_length=10, choices=STATUS_CHOICES, default="OPEN", db_index=True)
    created_at = models.DateTimeField(auto_now_add=True)
    resolved_at = models.DateTimeField(null=True, blank=True)
    resolved_by = models.ForeignKey(
        "auth.User", on_delete=models.SET_NULL, null=True, blank=True,
        related_name="lecture_requests_resolved")

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

    def __str__(self):
        return f"LectureRequest({self.student.code}, {self.kc.code}, {self.status})"


class PeerPair(models.Model):
    # PEER TUTORING (Section 15.9 line 3287; Section 18.2).
    # Reciprocal, teacher-assigned. NO private student-to-student
    # messaging. NO public profiles. NO ranking. Teacher supervises.
    # Standards: Vygotsky 1978 ZPD; Hattie 2009/2023; Johnson and Johnson
    # 1989; Zhang et al. 2025; Romero et al. 2025; Heller and Fantuzzo
    # 1993; CASEL; MTSS/NCII; UNICEF 2021; UK ICO AADC 2021; ISO/IEC
    # 27701 7.2.8.

    tutor = models.ForeignKey(
        Student, on_delete=models.CASCADE, related_name="peer_pairs_as_tutor")
    tutee = models.ForeignKey(
        Student, on_delete=models.CASCADE, related_name="peer_pairs_as_tutee")
    kc = models.ForeignKey(
        KnowledgeComponent, on_delete=models.CASCADE, related_name="peer_pairs")
    assigned_by = models.ForeignKey(
        "auth.User", on_delete=models.SET_NULL, null=True, blank=True,
        related_name="peer_pairs_assigned")
    assigned_at = models.DateTimeField(auto_now_add=True)
    active = models.BooleanField(default=True, db_index=True)
    notes = models.TextField(blank=True)

    class Meta:
        ordering = ["-assigned_at"]
        indexes = [
            models.Index(fields=["active", "kc"]),
        ]

    def clean(self):
        from django.core.exceptions import ValidationError
        if (self.tutor_id and self.tutee_id
                and self.tutor_id == self.tutee_id):
            raise ValidationError(
                "tutor and tutee must be different students.")

    def __str__(self):
        return f"PeerPair({self.tutor.code} -> {self.tutee.code}, {self.kc.code})"



class WorkflowState(models.Model):
    """Server-side progress for a checkout-style teacher workflow.

    One row per (user, workflow_key). Tracks which step the teacher
    reached, which steps are complete, and any payload the steps need
    to carry forward (e.g. the paper code, the generated prompt).

    Standards: AppMaster save-and-resume patterns (server-side state);
    Adobe Experience Cloud multi-step guidance (survives refresh and
    back-button); Nielsen NN - visibility of system status; WCAG 2.2
    SC 2.4.8 (Location); Rule 10 (one canonical state per workflow).
    """
    WORKFLOW_CHOICES = [
        ("student_paper_check", "Student paper check karein"),
        ("new_paper_ingest", "Naya paper system mein daalein"),
        ("concept_build", "Concept tayyar karein"),
        ("weekly_reflection", "Hafta-war reflection"),
        ("monthly_cards", "Mahine ka report"),
    ]

    user = models.ForeignKey(
        "auth.User", on_delete=models.CASCADE,
        related_name="workflow_states",
        help_text="Teacher who owns this draft.",
    )
    workflow_key = models.CharField(max_length=40, choices=WORKFLOW_CHOICES, db_index=True)
    current_step = models.PositiveSmallIntegerField(default=1)
    completed_steps = models.JSONField(default=list, blank=True,
        help_text="List of step numbers the user has finished.")
    total_steps = models.PositiveSmallIntegerField(default=5)
    payload = models.JSONField(default=dict, blank=True,
        help_text="Per-workflow data carried between steps.")
    is_completed = models.BooleanField(default=False, db_index=True)
    started_at = models.DateTimeField(auto_now_add=True)
    last_activity = models.DateTimeField(auto_now=True, db_index=True)

    class Meta:
        unique_together = [("user", "workflow_key")]
        ordering = ["-last_activity"]
        indexes = [
            models.Index(fields=["user", "is_completed"]),
        ]

    def progress_line(self):
        done = len(self.completed_steps or [])
        return f"{done} / {self.total_steps} mukammal"

    def __str__(self):
        return f"WorkflowState({self.user_id}, {self.workflow_key}, step {self.current_step}/{self.total_steps})"



class ReasoningStep(models.Model):
    """Four-step reasoning progress for one (student, exam).

    Session 8. Persists the student's path through Sweller's completion
    strategy: study the worked example, complete the faded solution,
    rewrite the full answer, submit for teacher review. Gated so the
    student cannot skip; state survives refresh and device change.

    Standards: Sweller et al. (2011) completion strategy / fading;
    Hattie & Timperley (2007) 'where to next'; GOV.UK Task List
    (one task per row, status shown); Nielsen NN - visibility of
    system status; WCAG 2.2 SC 2.4.8 (Location); OWASP ASVS 4.3.1
    (auth) and 5.1.3 (input validation); Rule 10 (one canonical
    state row per student-exam pair).
    """
    student = models.ForeignKey(
        Student, on_delete=models.CASCADE,
        related_name="reasoning_steps", db_index=True,
    )
    exam = models.ForeignKey(
        "Exam", on_delete=models.CASCADE,
        related_name="reasoning_steps", db_index=True,
    )
    current_step = models.PositiveSmallIntegerField(default=1)
    completed_steps = models.JSONField(default=list, blank=True,
        help_text="List of step numbers the student has finished.")
    faded_answers = models.JSONField(default=dict, blank=True,
        help_text="Answers to the faded-solution gaps, keyed by blank index.")
    rewritten_answer = models.TextField(blank=True,
        help_text="Student's rewritten full answer (Step 3).")
    submitted_at = models.DateTimeField(null=True, blank=True,
        help_text="When the student submitted for teacher review (Step 4).")
    teacher_feedback = models.TextField(blank=True)
    teacher_reviewed_at = models.DateTimeField(null=True, blank=True)
    started_at = models.DateTimeField(auto_now_add=True)
    last_activity = models.DateTimeField(auto_now=True, db_index=True)

    class Meta:
        unique_together = [("student", "exam")]
        ordering = ["-last_activity"]
        indexes = [
            models.Index(fields=["student", "current_step"]),
            models.Index(fields=["submitted_at"]),
        ]

    def progress_line(self):
        done = len(self.completed_steps or [])
        return f"{done} / 4 mukammal"

    def is_complete(self):
        return len(self.completed_steps or []) >= 4

    def __str__(self):
        return f"ReasoningStep({self.student.code}, exam {self.exam_id}, step {self.current_step}/4)"


# ---------------------------------------------------------------------------
# RPS - Retrieval Practice Scheduler (migration 0023)
# Design: design/RPS-DESIGN-v1.1.md
# Standards: Leitner 1972; SM-2 (Wozniak 1987); FSRS 2022-24;
#   Keller 1968 PSI; Bloom 1968; Guskey 2007; MTSS/DBI (NCII);
#   Sweller (cognitive load); AERA/APA/NCME 2014 Std 1.0, 13.7;
#   Rule 10 (isolated writers: rps_sync sole writer for RPS tables;
#            ingest_reports untouched, still sole writer of Exam/Submission).
# ---------------------------------------------------------------------------


class RPSItem(models.Model):
    """One question on one student's retrieval queue.

    Created by seed_rps_items. Updated by rps_sync (post-ingest).
    Never updated by any other path (Rule 10).
    """
    MASTERY_CHOICES = [
        ("LEARNING", "Learning"),
        ("REVIEWING", "Reviewing"),
        ("GRADUATED", "Graduated"),
    ]

    student = models.ForeignKey(
        Student, on_delete=models.CASCADE, related_name="rps_items",
    )
    kc_code = models.CharField(max_length=30, blank=True, db_index=True)
    model_question = models.ForeignKey(
        ModelQuestion, on_delete=models.CASCADE, related_name="rps_items",
    )
    first_seen_at = models.DateTimeField(auto_now_add=True)
    last_attempted_at = models.DateTimeField(null=True, blank=True)
    next_due_at = models.DateField(db_index=True)
    current_interval_days = models.PositiveSmallIntegerField(default=1)
    current_ease = models.FloatField(default=2.5)
    consecutive_correct = models.PositiveSmallIntegerField(default=0)
    lapsed_count = models.PositiveSmallIntegerField(default=0)
    mastery_state = models.CharField(
        max_length=12, choices=MASTERY_CHOICES, default="LEARNING", db_index=True,
    )
    mastery_probability = models.FloatField(default=0.3, help_text="BKT mastery probability [0.0-1.0]")
    mastery_attempts = models.PositiveSmallIntegerField(default=0, help_text="Failed mastery attempts")
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)

    class Meta:
        unique_together = [("student", "model_question")]
        indexes = [
            models.Index(fields=["student", "next_due_at"]),
            models.Index(fields=["student", "mastery_state"]),
        ]

    def __str__(self):
        return f"{self.student.code} | Q{self.model_question_id} | due {self.next_due_at} | {self.mastery_state}"


class RPSAttempt(models.Model):
    """Append-only log of one retrieval attempt.

    Written ONLY by rps_sync, which reads Exam + Submission rows that were
    written by the existing ingest_reports pipeline. Rule 10.
    """
    RESPONSE_KINDS = [
        ("PAPER_TEST", "Paper test (ingested)"),
        ("TYPED", "Typed answer (reserved)"),
        ("SELF_REPORT", "Self-report (reserved)"),
        ("MCQ", "MCQ (reserved)"),
        ("ORAL_TEACHER", "Teacher-oral (reserved)"),
    ]
    OUTCOMES = [
        ("CORRECT", "Correct"),
        ("PARTIAL", "Partial"),
        ("WRONG", "Wrong"),
        ("SKIPPED", "Skipped"),
    ]
    SOURCES = [
        ("INGEST_PIPELINE", "Ingest pipeline"),
        ("TEACHER_PORTAL", "Teacher portal"),
    ]

    item = models.ForeignKey(
        RPSItem, on_delete=models.CASCADE, related_name="attempts",
    )
    attempted_at = models.DateTimeField(db_index=True)
    latency_ms = models.PositiveIntegerField(null=True, blank=True)
    response_kind = models.CharField(
        max_length=16, choices=RESPONSE_KINDS, default="PAPER_TEST",
    )
    outcome = models.CharField(max_length=8, choices=OUTCOMES)
    source = models.CharField(
        max_length=16, choices=SOURCES, default="INGEST_PIPELINE",
    )
    exam = models.ForeignKey(
        Exam, on_delete=models.SET_NULL, null=True, blank=True,
        related_name="rps_attempts",
    )
    submission = models.ForeignKey(
        Submission, on_delete=models.SET_NULL, null=True, blank=True,
        related_name="rps_attempts",
    )
    note = models.TextField(blank=True)
    reported_at = models.DateTimeField(auto_now_add=True)

    class Meta:
        indexes = [
            models.Index(fields=["item", "attempted_at"]),
            models.Index(fields=["outcome"]),
        ]

    def __str__(self):
        return f"{self.item_id} | {self.outcome} | {self.attempted_at:%Y-%m-%d}"


class RPSSchedule(models.Model):
    """Per-student daily slice produced by rps_select.

    One row per (student, day). Idempotent: rps_select re-runs update the
    same row rather than duplicating.
    """
    student = models.ForeignKey(
        Student, on_delete=models.CASCADE, related_name="rps_schedules",
    )
    day = models.DateField(db_index=True)
    cap_items = models.PositiveSmallIntegerField()
    produced_count = models.PositiveSmallIntegerField(default=0)
    item_ids = models.JSONField(default=list, blank=True)
    produced_at = models.DateTimeField(auto_now_add=True)

    class Meta:
        unique_together = [("student", "day")]
        indexes = [models.Index(fields=["day"])]

    def __str__(self):
        return f"{self.student.code} | {self.day} | {self.produced_count}/{self.cap_items}"


# ---------------------------------------------------------------------------
# Student Task Queue - migration 0025 (PROP-2026-10-07-STUDENT-TASK-QUEUE v3.1)
# Standards: Womack & Jones Lean Thinking; Fowler Feature Toggles (2017);
#   ITIL 4 Release Management; Rule 10 (dispatch -> canonical writer);
#   Rule 11 (prompt served from disk); Rule H (KC content teacher_approved=False);
#   ISO 21500:2021 4.3.3; ISO 27001 A.8.15; GOV.UK Task List; WCAG 2.2 AA.
# NOTE: exclusivity of (task_type, task_ref) is enforced at ALLOCATION time in
# application code, not by a DB constraint: MySQL does not support partial /
# conditional unique indexes. Logged in proposal v3.1 Section 5.
# ---------------------------------------------------------------------------


class StudentTask(models.Model):

    def save(self, *args, **kwargs):
        # Turn B (2026-10-11) - invariant guard (Rule 10 + Rule 9)
        # A StudentTask with a student owner must have unassigned_at=None.
        # Standards: Saltzer & Schroeder 1975 (fail-safe default);
        #   ISO 9001 8.5.1 (controlled production); Kleppmann DDIA Ch.7.
        _auto_cleared = False
        if self.student_id is not None and self.unassigned_at is not None:
            self.unassigned_at = None
            _auto_cleared = True
            _uf = kwargs.get("update_fields")
            if _uf is not None:
                _uf = set(_uf) | {"unassigned_at"}
                kwargs["update_fields"] = list(_uf)
        super().save(*args, **kwargs)
        if _auto_cleared:
            try:
                from django.db import transaction as _tx
                _pk = self.pk
                def _log():
                    try:
                        PortalFeatureLog.objects.create(
                            key="auto_unassign_clear." + str(_pk),
                            old_enabled=False, new_enabled=True,
                            changed_by=None,
                            note=("auto-cleared unassigned_at because "
                                  "student was set (Turn B guard)"),
                        )
                    except Exception:
                        pass
                _tx.on_commit(_log)
            except Exception:
                pass

    TASK_TYPES = [
        ("BOOK_INGEST", "Book page-pair ingest"),
        ("KC_MISCONCEPTION", "KC misconception generation"),
        ("KC_DISCOVERY", "KC discovery (propose new KCs for subject)"),
        ("KC_TAG", "KC tagging"),
        ("KC_SOCRATIC_LADDER", "KC socratic ladder"),
        ("GLOSSARY", "Glossary entries"),
        ("STORY", "Story lecture"),
        # Phase 4 additions (2026-10-08): handwriting + reading modules
        ("HANDWRITING_EN", "Handwriting practice (English)"),
        ("HANDWRITING_UR", "Handwriting practice (Urdu Nastaliq)"),
        ("READING_EN", "Reading probe (English)"),
        ("READING_UR", "Reading probe (Urdu)"),
        ("DATA_CORRECTION", "KC data correction (P13)"),
    ]
    CATEGORY_CHOICES = [
        ("ACADEMIC", "Academic (student's own learning)"),
        ("MANAGEMENT", "Management (system upkeep)"),
        ("SUPPORT", "Support (optional help)"),
    ]
    STATUS = [
        ("ASSIGNED", "Assigned"),
        ("IN_PROGRESS", "In progress"),
        ("DONE", "Done"),
        ("SKIPPED", "Skipped"),
    ]
    INGEST = [
        ("PENDING", "Pending"),
        ("OK", "OK"),
        ("FAILED", "Failed"),
    ]

    student = models.ForeignKey(
        Student, on_delete=models.CASCADE, related_name="student_tasks",
    )
    task_type = models.CharField(max_length=24, choices=TASK_TYPES, db_index=True)
    # Rule 14: ACADEMIC rolls into student progress; MANAGEMENT/SUPPORT do not.
    category = models.CharField(
        max_length=12, choices=CATEGORY_CHOICES,
        default="ACADEMIC", db_index=True,
        help_text=("ACADEMIC: student's own learning. "
                   "MANAGEMENT: system upkeep. SUPPORT: optional help."))
    task_ref = models.CharField(max_length=120, db_index=True)
    status = models.CharField(
        max_length=12, choices=STATUS, default="ASSIGNED", db_index=True,
    )
    assigned_at = models.DateTimeField(auto_now_add=True)
    assigned_by = models.ForeignKey(
        "auth.User", on_delete=models.SET_NULL, null=True, blank=True,
        related_name="student_tasks_assigned",
    )
    completed_at = models.DateTimeField(null=True, blank=True)
    json_payload = models.JSONField(null=True, blank=True)
    ingest_status = models.CharField(
        max_length=10, choices=INGEST, default="PENDING", db_index=True,
    )
    ingest_error = models.TextField(blank=True)
    idempotency_key = models.CharField(max_length=64, blank=True, db_index=True)
    shared_group = models.CharField(max_length=120, blank=True, db_index=True)
    unassigned_at = models.DateTimeField(null=True, blank=True)
    pipeline = models.ForeignKey(
        "TaskPipeline", on_delete=models.SET_NULL, null=True, blank=True,
        related_name="stage_tasks",
    )
    pipeline_stage = models.PositiveSmallIntegerField(null=True, blank=True)
    current_step = models.PositiveSmallIntegerField(default=1)
    steps_completed = models.JSONField(default=list, blank=True)
    last_step_at = models.DateTimeField(null=True, blank=True)
    last_heartbeat_at = models.DateTimeField(null=True, blank=True)
    paused_at = models.DateTimeField(null=True, blank=True, db_index=True,
        help_text="Keller PSI self-pacing: student paused this task to work on another.")
    notes = models.TextField(blank=True)

    class Meta:
        indexes = [
            models.Index(fields=["student", "status"]),
            models.Index(fields=["task_type", "status"]),
        ]

    def __str__(self):
        return f"{self.student.code} | {self.task_type} | {self.task_ref} | {self.status}"


class PortalFeature(models.Model):
    ALLOCATION = [
        ("EXCLUSIVE", "Exclusive - one student per task_ref"),
        ("SHARED", "Shared - duplicates allowed"),
    ]
    key = models.CharField(max_length=80, unique=True)
    enabled = models.BooleanField(default=False)
    message = models.TextField(blank=True)
    allocation_policy = models.CharField(
        max_length=12, choices=ALLOCATION, default="EXCLUSIVE",
    )
    updated_at = models.DateTimeField(auto_now=True)
    updated_by = models.ForeignKey(
        "auth.User", on_delete=models.SET_NULL, null=True, blank=True,
        related_name="portal_features_updated",
    )

    def __str__(self):
        return f"{self.key}={'ON' if self.enabled else 'OFF'}"


class PortalFeatureLog(models.Model):
    key = models.CharField(max_length=80, db_index=True)
    old_enabled = models.BooleanField()
    new_enabled = models.BooleanField()
    changed_at = models.DateTimeField(auto_now_add=True, db_index=True)
    changed_by = models.ForeignKey(
        "auth.User", on_delete=models.SET_NULL, null=True, blank=True,
        related_name="portal_feature_logs",
    )
    note = models.TextField(blank=True)

    def __str__(self):
        return f"{self.key}: {self.old_enabled}->{self.new_enabled} @ {self.changed_at}"


class StudentTaskGate(models.Model):
    """Per-student override of the global task-portal toggle.

    Semantics (Fowler per-user override):
      - no row          -> follow PortalFeature global
      - enabled=True    -> force OPEN for this student
      - enabled=False   -> force CLOSED; show message (Roman Urdu)
    Rule 10: view-layer gate only; no writer touched.
    """
    student = models.OneToOneField(
        Student, on_delete=models.CASCADE, related_name="task_gate",
    )
    enabled = models.BooleanField(default=False)
    hidden = models.BooleanField(default=False, db_index=True)
    message = models.TextField(
        blank=True,
        default="Mere Kaam abhi band hai. Teacher se poochein.",
    )
    updated_at = models.DateTimeField(auto_now=True)
    updated_by = models.ForeignKey(
        "auth.User", on_delete=models.SET_NULL, null=True, blank=True,
        related_name="student_task_gate_updates",
    )

    def __str__(self):
        return self.student.code + (" ON" if self.enabled else " OFF")


# ---------------------------------------------------------------------------
# TaskPipeline - 9-stage per-paper pipeline (migration 0029)
# Standards: Cooper Stage-Gate (1990); GOV.UK Task List; Material Design
# Stepper; Rule 10 (writers untouched); Rule 11 (per-stage prompts);
# Rule H (no merged diagnostic stages); WCAG 2.2 SC 2.4.8.
# ---------------------------------------------------------------------------
class TaskPipeline(models.Model):
    STAGE_CHOICES = [
        (1, "Photo + prompt -> Gemini"),
        (2, "Ingest to bank"),
        (3, "KC tag"),
        (4, "KC misconception"),
        (5, "KC socratic ladder"),
        (6, "G5 teacher approval"),
        (7, "G6 prompt freeze"),
        (8, "Glossary"),
        (9, "Story lecture"),
    ]
    STATUS = [
        ("ACTIVE", "Active"),
        ("BLOCKED_ON_TEACHER", "Blocked on teacher"),
        ("DONE", "Done"),
    ]
    paper_code = models.CharField(max_length=60, unique=True, db_index=True)
    current_stage = models.PositiveSmallIntegerField(default=1)
    stages_completed = models.JSONField(default=list, blank=True)
    status = models.CharField(
        max_length=24, choices=STATUS, default="ACTIVE", db_index=True,
    )
    owner_student = models.ForeignKey(
        Student, on_delete=models.SET_NULL, null=True, blank=True,
        related_name="task_pipelines_owned",
    )
    started_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)

    released_at = models.DateTimeField(null=True, blank=True)
    released_by = models.ForeignKey('auth.User', null=True, blank=True,
                                     on_delete=models.SET_NULL, related_name='+')
    release_verdict = models.JSONField(null=True, blank=True)

    class Meta:
        indexes = [models.Index(fields=["status", "current_stage"])]

    @property
    def progress_pct(self):
        """Pipeline progress percent (capped at 100).

        Denominator is the FULL stage count (11). Historical code used 9,
        which allowed values above 100 for pipelines that completed all 11
        stages. Standards: NIST SP 800-53 SI-10; AERA Std 1.0;
        ISO 8000-61; Rule 4; Rule 26.
        """
        done = len(self.stages_completed or [])
        pct = int(round(done / 11 * 100)) if done else 0
        return min(pct, 100)

    def __str__(self):
        return f"{self.paper_code} | stage {self.current_stage}/9 | {self.status}"

    # Turn 2 (2026-10-10) - pipeline isolation (optimistic concurrency)
    # Standards: Kleppmann DDIA Ch. 7; Rule 28; Azure Bulkhead Pattern
    version = models.PositiveIntegerField(
        default=0,
        help_text='Optimistic concurrency version for pipeline isolation',
    )



class ParentMessage(models.Model):
    """Bounded one-to-one teacher-parent message about a specific student.

    Standards: WCAG 2.2 SC 3.3.1 (clear limits), ISO 9241-110 (self-descriptiveness),
    ISO 27001 A.5.3 (segregation), ISO 27701 7.2.8 (purpose limitation),
    Rule 15 (500-char cap, no attachments, append-only).
    """
    student = models.ForeignKey(
        Student, on_delete=models.CASCADE, related_name="parent_messages",
    )
    from_user = models.ForeignKey(
        "auth.User", on_delete=models.CASCADE, related_name="parent_messages_sent",
    )
    to_user = models.ForeignKey(
        "auth.User", on_delete=models.CASCADE, related_name="parent_messages_received",
    )
    body = models.CharField(max_length=500)
    created_at = models.DateTimeField(auto_now_add=True, db_index=True)
    read_at = models.DateTimeField(null=True, blank=True)
    thread_key = models.CharField(max_length=80, db_index=True)

    class Meta:
        ordering = ["-created_at"]
        indexes = [models.Index(fields=["thread_key", "-created_at"])]

    def __str__(self):
        return self.thread_key + " | " + self.from_user.username + " -> " + self.to_user.username


class SupportTicket(models.Model):
    """Structured support ticket (Rule 16; ISO 10002:2018; ITIL 4 Service Desk)."""
    CATEGORIES = [("ACADEMIC","Academic"),("TECHNICAL","Technical"),
                  ("ADMIN","Administrative"),("FEEDBACK","Feedback")]
    PRIORITIES = [("URGENT","Urgent"),("HIGH","High"),
                  ("MEDIUM","Medium"),("LOW","Low")]
    STATUSES = [("OPEN","Open"),("IN_PROGRESS","In progress"),
                ("WAITING","Waiting on user"),("RESOLVED","Resolved"),
                ("CLOSED","Closed")]

    student = models.ForeignKey(
        Student, on_delete=models.CASCADE, related_name="support_tickets")
    opened_by = models.ForeignKey(
        "auth.User", on_delete=models.CASCADE, related_name="support_tickets_opened")
    assignee = models.ForeignKey(
        "auth.User", on_delete=models.SET_NULL, null=True, blank=True,
        related_name="support_tickets_assigned")
    category = models.CharField(max_length=12, choices=CATEGORIES, db_index=True)
    priority = models.CharField(max_length=8, choices=PRIORITIES, db_index=True)
    status = models.CharField(max_length=12, choices=STATUSES,
                              default="OPEN", db_index=True)
    subject = models.CharField(max_length=120)
    body = models.TextField()
    attachment = models.ImageField(upload_to="support/", null=True, blank=True)
    created_at = models.DateTimeField(auto_now_add=True, db_index=True)
    updated_at = models.DateTimeField(auto_now=True)
    resolved_at = models.DateTimeField(null=True, blank=True)
    resolved_by = models.ForeignKey(
        "auth.User", on_delete=models.SET_NULL, null=True, blank=True,
        related_name="support_tickets_resolved")
    closed_at = models.DateTimeField(null=True, blank=True)
    sla_due = models.DateTimeField(null=True, blank=True)

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

    def __str__(self):
        return "T" + str(self.id) + " " + self.student.code + " " + self.category + " " + self.status


class TicketComment(models.Model):
    ticket = models.ForeignKey(
        SupportTicket, on_delete=models.CASCADE, related_name="comments")
    author = models.ForeignKey(
        "auth.User", on_delete=models.CASCADE, related_name="ticket_comments")
    body = models.TextField()
    attachment = models.ImageField(upload_to="support/", null=True, blank=True)
    is_internal = models.BooleanField(default=False)
    created_at = models.DateTimeField(auto_now_add=True, db_index=True)

    class Meta:
        ordering = ["created_at"]
        indexes = [models.Index(fields=["ticket","created_at"])]

    def __str__(self):
        return "T" + str(self.ticket_id) + "c" + str(self.id)



class FeatureAccess(models.Model):
    """Per-user feature control (Rule 17; NIST AC-6; ISO 27001 A.5.15/A.5.18;
    OWASP A01:2021; Fowler Permission Toggle).

    Precedence: DENY > ALLOW > DEFAULT. Server-side evaluation only.
    All decisions logged to PortalFeatureLog.
    """
    STATES = [
        ("ALLOW", "Allow"),
        ("DENY", "Deny"),
        ("DEFAULT", "Default - follow role/global"),
    ]

    user = models.ForeignKey(
        "auth.User", on_delete=models.CASCADE, related_name="feature_access",
    )
    feature_key = models.CharField(max_length=80, db_index=True)
    state = models.CharField(max_length=8, choices=STATES, db_index=True)
    reason = models.CharField(max_length=200)
    granted_by = models.ForeignKey(
        "auth.User", on_delete=models.SET_NULL, null=True, blank=True,
        related_name="feature_access_granted",
    )
    granted_at = models.DateTimeField(auto_now_add=True)
    expires_at = models.DateTimeField(null=True, blank=True, db_index=True)

    class Meta:
        unique_together = [("user", "feature_key")]
        indexes = [
            models.Index(fields=["user", "feature_key"]),
            models.Index(fields=["state", "expires_at"]),
        ]

    def __str__(self):
        return self.user.username + " | " + self.feature_key + " = " + self.state


class KillSwitchRegistry(models.Model):
    """Registry of every kill switch (Rule 18; Google SRE Workbook Ch. 14;
    AWS Well-Architected; ISO/IEC 42001 A.9.5).

    Quarterly test is mandatory. Untested switch = debt.
    """
    kill_switch_key = models.CharField(max_length=80, unique=True)
    owner = models.ForeignKey(
        "auth.User", on_delete=models.SET_NULL, null=True, blank=True,
        related_name="kill_switches_owned",
    )
    blast_radius = models.TextField(blank=True,
        help_text="Who is affected when this switch is OFF.")
    rollback_time_minutes = models.PositiveSmallIntegerField(default=5)
    last_tested_at = models.DateTimeField(null=True, blank=True, db_index=True)
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)

    class Meta:
        indexes = [models.Index(fields=["last_tested_at"])]

    def __str__(self):
        return self.kill_switch_key

# ---------------------------------------------------------------------------
# Health Centre models (added 2026-10-08, Phase 2)
# Design: design/HEALTH-CENTRE-POLICY-v1.0.1.md
# Standards: Amazon AHR / AHA; EWS ABC; PBIS; CASEL; Goss v. Lopez 1975;
#   FERPA; EU AI Act Art. 14; ISO 27001 A.8.15; ISO 42001 s7.5;
#   Rule 9 (append-only); Rule 12 (Mizan); Rule 13 (HITL); Rule 14.
# ---------------------------------------------------------------------------

class HealthPolicy(models.Model):
    """Catalogue of health policies (violations and credits).

    Standards: Amazon AHR (tiered impact); EWS ABC; PBIS (positive
    reinforcement 4:1 ratio); ISO 9001:2015 8.5.1 (controlled
    production); Rule 4 (cite the standard); Rule 12 (Mizan gates).
    """
    KIND_CHOICES = [
        ("VIOLATION", "Violation"),
        ("CREDIT", "Credit"),
    ]
    CATEGORY_CHOICES = [
        ("ATTENDANCE", "Attendance"),
        ("TASK", "Daily task"),
        ("BEHAVIOUR", "Behaviour"),
        ("CHARACTER", "Character"),
        ("HANDWRITING", "Handwriting"),
        ("READING", "Reading"),
        ("ACADEMIC", "Academic performance"),
    ]
    SEVERITY_CHOICES = [
        ("LOW", "Low"),
        ("MEDIUM", "Medium"),
        ("HIGH", "High"),
        ("CRITICAL", "Critical"),
    ]

    code = models.CharField(
        max_length=40, unique=True,
        help_text="Policy ID, e.g. POL-TSK-001 or CR-HW-IMP-2")
    kind = models.CharField(max_length=10, choices=KIND_CHOICES, db_index=True)
    category = models.CharField(
        max_length=20, choices=CATEGORY_CHOICES, db_index=True)
    severity = models.CharField(
        max_length=10, choices=SEVERITY_CHOICES, db_index=True)
    points = models.IntegerField(
        help_text="Negative for violations, positive for credits.")
    title_ur = models.CharField(
        max_length=200,
        help_text="Roman Urdu short title shown to student/parent.")
    description_ur = models.TextField(
        blank=True,
        help_text="Roman Urdu description of the policy.")
    standard_cited = models.CharField(
        max_length=300, blank=True,
        help_text="Named standard that grounds this policy.")
    is_active = models.BooleanField(default=True, db_index=True)
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)

    class Meta:
        ordering = ["code"]
        indexes = [
            models.Index(fields=["kind", "is_active"]),
            models.Index(fields=["category", "is_active"]),
        ]

    def __str__(self):
        return self.code + " (" + self.kind + " " + str(self.points) + ")"


class HealthEvent(models.Model):
    """A single health event: a policy applied to a student.

    APPEND-ONLY. Corrections are new events, not edits.
    Standards: Amazon AHR; ISO 27001 A.8.15 (logging);
    Rule 9 (log first, delete second); Rule 12 (Mizan).
    """
    KIND_CHOICES = [
        ("VIOLATION", "Violation"),
        ("CREDIT", "Credit"),
    ]
    SOURCE_CHOICES = [
        ("AUTO", "Automatic (Algorithm)"),
        ("TEACHER", "Teacher"),
        ("PARENT", "Parent"),
        ("STUDENT", "Student"),
        ("SYSTEM", "System"),
    ]

    student = models.ForeignKey(
        "Student", on_delete=models.CASCADE,
        related_name="health_events")
    policy = models.ForeignKey(
        HealthPolicy, on_delete=models.PROTECT,
        null=True, blank=True, related_name="events")
    kind = models.CharField(
        max_length=10, choices=KIND_CHOICES, db_index=True)
    points = models.IntegerField(
        help_text="Snapshot of policy.points at event time.")
    reason = models.TextField(
        help_text="Roman Urdu, plain language.")
    evidence = models.JSONField(default=dict, blank=True)
    source = models.CharField(
        max_length=10, choices=SOURCE_CHOICES,
        default="AUTO", db_index=True)
    actor = models.ForeignKey(
        "auth.User", on_delete=models.SET_NULL,
        null=True, blank=True, related_name="health_events_authored")
    overridden_by = models.ForeignKey(
        "auth.User", on_delete=models.SET_NULL,
        null=True, blank=True, related_name="health_events_overridden")
    overridden_at = models.DateTimeField(null=True, blank=True)
    override_reason = models.TextField(blank=True)
    created_at = models.DateTimeField(auto_now_add=True, db_index=True)

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

    def __str__(self):
        return (self.student.code + " " + self.kind + " "
                + str(self.points))

class HealthScore(models.Model):
    """Current health score for one student (one row per student).

    Model: Amazon AHR 0-1000 with four bands.
    Recomputed from HealthEvent stream. Never edited by hand.
    Standards: Amazon AHR bands; ISO 9001:2015 8.5.1;
    Rule 12 (Mizan computes); Rule 13 (HITL override on events,
    not on the aggregate).
    """
    BAND_CHOICES = [
        ("HEALTHY", "Healthy (700-1000)"),
        ("WATCH", "Watch (400-699)"),
        ("AT_RISK", "At Risk (200-399)"),
        ("CRITICAL", "Critical (0-199)"),
    ]

    student = models.OneToOneField(
        "Student", on_delete=models.CASCADE,
        related_name="health_score")
    score = models.IntegerField(default=500, db_index=True)
    band = models.CharField(max_length=20, default="NEUTRAL", choices=[
        ("STRUCK_OFF", "Struck off (0-99)"),
        ("ACTION", "Formal action (100-199)"),
        ("CRITICAL", "Critical (200-299)"),
        ("AT_RISK", "At risk (300-399)"),
        ("WATCH", "Watch (400-499)"),
        ("NEUTRAL", "Neutral / start (500-599)"),
        ("IMPROVING", "Improving (600-699)"),
        ("GOOD", "Good (700-799)"),
        ("EXCELLENT", "Excellent (800-899)"),
        ("EXEMPLARY", "Exemplary (900-1000)"),
    ])
    event_count = models.PositiveIntegerField(default=0)
    last_event_at = models.DateTimeField(null=True, blank=True)
    last_recompute_at = models.DateTimeField(auto_now=True)
    # Green Shield (AHA analogue) — 6 weeks at Healthy band
    green_shield_since = models.DateTimeField(null=True, blank=True)
    red_flag_since = models.DateTimeField(null=True, blank=True)
    algorithm_version = models.CharField(max_length=40, default="Mizan_Algorithm_v1.0")
    academic_pct = models.DecimalField(max_digits=5, decimal_places=2, null=True, blank=True)
    presence_pct = models.DecimalField(max_digits=5, decimal_places=2, null=True, blank=True)
    ontime_pct = models.DecimalField(max_digits=5, decimal_places=2, null=True, blank=True)
    kirdar_delta = models.IntegerField(default=0)
    credit_sum = models.IntegerField(default=0)
    penalty_sum = models.IntegerField(default=0)
    penalties = models.IntegerField(default=0)
    last_recompute_algorithm = models.CharField(max_length=40, blank=True)
    # When the current band was entered (used by badge_check for the 3-day hold).
    band_since = models.DateTimeField(null=True, blank=True)

    class Meta:
        indexes = [
            models.Index(fields=["band", "-score"]),
        ]


    @property
    def star_count(self):
        if self.score >= 900: return 5
        if self.score >= 800: return 4
        if self.score >= 700: return 3
        if self.score >= 600: return 2
        if self.score >= 500: return 1
        return 0
    def __str__(self):
        return (self.student.code + " " + str(self.score)
                + " (" + self.band + ")")


class BehaviourIncident(models.Model):
    """A single behavioural incident. APPEND-ONLY.

    Due process (Goss v. Lopez 1975): High/Critical incidents
    require the student to have a right to respond, and the
    teacher to review the response before any consequence.
    Standards: PBIS Tier 2; CASEL; Goss v. Lopez;
    Rule 9 (append-only); Rule 13 (HITL); Rule 14 (SUPPORT category).
    """
    SEVERITY_CHOICES = [
        ("LOW", "Low"),
        ("MEDIUM", "Medium"),
        ("HIGH", "High"),
        ("CRITICAL", "Critical"),
    ]
    STATUS_CHOICES = [
        ("OPEN", "Open"),
        ("STUDENT_RESPONDED", "Student responded"),
        ("REVIEWED", "Reviewed by teacher"),
        ("CLOSED", "Closed"),
        ("APPEALED", "Appealed"),
    ]

    student = models.ForeignKey(
        "Student", on_delete=models.CASCADE,
        related_name="behaviour_incidents")
    severity = models.CharField(
        max_length=10, choices=SEVERITY_CHOICES, db_index=True)
    category = models.CharField(
        max_length=40,
        help_text="E.g. RESPECT_TEACHER, RESPECT_PEER, HONESTY.")
    observed = models.TextField(
        help_text="Concrete event. What was seen or heard.")
    context = models.TextField(
        blank=True,
        help_text="Where / when / with whom.")
    source_label = models.CharField(
        max_length=80,
        help_text="Named source (teacher, staff, peer). Anonymous not allowed.")
    student_response = models.TextField(
        blank=True,
        help_text="Student's side (due process, Goss v. Lopez).")
    student_responded_at = models.DateTimeField(null=True, blank=True)
    teacher_review = models.TextField(blank=True)
    teacher_reviewed_by = models.ForeignKey(
        "auth.User", on_delete=models.SET_NULL,
        null=True, blank=True,
        related_name="behaviour_incidents_reviewed")
    teacher_reviewed_at = models.DateTimeField(null=True, blank=True)
    status = models.CharField(
        max_length=20, choices=STATUS_CHOICES,
        default="OPEN", db_index=True)
    parent_notified_at = models.DateTimeField(null=True, blank=True)
    health_event = models.ForeignKey(
        HealthEvent, on_delete=models.SET_NULL,
        null=True, blank=True,
        related_name="behaviour_incidents")
    created_at = models.DateTimeField(auto_now_add=True, db_index=True)
    updated_at = models.DateTimeField(auto_now=True)

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

    def __str__(self):
        return (self.student.code + " " + self.severity + " "
                + self.category)

class CreditEvent(models.Model):
    """A single credit event. APPEND-ONLY.

    Same shape as HealthEvent but separated for reporting clarity
    (Rule 14: ACADEMIC rolls into progress; character/behaviour do not).
    Standards: Amazon AHR positive activity; PBIS 4:1 ratio;
    ISO 27001 A.8.15; Rule 9.
    """
    student = models.ForeignKey(
        "Student", on_delete=models.CASCADE,
        related_name="credit_events")
    code = models.CharField(
        max_length=60,
        help_text="E.g. TASK_ON_TIME, HW_IMPROVEMENT, BOOK_FINISHED.")
    points = models.IntegerField()
    reason = models.TextField(blank=True)
    evidence = models.JSONField(default=dict, blank=True)
    source = models.CharField(
        max_length=10, default="AUTO", db_index=True)
    actor = models.ForeignKey(
        "auth.User", on_delete=models.SET_NULL,
        null=True, blank=True, related_name="credit_events_authored")
    health_event = models.ForeignKey(
        HealthEvent, on_delete=models.SET_NULL,
        null=True, blank=True, related_name="credits")
    created_at = models.DateTimeField(auto_now_add=True, db_index=True)

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

    def __str__(self):
        return self.student.code + " " + self.code + " +" + str(self.points)


class Badge(models.Model):
    """Catalogue of badge definitions.

    Standards: 1EdTech Open Badges 3.0; W3C Verifiable Credentials
    Data Model 2.0; Dai/Xu & Xing 2025 (Challenge + Mystery);
    Scilit 2026 (no gamipulation).
    """
    TIER_CHOICES = [
        (1, "Tier 1 - Micro"),
        (2, "Tier 2 - Weekly"),
        (3, "Tier 3 - Skill"),
        (4, "Tier 4 - Milestone"),
    ]

    code = models.CharField(
        max_length=60, unique=True,
        help_text="E.g. HW-HERO, BOOK-FIN, IRON-STREAK.")
    title_ur = models.CharField(max_length=120)
    description_ur = models.CharField(max_length=200, blank=True)
    tier = models.PositiveSmallIntegerField(
        choices=TIER_CHOICES, default=1, db_index=True)
    trigger = models.JSONField(
        default=dict, blank=True,
        help_text="Machine-checkable criteria (e.g. {event: TASK_ON_TIME, count: 7}).")
    health_points = models.PositiveSmallIntegerField(
        default=0,
        help_text=("Visual only (DEF-006 fix). Underlying events carry the "
                   "points via HealthPolicy; badge award must not double-count."))
    icon_svg = models.TextField(
        blank=True,
        help_text="Inline SVG (WCAG 2.2 AA contrast).")
    is_active = models.BooleanField(default=True, db_index=True)
    created_at = models.DateTimeField(auto_now_add=True)

    class Meta:
        ordering = ["tier", "code"]

    def __str__(self):
        return self.code + " (" + self.title_ur + ")"


class BadgeAward(models.Model):
    """A badge earned by a student. APPEND-ONLY; never revoked for
    punishment (Scilit 2026 gamipulation rules).

    Standards: Open Badges 3.0 (verifiable); W3C VC 2.0;
    Rule 9; Rule 13 (Algorithm awards, teacher may override).
    """
    student = models.ForeignKey(
        "Student", on_delete=models.CASCADE,
        related_name="badges")
    badge = models.ForeignKey(
        Badge, on_delete=models.PROTECT, related_name="awards")
    trigger_data = models.JSONField(
        default=dict, blank=True,
        help_text="Evidence that fired the trigger.")
    awarded_by = models.ForeignKey(
        "auth.User", on_delete=models.SET_NULL,
        null=True, blank=True, related_name="badges_awarded")
    awarded_at = models.DateTimeField(auto_now_add=True, db_index=True)
    # Open Badges 3.0 verifiable credential ID (ULID or UUID)
    credential_id = models.CharField(max_length=64, blank=True, db_index=True)

    class Meta:
        ordering = ["-awarded_at"]
        indexes = [
            models.Index(fields=["student", "-awarded_at"]),
            models.Index(fields=["badge", "-awarded_at"]),
        ]

    def __str__(self):
        return self.student.code + " -> " + self.badge.code

class Quest(models.Model):
    """A quest wraps one StudentTask into a multi-step reasoning path.

    Design: design/GAMIFICATION-SPEC-v1.0.md
    Purpose: complete the assigned task by breaking it into small
    steps (Sweller CLT chunking; Polya 4-phase).
    Standards: Sweller CLT; Polya 1945; Dai/Xu & Xing 2025;
    Rule 10 (one canonical writer per task); IN-16/IN-17.
    """
    STATUS_CHOICES = [
        ("ACTIVE", "Active"),
        ("COMPLETED", "Completed"),
        ("ABANDONED", "Abandoned (student exited)"),
        ("RESET", "Reset by teacher"),
    ]

    student = models.ForeignKey(
        "Student", on_delete=models.CASCADE, related_name="quests")
    student_task = models.OneToOneField(
        "StudentTask", on_delete=models.CASCADE,
        related_name="quest")
    status = models.CharField(
        max_length=10, choices=STATUS_CHOICES,
        default="ACTIVE", db_index=True)
    total_steps = models.PositiveSmallIntegerField(default=4)
    started_at = models.DateTimeField(auto_now_add=True)
    completed_at = models.DateTimeField(null=True, blank=True)
    last_activity_at = models.DateTimeField(
        auto_now=True, db_index=True)

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

    def __str__(self):
        return "Quest#" + str(self.id) + " " + self.student.code


class QuestStep(models.Model):
    """A single step within a quest. Completion is per-student
    and deterministic (no randomness, no timers).

    Standards: ISO 9241-110 (self-descriptiveness); WCAG 2.2 AA
    (progress bar with aria); Scilit 2026 (no artificial urgency);
    IN-22 (exit route on every screen).
    """
    quest = models.ForeignKey(
        Quest, on_delete=models.CASCADE, related_name="steps")
    step_index = models.PositiveSmallIntegerField()
    title_ur = models.CharField(max_length=200)
    instruction_ur = models.CharField(max_length=400, blank=True)
    input_type = models.CharField(
        max_length=20,
        default="BUTTON",
        help_text="BUTTON | PASTE | TEXT | PHOTO | CONFIRM.")
    done_condition = models.JSONField(
        default=dict, blank=True,
        help_text="Machine-checkable completion criteria.")
    completed = models.BooleanField(default=False, db_index=True)
    completed_at = models.DateTimeField(null=True, blank=True)
    completed_by = models.ForeignKey(
        "auth.User", on_delete=models.SET_NULL,
        null=True, blank=True, related_name="quest_steps_completed")
    created_at = models.DateTimeField(auto_now_add=True)

    class Meta:
        ordering = ["quest", "step_index"]
        unique_together = [("quest", "step_index")]
        indexes = [
            models.Index(fields=["quest", "completed"]),
        ]

    def __str__(self):
        return ("Quest#" + str(self.quest_id) + " step "
                + str(self.step_index) + " " + self.title_ur)


class Reinstatement(models.Model):
    """Reinstatement case for a suspended or critical-health student.

    Procedure: design/HEALTH-CENTRE-POLICY-v1.0.1.md s4.
    Standards: Amazon Plan of Action; Goss v. Lopez 1975 (due process);
    COSO P3 (four-eyes); EU AI Act Art. 14 (HITL); FERPA (parent rights);
    Rule 9; Rule 13.
    """
    STATUS_CHOICES = [
        ("DRAFT", "Draft (student filling)"),
        ("SUBMITTED", "Submitted for review"),
        ("APPROVED", "Approved by teacher"),
        ("MODIFIED", "Approved with modifications"),
        ("REJECTED", "Rejected by teacher"),
        ("IN_PROGRESS", "Recovery contract running"),
        ("CLEARED", "Cleared — reinstated"),
        ("FAILED", "Failed — escalated"),
    ]

    student = models.ForeignKey(
        "Student", on_delete=models.CASCADE,
        related_name="reinstatements")
    status = models.CharField(
        max_length=15, choices=STATUS_CHOICES,
        default="DRAFT", db_index=True)
    trigger_reason = models.TextField(
        help_text="What caused the suspension (Roman Urdu).")
    trigger_health_score = models.IntegerField(
        help_text="Score at trigger time (0-1000).")
    # Parent apology (IN-20)
    parent_apology_ur = models.CharField(
        max_length=300, blank=True,
        help_text="Parent apology, Roman Urdu, max 300 chars.")
    parent_name = models.CharField(max_length=200, blank=True)
    parent_confirmed_at = models.DateTimeField(null=True, blank=True)
    # Student action plan (Amazon POA)
    root_cause_ur = models.TextField(blank=True)
    corrective_actions = models.JSONField(
        default=list, blank=True,
        help_text="List of 3 corrective steps.")
    preventive_measures = models.JSONField(
        default=list, blank=True,
        help_text="List of 3 preventive steps.")
    # Teacher review (HITL)
    reviewed_by = models.ForeignKey(
        "auth.User", on_delete=models.SET_NULL,
        null=True, blank=True, related_name="reinstatements_reviewed")
    reviewed_at = models.DateTimeField(null=True, blank=True)
    review_notes = models.TextField(blank=True)
    # Recovery contract
    contract_starts_at = models.DateTimeField(null=True, blank=True)
    contract_ends_at = models.DateTimeField(null=True, blank=True)
    contract_extension_count = models.PositiveSmallIntegerField(default=0)
    deposit_kind = models.CharField(
        max_length=40, blank=True,
        help_text="PEER_TUTORING_HOURS | EXTRA_PRACTICE_SETS. Never money.")
    deposit_amount = models.PositiveSmallIntegerField(default=0)
    deposit_released_at = models.DateTimeField(null=True, blank=True)
    created_at = models.DateTimeField(auto_now_add=True, db_index=True)
    updated_at = models.DateTimeField(auto_now=True)

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

    def __str__(self):
        return ("Reinstatement#" + str(self.id) + " "
                + self.student.code + " " + self.status)

# ---------------------------------------------------------------------------
# SkillAssessment (Phase 4.1a, 2026-10-08)
# Design: design/HANDWRITING-SPEC-v1.0.md; design/READING-SPEC-v1.0.md
# Standards: DASH-2 (Pearson 2024); IEEE Access 2024 (Urdu Nastaliq);
#   Hasbrouck & Tindal 2017 (ORF WCPM); NAEP 2026 (comprehension);
#   AERA/APA/NCME 2014 Std 1.0 (construct naming);
#   ISO 27001 A.8.15 (append-only); Rule 9; Rule 10; Rule 12.
# ---------------------------------------------------------------------------
class SkillAssessment(models.Model):
    """Periodic skill assessment (handwriting EN/UR; reading EN/UR).

    APPEND-ONLY: corrections are new rows, not edits.
    One row per assessment session per student.
    """
    SKILL_CHOICES = [
        ("HANDWRITING_EN", "Handwriting English (DASH-2)"),
        ("HANDWRITING_UR", "Handwriting Urdu (Nastaliq)"),
        ("READING_EN", "Reading English (ORF + NAEP)"),
        ("READING_UR", "Reading Urdu"),
    ]
    BAND_CHOICES = [
        ("EXCELLENT", "Excellent"),
        ("GOOD", "Good"),
        ("FAIR", "Fair"),
        ("BELOW_AVG", "Below Average"),
        ("CRITICAL", "Critical"),
    ]

    student = models.ForeignKey(
        "Student", on_delete=models.CASCADE,
        related_name="skill_assessments")
    skill_type = models.CharField(
        max_length=20, choices=SKILL_CHOICES, db_index=True)
    assessed_at = models.DateTimeField(db_index=True)
    assessed_by = models.ForeignKey(
        "auth.User", on_delete=models.SET_NULL,
        null=True, blank=True, related_name="skill_assessments_made")
    # Raw measurements (per-skill shape documented in design docs)
    score_data = models.JSONField(
        default=dict,
        help_text=("Per-skill structured scores. E.g. handwriting: "
                   "{criteria: {legibility: 2, ...}, total: 12}. "
                   "Reading: {wpm: 130, percentile: 45, comprehension: "
                   "{locate: 2, integrate: 1, analyze: 1, use: 1}}."))
    band = models.CharField(
        max_length=15, choices=BAND_CHOICES, db_index=True)
    notes_ur = models.TextField(
        blank=True,
        help_text="Roman Urdu notes for student + parent.")
    next_assessment_at = models.DateTimeField(
        null=True, blank=True, db_index=True,
        help_text="When the next assessment is due (weekly HW / monthly RD).")
    health_event = models.ForeignKey(
        HealthEvent, on_delete=models.SET_NULL,
        null=True, blank=True, related_name="skill_assessments")
    created_at = models.DateTimeField(auto_now_add=True, db_index=True)

    class Meta:
        ordering = ["-assessed_at"]
        indexes = [
            models.Index(fields=["student", "skill_type", "-assessed_at"]),
            models.Index(fields=["skill_type", "band"]),
            models.Index(fields=["next_assessment_at"]),
        ]

    def __str__(self):
        return (self.student.code + " " + self.skill_type
                + " = " + self.band + " (" + str(self.assessed_at.date()) + ")")

# ---------------------------------------------------------------------------
# Phase 7.6 — Configurable Health Centre (migration 0040+)
# Design: design/ADMIN-CONSOLE-SPEC-v1.0.md
# Standards: OMG DMN 1.4; ASVS V6.3 + V7.5.3; NIST SP 800-63B AAL2;
#   ISO 27001 A.5.3 + A.8.32; NIST OSCAL (policy-as-code);
#   ISO 9241-110; AERA Std 1.0; Rule 4; Rule 14; Rule 17; Rule 18.
# ---------------------------------------------------------------------------

class ConfigMetric(models.Model):
    """Admin-configurable metric (one row per metric).

    Replaces the read-only HealthPolicy catalogue with a UI-editable one.
    Every metric carries its construct name, direction of "better", and
    the standard that grounds it (AERA Std 1.0).
    """
    CATEGORY_CHOICES = [
        ("ATTENDANCE", "Attendance"),
        ("TASK", "Daily task"),
        ("BEHAVIOUR", "Behaviour"),
        ("CHARACTER", "Character"),
        ("HANDWRITING", "Handwriting"),
        ("READING", "Reading"),
        ("ACADEMIC", "Academic"),
    ]
    KIND_CHOICES = [
        ("VIOLATION", "Violation"),
        ("CREDIT", "Credit"),
    ]
    SEVERITY_CHOICES = [
        ("LOW", "Low"), ("MEDIUM", "Medium"),
        ("HIGH", "High"), ("CRITICAL", "Critical"),
    ]
    DIRECTION_CHOICES = [
        ("BETTER_LOWER", "Better when lower (e.g. DASH-2)"),
        ("BETTER_HIGHER", "Better when higher (e.g. WCPM)"),
        ("NEUTRAL", "Neutral (count)"),
    ]
    STRICTNESS_CHOICES = [
        ("STRICT", "Strict (fires immediately)"),
        ("FLEXIBLE", "Flexible (grace window)"),
        ("ADVISORY", "Advisory (no deduction)"),
    ]

    code = models.CharField(max_length=40, unique=True,
                            help_text="Stable ID, e.g. POL-TSK-001")
    title_ur = models.CharField(max_length=200)
    category = models.CharField(max_length=20, choices=CATEGORY_CHOICES,
                                db_index=True)
    kind = models.CharField(max_length=10, choices=KIND_CHOICES,
                            db_index=True)
    severity = models.CharField(max_length=10, choices=SEVERITY_CHOICES,
                                db_index=True)
    points = models.IntegerField(
        help_text="Negative for violations, positive for credits.")
    direction = models.CharField(max_length=15, choices=DIRECTION_CHOICES,
                                 default="NEUTRAL")
    threshold_expr = models.CharField(
        max_length=200, blank=True,
        help_text="Safe grammar: LHS OP RHS (see spec s5).")
    strictness = models.CharField(max_length=10, choices=STRICTNESS_CHOICES,
                                  default="STRICT", db_index=True)
    grace_days = models.PositiveSmallIntegerField(
        default=7,
        help_text="Grace window for FLEXIBLE strictness (days).")
    standard_cited = models.CharField(
        max_length=300,
        help_text="Named standard grounding this metric. Required (AERA 1.0).")
    evidence_range = models.JSONField(
        default=dict, blank=True,
        help_text="Permitted value range by the cited standard.")
    override_reason = models.TextField(
        blank=True,
        help_text="Required only when threshold falls outside evidence_range.")
    is_active = models.BooleanField(default=True, db_index=True)
    effective_from = models.DateTimeField(null=True, blank=True)
    effective_to = models.DateTimeField(null=True, blank=True)
    version = models.PositiveIntegerField(default=1)
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)

    class Meta:
        ordering = ["category", "code"]
        indexes = [
            models.Index(fields=["category", "is_active"]),
            models.Index(fields=["kind", "is_active"]),
            models.Index(fields=["strictness", "is_active"]),
        ]

    def __str__(self):
        return self.code + " (" + self.kind + " " + str(self.points) + ")"

class ConfigSnapshot(models.Model):
    """A signed, immutable snapshot of the ConfigMetric catalogue.

    Every applied change writes exactly one new snapshot; the previous
    current snapshot is marked is_current=False. Exactly one row is
    is_current=True at any time.
    Standards: NIST OSCAL (policy-as-code); ISO 27001 A.8.32 (change
    management); ISO 27001 A.8.15 (audit trail); Rule 9 (append-only).
    """
    version = models.PositiveIntegerField(unique=True, db_index=True)
    created_at = models.DateTimeField(auto_now_add=True, db_index=True)
    created_by = models.ForeignKey(
        "auth.User", on_delete=models.SET_NULL,
        null=True, blank=True, related_name="config_snapshots_created")
    payload_json = models.JSONField(
        default=dict,
        help_text="Full catalogue of ConfigMetric rows as a JSON dict.")
    sha256 = models.CharField(max_length=64, db_index=True)
    prev_version = models.PositiveIntegerField(null=True, blank=True)
    is_current = models.BooleanField(default=False, db_index=True)
    note = models.TextField(
        blank=True,
        help_text="One-line description of what changed in this snapshot.")

    class Meta:
        ordering = ["-version"]
        indexes = [
            models.Index(fields=["is_current"]),
            models.Index(fields=["version"]),
        ]

    def __str__(self):
        return "v" + str(self.version) + (" (current)" if self.is_current else "")


class ConfigChangeProposal(models.Model):
    """Maker-checker proposal. Every metric change goes through one.

    Lifecycle: PENDING -> APPROVED -> APPLIED (or REJECTED / EXPIRED).
    Cooling-off: between PENDING and APPLIED, a 60-minute minimum
    (single-teacher compensating control per ISO 27001 A.5.3). When a
    second admin exists, approver != maker is enforced.
    Standards: ISO 27001 A.5.3 (dual control) + A.8.32 (change
    management); ITIL 4 Change Enablement; ASVS V7.5.3 (re-auth).
    """
    STATUS_CHOICES = [
        ("PENDING", "Pending approval"),
        ("APPROVED", "Approved (cooling off)"),
        ("APPLIED", "Applied"),
        ("REJECTED", "Rejected"),
        ("EXPIRED", "Expired"),
    ]

    maker = models.ForeignKey(
        "auth.User", on_delete=models.SET_NULL,
        null=True, blank=True, related_name="config_proposals_made")
    created_at = models.DateTimeField(auto_now_add=True, db_index=True)
    reason = models.TextField(
        help_text="Required; one-line why the change is being proposed.")
    before_snapshot = models.JSONField(
        default=dict,
        help_text="Catalogue state before the change.")
    after_snapshot = models.JSONField(
        default=dict,
        help_text="Catalogue state after the change.")
    maker_2fa_id = models.CharField(
        max_length=64, blank=True,
        help_text="TOTP challenge ID that authorised the proposal.")
    status = models.CharField(
        max_length=12, choices=STATUS_CHOICES,
        default="PENDING", db_index=True)
    approver = models.ForeignKey(
        "auth.User", on_delete=models.SET_NULL,
        null=True, blank=True, related_name="config_proposals_approved")
    approved_at = models.DateTimeField(null=True, blank=True)
    approver_2fa_id = models.CharField(max_length=64, blank=True)
    applied_at = models.DateTimeField(null=True, blank=True)
    applied_version = models.PositiveIntegerField(null=True, blank=True)
    rejection_reason = models.TextField(blank=True)
    expires_at = models.DateTimeField(null=True, blank=True, db_index=True)

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

    def __str__(self):
        return ("Proposal#" + str(self.id) + " " + self.status
                + " by " + (self.maker.username if self.maker else "?"))


class UserMFA(models.Model):
    """TOTP enrolment per user (NIST SP 800-63B AAL2).

    Factor: RFC 6238 TOTP via any authenticator app. No SMS, no email
    OTP (OWASP ASVS 5.0 V6.3; email is not a valid factor).
    Recovery codes: single-use, time-limited (ASVS V6.4).
    """
    user = models.OneToOneField(
        "auth.User", on_delete=models.CASCADE, related_name="mfa")
    secret_b32 = models.CharField(
        max_length=64,
        help_text="Base32-encoded TOTP shared secret. Never displayed after enrolment.")
    enrolled_at = models.DateTimeField(auto_now_add=True)
    last_used_at = models.DateTimeField(null=True, blank=True)
    recovery_hashes = models.JSONField(
        default=list, blank=True,
        help_text="List of SHA-256 hashes of single-use recovery codes.")
    is_active = models.BooleanField(default=True, db_index=True)

    class Meta:
        indexes = [models.Index(fields=["is_active"])]

    def __str__(self):
        return self.user.username + " (MFA)"


class TwoFactorChallenge(models.Model):
    """One step-up challenge event. Append-only.

    Standards: ASVS V7.5.3 (re-auth before sensitive ops);
    NIST SP 800-63B AAL2 (15-min admin session);
    ISO 27001 A.8.15 (logging); Rule 9 (append-only).
    """
    RESULT_CHOICES = [
        ("PASS", "Pass"),
        ("FAIL", "Fail"),
        ("EXPIRED", "Expired"),
    ]

    user = models.ForeignKey(
        "auth.User", on_delete=models.CASCADE,
        related_name="mfa_challenges")
    purpose = models.CharField(
        max_length=40,
        help_text="E.g. admin_config_change, admin_console_login.")
    created_at = models.DateTimeField(auto_now_add=True, db_index=True)
    expires_at = models.DateTimeField(db_index=True)
    consumed_at = models.DateTimeField(null=True, blank=True)
    result = models.CharField(
        max_length=10, choices=RESULT_CHOICES,
        default="EXPIRED", db_index=True)
    ip_address = models.GenericIPAddressField(null=True, blank=True)

    class Meta:
        ordering = ["-created_at"]
        indexes = [
            models.Index(fields=["user", "-created_at"]),
            models.Index(fields=["result", "-created_at"]),
        ]

    def __str__(self):
        return ("2FA#" + str(self.id) + " " + self.user.username
                + " " + self.result)



# ============================================================
# ParentAcknowledgement (POP-001 / MIZAN-v3.0)
# ============================================================
class ParentAcknowledgement(models.Model):
    user = models.ForeignKey(
        settings.AUTH_USER_MODEL, on_delete=models.CASCADE,
        related_name="acknowledgements",
    )
    ack_type = models.CharField(max_length=50, db_index=True)
    ack_version = models.CharField(max_length=20)
    passed_at = models.DateTimeField(auto_now_add=True)
    quiz_score = models.PositiveSmallIntegerField(default=0)
    quiz_answers = models.JSONField(default=dict, blank=True)

    class Meta:
        unique_together = (("user", "ack_type", "ack_version"),)
        indexes = [models.Index(fields=["user", "ack_type"])]

    def __str__(self):
        return f"{self.user_id} | {self.ack_type} v{self.ack_version} score={self.quiz_score}"


# ============================================================
# ParentTaskCompletion (Rule 15.2 - anti-fraud voice-note)
# Parent must prove task was done by THEM (not student).
# Requires: voice note >= 5s, live challenge phrase, teacher confirm.
# Standards: ISO 27001 A.5.15, A.8.15; ISO 27701 7.2.8;
#   ISO/IEC 30107-3 (liveness detection best practices);
#   PECA 2016 s.3; Rule 15, Rule 22, Rule 13 (four-eyes);
#   ALCOA+ Contemporaneous.
# ============================================================
class ParentTaskCompletion(models.Model):
    STATUS_CHOICES = [
        ("PENDING", "Pending review"),
        ("CONFIRMED", "Confirmed by teacher"),
        ("REJECTED", "Rejected (fraud suspected)"),
    ]
    student = models.ForeignKey(
        Student, on_delete=models.CASCADE,
        related_name="parent_task_completions",
    )
    task_ref = models.CharField(max_length=80)
    task_type = models.CharField(max_length=30)
    challenge_phrase = models.CharField(max_length=120, blank=True,
        help_text="Random phrase parent must say aloud (anti-pre-record)")
    voice_note = models.FileField(upload_to="parent_voice_notes/%Y/%m/")
    voice_duration_seconds = models.PositiveSmallIntegerField(default=0)
    submitted_at = models.DateTimeField(auto_now_add=True)
    submitted_ip = models.GenericIPAddressField(null=True, blank=True)
    status = models.CharField(max_length=12, choices=STATUS_CHOICES,
                              default="PENDING", db_index=True)
    teacher_confirmed = models.BooleanField(default=False)
    teacher_confirmed_at = models.DateTimeField(null=True, blank=True)
    teacher_confirmed_by = models.ForeignKey(
        settings.AUTH_USER_MODEL, on_delete=models.SET_NULL,
        null=True, blank=True, related_name="confirmed_parent_tasks",
    )
    teacher_note = models.TextField(blank=True)
    fraud_suspected = models.BooleanField(default=False)

    class Meta:
        unique_together = (("student", "task_ref"),)
        indexes = [
            models.Index(fields=["student", "task_ref"]),
            models.Index(fields=["status", "submitted_at"]),
        ]

    def __str__(self):
        return f"{self.student_id} | {self.task_ref} | {self.status}"


# ============================================================
# PolicyViolation (sealed policy breach)
# Types: parent_task_fraud, absent, late, handwriting_fail, other.
# Consequence ladder: 1st -> -25 + warning; 2nd -> strike-off.
# Standards: Rule I, Rule 12, Rule 22; Section 23.13 P-KZM-04;
#   ISO 27001 A.8.15 (append-only).
# ============================================================
class PolicyViolation(models.Model):
    VIOLATION_TYPES = [
        ("parent_task_fraud", "Student completed parent's task / shared parent credentials"),
        ("parent_creds_shared", "Parent credentials shared with student"),
        ("absent_unexcused", "Unexcused absence"),
        ("late", "Late arrival"),
        ("handwriting_fail", "Handwriting drill fail"),
        ("other", "Other"),
    ]
    student = models.ForeignKey(
        Student, on_delete=models.CASCADE,
        related_name="policy_violations",
    )
    violation_type = models.CharField(max_length=30, choices=VIOLATION_TYPES,
                                      db_index=True)
    detected_at = models.DateTimeField(auto_now_add=True)
    detected_by = models.ForeignKey(
        settings.AUTH_USER_MODEL, on_delete=models.SET_NULL,
        null=True, related_name="detected_violations",
    )
    evidence = models.TextField(help_text="What was observed")
    warning_number = models.PositiveSmallIntegerField(
        default=1, help_text="1 = first warning, 2 = strike-off trigger",
    )
    points_deducted = models.SmallIntegerField(default=0)
    strike_off_triggered = models.BooleanField(default=False)
    notes = models.TextField(blank=True)

    class Meta:
        ordering = ["-detected_at"]
        indexes = [
            models.Index(fields=["student", "violation_type"]),
            models.Index(fields=["strike_off_triggered"]),
        ]

    def __str__(self):
        return f"{self.student_id} | {self.violation_type} | warn#{self.warning_number}"


# ============================================================
# StageCompletionRequest (Rule 13 HITL; NIST AC-6; COSO P3)
# Student signals a stage is complete; teacher approves.
# ============================================================
class StageCompletionRequest(models.Model):
    STATUS_CHOICES = [
        ("PENDING", "Pending review"),
        ("APPROVED", "Approved by teacher"),
        ("REJECTED", "Rejected by teacher"),
    ]
    student = models.ForeignKey(
        Student, on_delete=models.CASCADE,
        related_name="stage_completion_requests",
    )
    task_type = models.CharField(max_length=30, db_index=True)
    task_ref_prefix = models.CharField(max_length=80)
    reason = models.TextField()
    status = models.CharField(max_length=12, choices=STATUS_CHOICES,
                              default="PENDING", db_index=True)
    requested_at = models.DateTimeField(auto_now_add=True)
    reviewed_at = models.DateTimeField(null=True, blank=True)
    reviewed_by = models.ForeignKey(
        settings.AUTH_USER_MODEL, on_delete=models.SET_NULL,
        null=True, blank=True, related_name="reviewed_stage_completions",
    )
    teacher_note = models.TextField(blank=True)

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

    def __str__(self):
        return f"{self.student_id} | {self.task_type} | {self.task_ref_prefix} | {self.status}"


class PipelineMembership(models.Model):
    """Turn 14b (2026-10-11) — shared work pool membership.

    Standards: Master/Worker POSA v1; TOGAF 10 shared service centre;
    Rule 25 (per-task owner); design/PIPELINE-SHARED-POOL-v1.0.md.
    """
    pipeline = models.ForeignKey(
        "TaskPipeline", on_delete=models.CASCADE,
        related_name="memberships",
    )
    student = models.ForeignKey(
        "Student", on_delete=models.CASCADE,
        related_name="pipeline_memberships",
    )
    joined_at = models.DateTimeField(auto_now_add=True)

    class Meta:
        unique_together = [("pipeline", "student")]
        indexes = [models.Index(fields=["pipeline", "student"])]

    def __str__(self):
        return f"{self.pipeline.paper_code} <- {self.student.code}"


class TaskClaim(models.Model):
    """Turn 14b (2026-10-11) — append-only claim record.

    Standards: ALCOA+ Original; Kleppmann DDIA Ch.7; MySQL 8.0 15.7.2;
    design/PIPELINE-SHARED-POOL-v1.0.md.
    """
    task = models.OneToOneField(
        "StudentTask", on_delete=models.CASCADE,
        related_name="claim",
    )
    student = models.ForeignKey(
        "Student", on_delete=models.PROTECT,
    )
    claimed_at = models.DateTimeField(auto_now_add=True)
    released_at = models.DateTimeField(null=True, blank=True)

    def __str__(self):
        return f"task {self.task_id} <- {self.student.code}"


# ---------------------------------------------------------------------------
# KC Pipeline Firewall (P14-2)
# Freeze KC pipeline entities + student/subject links by default.
# Design: design/KC-PIPELINE-FIREWALL-v1.0.md
# Standards: ISO/IEC/IEEE 12207 6.4.9; Saltzer & Schroeder 1975 (fail-safe);
#            NIST SP 800-53 AC-6, CM-3, SI-10; ISO 27001 A.5.3, A.5.15, A.8.32;
#            ALCOA+ Original; Rule 9; Rule 24; Rule 25; Rule 28.
# ---------------------------------------------------------------------------


class KcPipelineLock(models.Model):
    """Layer 1 of the KC pipeline firewall.

    Default state = LOCKED. A row may exist to record an unlock window
    (with written reason + duration). Absence of a row means LOCKED.

    scope:
        GLOBAL          - entire pipeline frozen
        ENTITY_TYPE     - one model frozen (all instances)
        ENTITY_INSTANCE - one row frozen
    """

    SCOPE_CHOICES = [
        ("GLOBAL", "Global"),
        ("ENTITY_TYPE", "Entity type"),
        ("ENTITY_INSTANCE", "Entity instance"),
    ]

    scope = models.CharField(max_length=20, choices=SCOPE_CHOICES, db_index=True)
    entity_type = models.CharField(max_length=60, blank=True)
    entity_id = models.PositiveIntegerField(null=True, blank=True)
    locked = models.BooleanField(default=True, db_index=True)
    reason = models.TextField(blank=True)
    unlocked_by = models.ForeignKey(
        "auth.User", null=True, blank=True,
        on_delete=models.SET_NULL, related_name="kc_unlocks"
    )
    unlocked_at = models.DateTimeField(null=True, blank=True)
    re_lock_at = models.DateTimeField(null=True, blank=True, db_index=True)
    created_at = models.DateTimeField(auto_now_add=True)

    class Meta:
        app_label = "exams"
        ordering = ["-created_at"]
        indexes = [
            models.Index(fields=["scope", "entity_type", "entity_id"]),
        ]

    def __str__(self):
        target = self.entity_type or "*"
        if self.entity_id:
            target += ":" + str(self.entity_id)
        state = "LOCKED" if self.locked else "UNLOCKED"
        return target + " " + state


# ---------------------------------------------------------------------------
# KC Data Quality Remediation (P13-1)
# Detects defects (missing / wrong / inconsistent / duplicate / malformed /
# orphan) in KC pipeline entities; tracks correction lifecycle.
# Design: design/KC-DATA-QUALITY-REMEDIATION-v1.0.md
# Standards: ISO 8000-8 5.2-5.5; ISO 8000-61; DAMA-DMBOK2 Ch.13;
#            ALCOA+ Original; Rule 9; Rule 14 (MANAGEMENT category);
#            Rule 28.
# ---------------------------------------------------------------------------


class DataQualityIssue(models.Model):
    SEVERITY_CHOICES = [
        ("BLOCKER", "Blocking downstream work"),
        ("MAJOR", "Affects quality materially"),
        ("MINOR", "Cosmetic / non-blocking"),
    ]
    CLASS_CHOICES = [
        ("MISSING", "Required field is null / blank"),
        ("WRONG", "Semantic check fails"),
        ("INCONSISTENT", "Same construct, conflicting values"),
        ("DUPLICATE", "Same content, multiple rows"),
        ("MALFORMED", "Shape violates schema"),
        ("ORPHAN", "Foreign key points to nothing"),
    ]
    STATUS_CHOICES = [
        ("OPEN", "Detected, not yet assigned"),
        ("TASK_ASSIGNED", "Correction task created"),
        ("IN_PROGRESS", "Student working on it"),
        ("VERIFIED", "Correction verified"),
        ("CLOSED", "Resolved (new row supersedes old)"),
        ("ESCALATED", "Routed to teacher queue"),
    ]

    severity = models.CharField(max_length=10, choices=SEVERITY_CHOICES, db_index=True)
    defect_class = models.CharField(max_length=15, choices=CLASS_CHOICES, db_index=True)
    entity_type = models.CharField(max_length=40, db_index=True)
    entity_id = models.PositiveIntegerField(db_index=True)
    evidence = models.JSONField(default=dict, blank=True,
        help_text="Raw defective content + context for the correction prompt.")
    status = models.CharField(max_length=15, choices=STATUS_CHOICES,
        default="OPEN", db_index=True)
    detected_at = models.DateTimeField(auto_now_add=True, db_index=True)
    detected_by = models.CharField(max_length=60, default="detect_kc_defects")
    resolved_by_task = models.ForeignKey(
        "StudentTask", null=True, blank=True,
        on_delete=models.SET_NULL, related_name="dq_issues")
    superseded_at = models.DateTimeField(null=True, blank=True)
    resolved_at = models.DateTimeField(null=True, blank=True)
    attempt_count = models.PositiveSmallIntegerField(default=0)

    class Meta:
        ordering = ["-detected_at"]
        indexes = [
            models.Index(fields=["entity_type", "entity_id"]),
            models.Index(fields=["status", "severity"]),
        ]

    def __str__(self):
        return f"{self.severity} {self.defect_class} {self.entity_type}#{self.entity_id}"


class StudentNote(models.Model):
    """Private study notes. Facility, not a task (P22 scope)."""
    MEDIUM_CHOICES = [("EN", "English"), ("UR", "Urdu")]
    SOURCE_CHOICES = [
        ("chatgpt", "ChatGPT"), ("gemini", "Gemini"),
        ("claude", "Claude"), ("other", "Other"),
    ]

    student = models.ForeignKey(
        "Student", on_delete=models.PROTECT, related_name="student_notes")
    subject = models.CharField(max_length=20, db_index=True,
        help_text="Subject code e.g. PH-9, CH-9")
    medium = models.CharField(max_length=2, choices=MEDIUM_CHOICES, default="EN")
    chapter = models.CharField(max_length=60, blank=True, db_index=True)
    q_number = models.CharField(max_length=20)
    question = models.TextField()
    command_word = models.CharField(max_length=20, blank=True)
    keywords = models.JSONField(default=list, blank=True,
        help_text="Board keywords the examiner scans for.")
    short_core_answer = models.TextField(
        help_text="3-5 short sentences carrying every keyword.")
    max_marks = models.PositiveSmallIntegerField(null=True, blank=True)
    model_source = models.CharField(max_length=20, choices=SOURCE_CHOICES,
        default="other")
    prompt_version = models.CharField(max_length=20, default="short-core-v1.0")
    needs_teacher_review = models.BooleanField(default=False, db_index=True)
    is_contribution = models.BooleanField(default=False, db_index=True,
        help_text="True if this note was created by contributing a story heal.")
    teacher_reviewed = models.BooleanField(default=False, db_index=True)
    teacher_reviewed_at = models.DateTimeField(null=True, blank=True)
    teacher_reviewed_by = models.ForeignKey(
        settings.AUTH_USER_MODEL, null=True, blank=True,
        on_delete=models.SET_NULL, related_name="notes_reviewed")
    superseded_by = models.ForeignKey(
        "self", null=True, blank=True,
        on_delete=models.SET_NULL, related_name="supersedes_chain")
    created_at = models.DateTimeField(auto_now_add=True, db_index=True)
    updated_at = models.DateTimeField(auto_now=True)

    class Meta:
        ordering = ["-created_at"]
        indexes = [
            models.Index(fields=["student", "subject", "created_at"]),
            models.Index(fields=["student", "subject", "chapter", "q_number"]),
        ]

    def __str__(self):
        return f"{self.student.code} {self.subject} {self.q_number}"


class KCCard(models.Model):
    """FSRS-6 spaced repetition card for a specific student and KC."""
    student = models.ForeignKey('Student', on_delete=models.CASCADE, related_name='kc_cards')
    kc = models.ForeignKey('KnowledgeComponent', on_delete=models.CASCADE, related_name='student_cards')
    difficulty = models.FloatField(default=0.0)
    stability = models.FloatField(default=0.0)
    retrievability = models.FloatField(default=0.0)
    state = models.CharField(max_length=20, default='NEW', choices=[
        ('NEW', 'New'), ('LEARNING', 'Learning'), ('REVIEW', 'Review'),
        ('RELEARNING', 'Relearning'), ('MASTERED', 'Mastered')
    ])
    reps = models.PositiveIntegerField(default=0)
    lapses = models.PositiveIntegerField(default=0)
    last_review_at = models.DateTimeField(null=True, blank=True)
    next_due_at = models.DateTimeField(null=True, blank=True, db_index=True)

    class Meta:
        unique_together = [('student', 'kc')]
        indexes = [models.Index(fields=['student', 'next_due_at'])]

    def __str__(self):
        return f"{self.student.code} - {self.kc} - {self.state}"


class StudentAbility(models.Model):
    student = models.OneToOneField(Student, on_delete=models.CASCADE, related_name="ability")
    current_level = models.FloatField(default=0.5, help_text="0.0 to 1.0 mastery ability")
    updated_at = models.DateTimeField(auto_now=True)

def _trophy_today():
    from django.utils import timezone
    return timezone.localdate()

class DailyQuestionCount(models.Model):
    student = models.ForeignKey(Student, on_delete=models.CASCADE, related_name="daily_counts")
    date = models.DateField(default=_trophy_today)
    assigned_count = models.PositiveIntegerField(default=0)
    completed_count = models.PositiveIntegerField(default=0)
    
    class Meta:
        unique_together = ('student', 'date')

class CatchUpQueue(models.Model):
    student = models.ForeignKey(Student, on_delete=models.CASCADE, related_name="catch_up_queue")
    exam = models.ForeignKey(Exam, on_delete=models.CASCADE, null=True, blank=True)
    added_at = models.DateTimeField(auto_now_add=True)
    is_processed = models.BooleanField(default=False)


class MemorizationLadder(models.Model):
    student = models.ForeignKey(Student, on_delete=models.CASCADE, related_name="memorization_ladders")
    kc = models.ForeignKey('KnowledgeComponent', on_delete=models.CASCADE)
    phase = models.CharField(max_length=20, default='BUILD') # BUILD, CONSOLIDATE, MASTER
    streak = models.PositiveIntegerField(default=0)
    next_review_date = models.DateField(null=True, blank=True)
    is_retired = models.BooleanField(default=False)
    created_at = models.DateTimeField(auto_now_add=True)

    class Meta:
        unique_together = ('student', 'kc')


class StudentStarCommitment(models.Model):
    student = models.ForeignKey(Student, on_delete=models.CASCADE, related_name="star_commitments")
    commitment = models.CharField(max_length=255, help_text="What the student promised to do")
    created_at = models.DateTimeField(auto_now_add=True)
    is_fulfilled = models.BooleanField(default=False)

class RemediationPlan(models.Model):
    student = models.ForeignKey(Student, on_delete=models.CASCADE, related_name="remediation_plans")
    kc = models.ForeignKey('KnowledgeComponent', on_delete=models.CASCADE)
    plan_text = models.TextField(help_text="Diagnostic and prescriptive steps")
    scheduled_date = models.DateField()
    is_completed = models.BooleanField(default=False)
    created_at = models.DateTimeField(auto_now_add=True)

class StudentStreak(models.Model):
    student = models.OneToOneField(Student, on_delete=models.CASCADE, related_name="streak")
    current_streak = models.PositiveIntegerField(default=0)
    longest_streak = models.PositiveIntegerField(default=0)
    last_activity_date = models.DateField(null=True, blank=True)


class LearningEvent(models.Model):
    student = models.ForeignKey(Student, on_delete=models.CASCADE, related_name="learning_events")
    verb = models.CharField(max_length=50) # e.g., 'completed', 'attempted'
    object_type = models.CharField(max_length=50)
    object_id = models.CharField(max_length=100)
    timestamp = models.DateTimeField(auto_now_add=True)
    payload = models.JSONField(default=dict, blank=True)

from .models_audit import PageAudit

from .models_delegation import TaskDelegation
from .models_trophy import TrophyEvent


class QuestionReviewLog(models.Model):
    """Audit trail for every review decision on a question."""
    SOURCE_CHOICES = [
        ('human', 'Human'),
        ('rules', 'Rules'),
        ('similarity', 'Similarity'),
        ('llm', 'LLM'),
        ('ensemble', 'Ensemble'),
    ]
    question = models.ForeignKey(
        ModelQuestion, on_delete=models.CASCADE, related_name='review_log',
    )
    old_status = models.CharField(max_length=16)
    new_status = models.CharField(max_length=16)
    version = models.PositiveIntegerField()
    confidence = models.FloatField(null=True, blank=True)
    source = models.CharField(
        max_length=16, choices=SOURCE_CHOICES, default='human',
    )
    reviewer = models.ForeignKey(
        'auth.User', null=True, blank=True,
        on_delete=models.SET_NULL, related_name='+',
    )
    notes = models.TextField(blank=True, default='')
    created_at = models.DateTimeField(auto_now_add=True)

    class Meta:
        ordering = ['-created_at']
        indexes = [
            models.Index(fields=['question', '-created_at'], name='exams_qrl_q_cr'),
        ]

    def __str__(self):
        return 'Q' + str(self.question_id) + ': ' + self.old_status + '->' + self.new_status


# ============================================================
# PHASE 1: 150-DAY MASTER PIPELINE (2026-10-21)
# Standards: ISO 9001 (Controlled Production), NIST SP 800-63B
# ============================================================

class GlobalStudyConfig(models.Model):
    """Owner-controlled state machine for the 150-day count."""
    is_active = models.BooleanField(default=False)
    current_day = models.PositiveIntegerField(default=1)
    start_date = models.DateField(null=True, blank=True, help_text="Day 1 of the cohort. If set, current_day is computed from this.")
    last_rollover_date = models.DateField(null=True, blank=True)
    updated_by = models.ForeignKey('auth.User', on_delete=models.SET_NULL, null=True, blank=True)
    updated_at = models.DateTimeField(auto_now=True)

    @property
    def computed_day(self):
        """Day 1 = start_date. Returns 0 before start_date."""
        from django.utils import timezone
        from datetime import date as _date
        if not self.start_date:
            return self.current_day
        start = self.start_date
        if isinstance(start, str):
            try:
                start = _date.fromisoformat(start)
            except (ValueError, TypeError):
                return self.current_day
        today = timezone.now().date()
        delta = (today - start).days
        if delta < 0:
            return 0
        return delta + 1

    def __str__(self):
        return f"Day {self.computed_day} ({'Active' if self.is_active else 'Paused'})"
    exam_batch_size = models.PositiveSmallIntegerField(default=1, help_text="Teacher calls N students per batch (1-50)")
    exam_grace_minutes = models.PositiveSmallIntegerField(default=15, help_text="Minutes before auto-skip if student does not start")

class StudentQuestionLock(models.Model):
    """Permanent ledger for 150-day anti-fraud question locking."""
    student = models.ForeignKey(Student, on_delete=models.CASCADE, related_name='question_locks')
    question = models.ForeignKey(ModelQuestion, on_delete=models.CASCADE, related_name='locks')
    locked_at = models.DateTimeField(auto_now_add=True)
    is_active = models.BooleanField(default=True, help_text="Teacher can toggle to unlock")

    class Meta:
        unique_together = ('student', 'question')
        indexes = [models.Index(fields=['student', 'is_active'])]

    def __str__(self):
        return f"{self.student.code} - Q{self.question.id}"

class RetakeTicket(models.Model):
    """Tracks the 3-attempt mastery loop."""
    STATUS_CHOICES = [
        ('FAILED', 'Failed - Awaiting Reassignment'),
        ('ESCALATED', 'Escalated to RemediationPlan'),
        ('MASTERED', 'Mastered')
    ]
    student = models.ForeignKey(Student, on_delete=models.CASCADE, related_name='retake_tickets')
    question = models.ForeignKey(ModelQuestion, on_delete=models.CASCADE)
    attempt_number = models.PositiveSmallIntegerField(default=1)
    status = models.CharField(max_length=20, choices=STATUS_CHOICES, default='FAILED')
    teacher_note = models.TextField(blank=True)
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)

    def __str__(self):
        return f"{self.student.code} - Q{self.question.id} (Attempt {self.attempt_number})"


class StudentDailyCode(models.Model):
    """One code per student per day - supports pre-assignment."""
    student = models.ForeignKey(Student, on_delete=models.CASCADE, related_name="daily_codes")
    date = models.DateField(db_index=True)
    code = models.PositiveSmallIntegerField(default=0)
    per_book_codes = models.JSONField(default=dict, blank=True, help_text="Per-book test codes; two-shift layout {morning:{}, evening:{}}")
    created_at = models.DateTimeField(auto_now_add=True)
    created_by = models.ForeignKey('auth.User', on_delete=models.SET_NULL, null=True, blank=True)

    # Phase B0 — teacher edit + lock controls
    is_locked = models.BooleanField(default=False, db_index=True,
        help_text="When True, student cannot regenerate; teacher controls the code.")
    locked_by = models.ForeignKey('auth.User', on_delete=models.SET_NULL,
        null=True, blank=True, related_name='daily_codes_locked')
    locked_at = models.DateTimeField(null=True, blank=True)
    edited_by = models.ForeignKey('auth.User', on_delete=models.SET_NULL,
        null=True, blank=True, related_name='daily_codes_edited')
    edited_at = models.DateTimeField(null=True, blank=True)

    class Meta:
        unique_together = ('student', 'date')
        ordering = ['-date', 'student__code']

    def __str__(self):
        return f"{self.student.code} - {self.date} - Q{self.code}"


# Auto-generated Engine State Logic

from django.utils import timezone

class EngineState(models.Model):
    is_running = models.BooleanField(default=False)
    last_updated = models.DateTimeField(null=True, blank=True)
    TOTAL_DURATION = 10368000 # 120 Days in seconds
    remaining_seconds = models.FloatField(default=TOTAL_DURATION)
    start_day = models.PositiveIntegerField(default=1)
    has_started = models.BooleanField(default=False)
    start_date = models.DateField(null=True, blank=True, help_text='Calendar date for Day 1')

    def get_current_day(self):
        """Calendar-based day counter. Day 1 = start_date. Ticks at midnight."""
        if not self.has_started:
            return 0
        if not self.start_date:
            return self.start_day or 1
        from django.utils import timezone
        delta = (timezone.localdate() - self.start_date).days
        return max(1, (self.start_day or 1) + delta)

    def save(self, *args, **kwargs):
        now = timezone.now()
        if self.pk:
            old_state = EngineState.objects.get(pk=self.pk)
            if old_state.is_running and old_state.last_updated:
                elapsed = (now - old_state.last_updated).total_seconds()
                self.remaining_seconds = max(0, old_state.remaining_seconds - elapsed)
            elif not old_state.is_running and self.is_running:
                self.last_updated = now
                if not old_state.has_started and not self.start_date:
                    self.start_date = timezone.localdate()
            elif old_state.is_running and not self.is_running:
                self.last_updated = None
        if self.is_running and not self.last_updated:
            self.last_updated = now
        super().save(*args, **kwargs)

    def get_live_remaining(self):
        if self.is_running and self.last_updated:
            elapsed = (timezone.now() - self.last_updated).total_seconds()
            return max(0, self.remaining_seconds - elapsed)
        return self.remaining_seconds


class StudentSwapLog(models.Model):
    """Tracks how many times a student swapped a daily mission question in a day."""
    student = models.ForeignKey(Student, on_delete=models.CASCADE, related_name="swap_logs")
    date = models.DateField(auto_now_add=True, db_index=True)
    count = models.PositiveSmallIntegerField(default=0)

    class Meta:
        unique_together = ('student', 'date')

    def __str__(self):
        return f"{self.student.code} - {self.date} - {self.count} swaps"

from exams.models_rewrite import RewritePrompt  # noqa: F401, E402


# StudentDayMission ledger (archive feature, Phase 1)
from .models_day_mission import StudentDayMission


# Overdue Penalty Ledger (Phase 1)
from .models_overdue_penalty import OverduePenalty

class StoryVersion(models.Model):
    """Stores every iteration of a story for audit and teacher review."""
    kc = models.ForeignKey('KnowledgeComponent', on_delete=models.CASCADE, related_name='story_versions')
    version_number = models.PositiveIntegerField(default=1)
    source = models.CharField(max_length=20, default='PANEL_AI', choices=[('PANEL_AI', 'Panel AI'), ('TEACHER_EDIT', 'Teacher Edit'), ('RULE_BASED', 'Rule Based')])
    story_text = models.TextField()
    panel_verdict = models.JSONField(default=dict, blank=True)
    created_at = models.DateTimeField(auto_now_add=True)
    created_by = models.ForeignKey('auth.User', null=True, blank=True, on_delete=models.SET_NULL, related_name='+')

    class Meta:
        unique_together = [('kc', 'version_number')]
        ordering = ['-version_number']

    def __str__(self):
        return f"{self.kc.code} - v{self.version_number}"


class StudentContribution(models.Model):
    """Logs each AI content contribution made by a student. Once a student has
    at least one row, the compulsory contribution gate is satisfied."""
    student = models.ForeignKey('Student', on_delete=models.CASCADE, related_name='contributions')
    kc_code = models.CharField(max_length=30)
    field_type = models.CharField(max_length=30)
    created_at = models.DateTimeField(auto_now_add=True)

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

    def __str__(self):
        return f"{self.student.code} - {self.kc_code}/{self.field_type}"



# ============================================================
# Foreground Time Tracking (Phase A)
# ============================================================
class ActiveTimeSession(models.Model):
    """Per-browser-session foreground time tracking.
    Uses W3C Page Visibility API: only 'visible' state increments active_seconds.
    'hidden' = tab switched/other app open. 'idle' = no input for 2min.
    """
    student = models.ForeignKey('Student', on_delete=models.CASCADE, related_name='active_time_sessions')
    date = models.DateField(db_index=True)
    student_session_key = models.CharField(max_length=40, blank=True, db_index=True)
    page_url = models.CharField(max_length=500, blank=True)
    started_at = models.DateTimeField(auto_now_add=True)
    ended_at = models.DateTimeField(null=True, blank=True)
    active_seconds = models.PositiveIntegerField(default=0)
    idle_seconds = models.PositiveIntegerField(default=0)
    hidden_seconds = models.PositiveIntegerField(default=0)
    last_heartbeat = models.DateTimeField(null=True, blank=True)
    ip_address = models.GenericIPAddressField(null=True, blank=True)
    user_agent = models.TextField(blank=True)
    suspicious_flag = models.BooleanField(default=False)

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

    def __str__(self):
        return f"{self.student.code} {self.date} active={self.active_seconds}s"


class DailyActiveTime(models.Model):
    """Aggregated per-student-per-day rollup. Written on every heartbeat.
    Base table for all reports (1d/15d/30d/90d/180d windows).
    """
    student = models.ForeignKey('Student', on_delete=models.CASCADE, related_name='daily_active_times')
    date = models.DateField(db_index=True)
    total_active_seconds = models.PositiveIntegerField(default=0)
    total_idle_seconds = models.PositiveIntegerField(default=0)
    total_hidden_seconds = models.PositiveIntegerField(default=0)
    first_login_at = models.DateTimeField(null=True, blank=True)
    last_logout_at = models.DateTimeField(null=True, blank=True)
    distinct_devices = models.PositiveSmallIntegerField(default=0)
    distinct_ips = models.PositiveSmallIntegerField(default=0)
    suspicious_flag = models.BooleanField(default=False)

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

    def __str__(self):
        return f"{self.student.code} {self.date} active={self.total_active_seconds}s"


# ═══════════════════════════════════════════════════════════════
# Personal To-Do List (staff-only)
# ═══════════════════════════════════════════════════════════════
class TodoItem(models.Model):
    """Personal task list for staff/superuser. Editable, tickable, archivable."""
    user = models.ForeignKey(
        'auth.User', on_delete=models.CASCADE, related_name='todo_items')
    title = models.CharField(max_length=200)
    notes = models.TextField(blank=True)
    is_done = models.BooleanField(default=False, db_index=True)
    is_archived = models.BooleanField(default=False, db_index=True)
    created_at = models.DateTimeField(auto_now_add=True, db_index=True)
    completed_at = models.DateTimeField(null=True, blank=True)
    archived_at = models.DateTimeField(null=True, blank=True)

    class Meta:
        ordering = ['is_done', '-created_at']
        indexes = [
            models.Index(fields=['user', 'is_archived', 'is_done']),
        ]

    def __str__(self):
        return f"{self.user.username}: {self.title[:50]}"


# ═══════════════════════════════════════════════════════════════
# Question Correction Requests (student suggests → teacher approves)
# ═══════════════════════════════════════════════════════════════
class QuestionCorrectionRequest(models.Model):
    """Student-submitted correction for a ModelQuestion field.

    Workflow: Student submits → Teacher approves/rejects → if approved,
    ModelQuestion is updated for everyone + CorrectionLog written.

    Anti-abuse:
      - Unique pending request per (question, student, field)
      - Max 10 pending per student (enforced in view)
      - Teacher approval mandatory
    """
    STATUS_CHOICES = [
        ('PENDING', 'Pending Review'),
        ('APPROVED', 'Approved'),
        ('REJECTED', 'Rejected'),
    ]
    FIELD_CHOICES = [
        ('question_text', 'Question Text'),
        ('model_answer', 'Model Answer'),
        ('explanation', 'Explanation'),
        ('marks', 'Marks'),
    ]

    question = models.ForeignKey(
        'ModelQuestion', on_delete=models.CASCADE,
        related_name='correction_requests')
    student = models.ForeignKey(
        'Student', on_delete=models.CASCADE,
        related_name='correction_requests')
    field_name = models.CharField(max_length=30, choices=FIELD_CHOICES)
    current_value = models.TextField(blank=True,
        help_text='Snapshot of field at time of request')
    proposed_value = models.TextField(help_text='What student suggests')
    reason = models.TextField(help_text='Why student thinks current is wrong')
    status = models.CharField(
        max_length=20, choices=STATUS_CHOICES, default='PENDING', db_index=True)
    reviewed_by = models.ForeignKey(
        'auth.User', null=True, blank=True, on_delete=models.SET_NULL,
        related_name='+')
    reviewed_at = models.DateTimeField(null=True, blank=True)
    review_notes = models.TextField(blank=True)
    created_at = models.DateTimeField(auto_now_add=True, db_index=True)
    updated_at = models.DateTimeField(auto_now=True)

    class Meta:
        ordering = ['-created_at']
        indexes = [
            models.Index(fields=['status', 'created_at']),
            models.Index(fields=['student', 'created_at']),
            models.Index(fields=['question', 'status']),
        ]
        constraints = [
            models.UniqueConstraint(
                fields=['question', 'student', 'field_name'],
                condition=models.Q(status='PENDING'),
                name='unique_pending_correction_per_field',
            ),
        ]

    def __str__(self):
        return f"Q{self.question_id}/{self.field_name} ({self.status})"


class QuestionEditRequest(models.Model):
    student = models.ForeignKey(Student, on_delete=models.CASCADE)
    question = models.ForeignKey(ModelQuestion, on_delete=models.CASCADE)
    new_question_text = models.TextField()
    new_model_answer = models.TextField()
    status = models.CharField(max_length=20, default='PENDING')
    created_at = models.DateTimeField(auto_now_add=True)



class StoryHealRequest(models.Model):
    student = models.ForeignKey(Student, on_delete=models.CASCADE)
    kc = models.ForeignKey(KnowledgeComponent, on_delete=models.CASCADE)
    new_story = models.JSONField(default=list)
    status = models.CharField(max_length=20, default='PENDING')
    created_at = models.DateTimeField(auto_now_add=True)

    class Meta:
        ordering = ['-created_at']


class AttemptLog(models.Model):
    """Append-only record of every answer submitted for a question.
    Used for pipeline state computation and cheat prevention.
    Standards: ISO 8601, AERA/APA/NCME 2014, Rule 9 (append-only).
    """
    student = models.ForeignKey(Student, on_delete=models.CASCADE, related_name='attempt_logs')
    question = models.ForeignKey(ModelQuestion, on_delete=models.CASCADE, related_name='attempt_logs')
    student_answer = models.TextField(blank=True)
    score = models.DecimalField(max_digits=5, decimal_places=2, default=0)
    max_score = models.PositiveSmallIntegerField(default=5)
    outcome = models.CharField(max_length=20, default='WRONG')
    result_json = models.JSONField(default=dict, blank=True)
    created_at = models.DateTimeField(auto_now_add=True, db_index=True)

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

    @property
    def percentage(self):
        if self.max_score == 0:
            return 0.0
        return round((float(self.score) / self.max_score) * 100, 1)

    @property
    def passed(self):
        return self.percentage >= 80.0

    # --- Phase 1 physical test fields (all nullable, additive) ---
    image = models.ImageField(upload_to="attempts/%Y/%m/", blank=True, null=True)
    ocr_text = models.TextField(blank=True, default="",
        help_text="Transcribed answer text (from OCR or delegate entry).")
    grading_rubric = models.JSONField(default=dict, blank=True,
        help_text="Rubric used for grading: expected_answer, keywords, max_marks.")
    grading_prompt = models.TextField(blank=True, default="",
        help_text="AI prompt used to OCR/grade, for audit.")
    needs_review = models.BooleanField(default=False, db_index=True, help_text="Flagged for human review (e.g., missing image).")
    review_status = models.CharField(
        max_length=20, default='pending_review', db_index=True,
        choices=[
            ('pending_review', 'Pending Review'),
            ('approved', 'Approved by Teacher'),
            ('published', 'Published to Parent'),
        ],
        help_text="HITL state: pending_review -> approved -> published"
    )
    teacher_score = models.FloatField(null=True, blank=True, help_text="Manually entered score by teacher")
    teacher_feedback = models.TextField(blank=True, default="", help_text="Manually entered feedback by teacher")
    reviewed_at = models.DateTimeField(null=True, blank=True, help_text="When the teacher reviewed this attempt")
    daily_code = models.CharField(max_length=30, blank=True, default="", db_index=True,
        help_text="Daily code entered by student to unlock this attempt.")
    uploaded_by_user = models.ForeignKey(
        "auth.User", on_delete=models.SET_NULL, null=True, blank=True,
        related_name="uploaded_attempts",
        help_text="Delegate who uploaded on behalf of student (teacher-delegated).")
    is_physical = models.BooleanField(default=False, db_index=True,
        help_text="True if this attempt came from a physical test upload.")
    is_practice = models.BooleanField(default=False, db_index=True,
        help_text="True if this attempt was made during a FUTURE_PRACTICE window (does not affect Mizan)")
    is_late = models.BooleanField(default=False, db_index=True,
        help_text="True if this attempt was made during a PAST_REATTEMPT window (score penalty applied)")
    target_day_number = models.PositiveSmallIntegerField(null=True, blank=True,
        help_text="Which curriculum day this attempt was for (null = current day)")

    # Fraud cancellation tracking (added 2026-11-16)
    cancelled_at = models.DateTimeField(null=True, blank=True, db_index=True,
        help_text="Set when this attempt was cancelled as fraudulent.")
    cancelled_by = models.ForeignKey('auth.User', null=True, blank=True, on_delete=models.SET_NULL,
        related_name='cancelled_attempts',
        help_text="Teacher who cancelled this attempt.")
    cancel_reason = models.TextField(blank=True, default="",
        help_text="Reason for cancellation (fraud evidence description).")
    cancel_evidence_url = models.URLField(blank=True, default="",
        help_text="Google Drive link to the physical paper image evidence.")
    def __str__(self):
        return f"{self.student.code} Q{self.question_id} {self.outcome} {self.percentage}%"


class TestUploaderDelegation(models.Model):
    """Teacher grants a student the right to upload physical tests for another student.
    Audit: granted_by + granted_at. Revoke via is_active=False.
    """
    delegate = models.ForeignKey(Student, on_delete=models.CASCADE,
        related_name='given_delegations')
    target = models.ForeignKey(Student, on_delete=models.CASCADE,
        related_name='received_delegations')
    granted_by = models.ForeignKey('auth.User', on_delete=models.PROTECT,
        related_name='delegations_granted')
    granted_at = models.DateTimeField(auto_now_add=True)
    expires_at = models.DateTimeField(null=True, blank=True)
    is_active = models.BooleanField(default=True, db_index=True)
    notes = models.TextField(blank=True, default='')

    class Meta:
        unique_together = ('delegate', 'target')
        ordering = ['-granted_at']

    def __str__(self):
        return f"{self.delegate.code}→{self.target.code}"


class StageSkip(models.Model):
    """Append-only audit trail when a student pays points to skip a stage.
    Allowed stages: STUDY, VERIFY, REMEDIATION, ESCALATED. Cost: 10 pts.
    """
    student = models.ForeignKey(Student, on_delete=models.CASCADE,
        related_name='stage_skips')
    question = models.ForeignKey(ModelQuestion, on_delete=models.CASCADE,
        related_name='stage_skips',
        null=True, blank=True,
        help_text='Null = bulk skip for all student questions at this stage.')
    stage = models.CharField(max_length=30, db_index=True)
    cost_points = models.PositiveSmallIntegerField(default=1)
    is_bulk = models.BooleanField(default=False, db_index=True)
    skipped_at = models.DateTimeField(auto_now_add=True)

    class Meta:
        unique_together = ('student', 'question', 'stage')
        ordering = ['-skipped_at']

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


class StageUngate(models.Model):
    """Teacher ungates a stage for a student. No reason field per policy.
    Audit: performed_by + performed_at (ISO 27001 A.12.4.1).
    question=NULL means "ungate this stage for all student's questions".
    """
    student = models.ForeignKey(Student, on_delete=models.CASCADE,
        related_name='stage_ungates')
    question = models.ForeignKey(ModelQuestion, on_delete=models.CASCADE,
        null=True, blank=True, related_name='stage_ungates')
    stage = models.CharField(max_length=30, db_index=True)
    ungated_by = models.ForeignKey('auth.User', on_delete=models.PROTECT,
        related_name='ungates_performed')
    ungated_at = models.DateTimeField(auto_now_add=True)
    revoked_at = models.DateTimeField(null=True, blank=True)

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

    def __str__(self):
        return f"{self.student.code} ungate {self.stage}"


class StageUngateRequest(models.Model):
    """Student requests teacher to ungate a stage.
    Teacher resolves: APPROVED creates a StageUngate row.
    """
    STATUS_CHOICES = [
        ('PENDING', 'Pending'),
        ('APPROVED', 'Approved'),
        ('REJECTED', 'Rejected'),
    ]
    student = models.ForeignKey(Student, on_delete=models.CASCADE,
        related_name='ungate_requests')
    question = models.ForeignKey(ModelQuestion, on_delete=models.CASCADE,
        null=True, blank=True, related_name='ungate_requests')
    stage = models.CharField(max_length=30, db_index=True)
    status = models.CharField(max_length=10, choices=STATUS_CHOICES,
        default='PENDING', db_index=True)
    student_note = models.TextField(blank=True, default='')
    requested_at = models.DateTimeField(auto_now_add=True)
    resolved_at = models.DateTimeField(null=True, blank=True)
    resolved_by = models.ForeignKey('auth.User', on_delete=models.SET_NULL,
        null=True, blank=True, related_name='ungate_requests_resolved')

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

    def __str__(self):
        return f"{self.student.code} {self.stage} {self.status}"


class StudentTodo(models.Model):
    """Personal todo list for a student.
    
    Standards: FERPA (private to student), NN/g (progressive disclosure).
    """
    student = models.ForeignKey(Student, on_delete=models.CASCADE, related_name='todos')
    title = models.CharField(max_length=255)
    is_completed = models.BooleanField(default=False)
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)

    class Meta:
        ordering = ['is_completed', '-created_at']
        verbose_name = "Student Todo"
        verbose_name_plural = "Student Todos"

    def __str__(self):
        status = "✓" if self.is_completed else "○"
        return f"{status} {self.title}"


class PersonalTodo(models.Model):
    """Personal todo list for any user (Student, Teacher, Parent).
    Standards: FERPA (private to user), NN/g (progressive disclosure).
    """
    from django.conf import settings
    user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name='personal_todos')
    title = models.CharField(max_length=255)
    is_completed = models.BooleanField(default=False)
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)

    class Meta:
        ordering = ['is_completed', '-created_at']
        verbose_name = "Personal Todo"
        verbose_name_plural = "Personal Todos"

    def __str__(self):
        status = "✓" if self.is_completed else "○"
        return f"{status} {self.title}"


# ============================================================
# StudentDayCompletion — xAPI-aligned "completed" ledger
# Verb: http://adlnet.gov/expapi/verbs/completed
# Append-only in spirit: completed_at is immutable once set.
# ============================================================
class StudentDayCompletion(models.Model):
    """Per-student, per-curriculum-day completion record.

    Day N is 'complete' when ALL StudentDayMission questions for Day N
    have reached SAFAR in the per-question pipeline (pipeline_state).
    The completed_at timestamp is set once and never overwritten.
    """
    STATUS_CHOICES = [
        ('PENDING', 'Pending'),
        ('COMPLETED', 'Completed'),
        ('MISSED', 'Missed'),
    ]

    student = models.ForeignKey(
        'exams.Student', on_delete=models.CASCADE,
        related_name='day_completions',
    )
    day_number = models.PositiveIntegerField(db_index=True)
    status = models.CharField(
        max_length=16, choices=STATUS_CHOICES, default='PENDING',
    )
    completed_at = models.DateTimeField(null=True, blank=True)
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)

    class Meta:
        unique_together = ('student', 'day_number')
        ordering = ['-day_number']

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

    @property
    def completed_date(self):
        return self.completed_at.date() if self.completed_at else None

class AIJourneyStage(models.Model):
    """Stores the AI-generated next stage and feedback for a student's attempt."""
    student = models.ForeignKey('Student', on_delete=models.CASCADE, related_name='ai_journey_stages')
    attempt_log = models.ForeignKey('AttemptLog', on_delete=models.SET_NULL, null=True, blank=True)
    feedback = models.TextField(blank=True, help_text="AI feedback in Roman Urdu")
    next_stage_type = models.CharField(max_length=20, choices=[
        ('STUDY', 'Study (Re-read story)'),
        ('PRACTICE', 'Practice (New generated question)'),
        ('VERIFY', 'Verify (Mastery challenge)')
    ])
    generated_question_text = models.TextField(blank=True)
    generated_model_answer = models.TextField(blank=True)
    generated_options = models.JSONField(default=list, blank=True)
    raw_json = models.JSONField(default=dict, blank=True)
    created_at = models.DateTimeField(auto_now_add=True)

    class Meta:
        ordering = ['-created_at']

    def __str__(self):
        return f"{self.student.code} - {self.next_stage_type} at {self.created_at}"



class ExamToken(models.Model):
    """FIFO queue for physical test appointments (hospital bari system).

    Lifecycle: PENDING -> CALLED -> IN_PROGRESS -> COMPLETED
                     -> SKIPPED (no-show) / CANCELLED (student leaves)

    Standards: FIFO queuing; one active token per student;
    token numbers sequential per day, never renumbered.
    """
    STATUS_CHOICES = [
        ('PENDING', 'Waiting'),
        ('CALLED', 'Called'),
        ('IN_PROGRESS', 'In Progress'),
        ('COMPLETED', 'Completed'),
        ('SKIPPED', 'Skipped'),
        ('CANCELLED', 'Cancelled'),
    ]

    student = models.ForeignKey(
        Student, on_delete=models.CASCADE, related_name='exam_tokens')
    date = models.DateField(db_index=True, help_text='Queue day (local)')
    token_number = models.PositiveIntegerField(
        db_index=True, help_text='Sequential within day, never renumbered')
    status = models.CharField(
        max_length=15, choices=STATUS_CHOICES, default='PENDING', db_index=True)
    issued_at = models.DateTimeField(auto_now_add=True)
    called_at = models.DateTimeField(null=True, blank=True)
    started_at = models.DateTimeField(null=True, blank=True)
    completed_at = models.DateTimeField(null=True, blank=True)
    called_by = models.ForeignKey(
        'auth.User', on_delete=models.SET_NULL, null=True, blank=True,
        related_name='called_exam_tokens')
    attempt = models.ForeignKey(
        'AttemptLog', on_delete=models.SET_NULL, null=True, blank=True,
        related_name='exam_tokens',
        help_text='Physical test attempt linked to this token')
    notes = models.TextField(blank=True, help_text='Teacher remarks')
    uses_remaining = models.PositiveSmallIntegerField(
        default=4,
        help_text='Exam attempts remaining on this token. 0 = finished.',
    )

    class Meta:
        ordering = ['date', 'token_number']
        unique_together = ('date', 'token_number')
        indexes = [
            models.Index(fields=['date', 'status']),
            models.Index(fields=['student', 'status']),
        ]
        constraints = [
            models.UniqueConstraint(
                fields=['student'],
                condition=models.Q(status__in=['PENDING', 'CALLED', 'IN_PROGRESS']),
                name='one_active_exam_token_per_student',
            ),
        ]

    def __str__(self):
        return f'#{self.token_number} {self.student.code} [{self.status}]'


class BetaLegacyRecord(models.Model):
    """Permanent record of a student's contribution during the Beta phase."""
    student_code = models.CharField(max_length=20, unique=True)
    student_name = models.CharField(max_length=100)
    trophies = models.IntegerField(default=0)
    badges = models.IntegerField(default=0)
    mizan_score = models.IntegerField(default=500)
    rank = models.IntegerField(default=0)
    is_founder = models.BooleanField(default=False)
    created_at = models.DateTimeField(auto_now_add=True)

    class Meta:
        ordering = ['rank']
    

class StudentNotification(models.Model):
    """In-app notifications, expire after 1 hour."""
    SHIFT_CHOICES = [('morning','Morning'), ('evening','Evening'), ('general','General')]
    
    student = models.ForeignKey(Student, on_delete=models.CASCADE, related_name='notifications')
    title = models.CharField(max_length=100)
    message = models.TextField()
    shift = models.CharField(max_length=10, choices=SHIFT_CHOICES, default='general')
    expires_at = models.DateTimeField(null=True, blank=True, db_index=True)
    is_read = models.BooleanField(default=False, db_index=True)
    created_at = models.DateTimeField(auto_now_add=True)
    
    class Meta:
        ordering = ['-created_at']
        indexes = [models.Index(fields=['student', 'is_read', 'expires_at'])]
    
    def __str__(self):
        return f"{self.student.code} - {self.title}"


class SafeTerminalOutput(models.Model):
    content = models.TextField()
    created_at = models.DateTimeField(auto_now_add=True)

    class Meta:
        ordering = ['-created_at']


# Classroom 360 models (Command 116)
from .models_classroom import ClassroomSession, ClassroomAttendance, ClassroomResource  # noqa: F401, E402

# Flow engine models (Command 150)
from .models_flow import FlowDefinition, FlowNode, FlowEdge, FlowRun, FlowRunEvent  # noqa

# === Approval gate (2026-11-11) ===
class PendingPointAward(models.Model):
    STATUS_CHOICES = [("PENDING", "Pending"), ("APPROVED", "Approved"), ("REJECTED", "Rejected")]
    student = models.ForeignKey("Student", on_delete=models.CASCADE, related_name="pending_awards")
    points = models.IntegerField()
    code = models.CharField(max_length=60)
    reason = models.TextField(blank=True)
    evidence = models.JSONField(default=dict, blank=True)
    source = models.CharField(max_length=10, default="AUTO")
    requested_by = models.ForeignKey("auth.User", on_delete=models.SET_NULL, null=True, blank=True, related_name="pending_awards_requested")
    status = models.CharField(max_length=10, choices=STATUS_CHOICES, default="PENDING", db_index=True)
    approved_by = models.ForeignKey("auth.User", on_delete=models.SET_NULL, null=True, blank=True, related_name="pending_awards_approved")
    approved_at = models.DateTimeField(null=True, blank=True)
    rejection_reason = models.TextField(blank=True)
    created_at = models.DateTimeField(auto_now_add=True, db_index=True)
    resolved_at = models.DateTimeField(null=True, blank=True)
    class Meta:
        ordering = ["-created_at"]
        indexes = [models.Index(fields=["status", "-created_at"]), models.Index(fields=["student", "status"])]
    def __str__(self):
        return self.student.code + " " + self.code + " " + str(self.points) + " [" + self.status + "]"


class SignupRequest(models.Model):
    """Stores pending signup requests. Does NOT create a User until approved by superuser."""
    name = models.CharField(max_length=150)
    email = models.EmailField(unique=True, help_text='Must be unique to prevent spam')
    student_class = models.CharField(max_length=50)
    shift = models.CharField(max_length=20, choices=[('morning', 'Morning'), ('evening', 'Evening')], default='morning')
    whatsapp_number = models.CharField(max_length=20, blank=True)
    STATUS_CHOICES = [('PENDING', 'Pending'), ('APPROVED', 'Approved'), ('REJECTED', 'Rejected')]
    status = models.CharField(max_length=20, choices=STATUS_CHOICES, default='PENDING', db_index=True)
    created_at = models.DateTimeField(auto_now_add=True)
    processed_at = models.DateTimeField(null=True, blank=True)
    processed_by = models.ForeignKey('auth.User', null=True, blank=True, on_delete=models.SET_NULL, related_name='processed_signups')

    class Meta:
        ordering = ['-created_at']

    def __str__(self):
        return f'{self.name} ({self.email}) - {self.status}'


class PasswordResetRequest(models.Model):
    """Stores requests for password resets."""
    student_code = models.CharField(max_length=20)
    email = models.EmailField()
    STATUS_CHOICES = [('PENDING', 'Pending'), ('APPROVED', 'Approved'), ('REJECTED', 'Rejected')]
    status = models.CharField(max_length=20, choices=STATUS_CHOICES, default='PENDING', db_index=True)
    created_at = models.DateTimeField(auto_now_add=True)
    processed_at = models.DateTimeField(null=True, blank=True)
    processed_by = models.ForeignKey('auth.User', null=True, blank=True, on_delete=models.SET_NULL, related_name='processed_resets')

    class Meta:
        ordering = ['-created_at']

    def __str__(self):
        return f'{self.student_code} - {self.status}'


class RetakeRequest(models.Model):
    """Student-initiated retake request. Teacher approves to grant attempts.

    Flow:
      1. Student hits "Request Retake" on past-day book in Upload Center
      2. RetakeRequest created with status='PENDING'
      3. Teacher sees it in dashboard, clicks Approve → grants N attempts
      4. Student can upload that book up to N times
      5. Each upload uses 1 attempt; when used up, student must request again
    """
    STATUS_CHOICES = [
        ('PENDING', 'Pending'),
        ('APPROVED', 'Approved'),
        ('REJECTED', 'Rejected'),
    ]
    student = models.ForeignKey(
        'exams.Student', on_delete=models.CASCADE,
        related_name='retake_requests',
    )
    day_number = models.PositiveIntegerField(
        help_text='SDM day number this retake is for (1-120)',
    )
    subject = models.CharField(
        max_length=50,
        help_text='Subject name (e.g. Chemistry, Physics)',
    )
    attempts_requested = models.PositiveSmallIntegerField(
        default=1,
        help_text='How many retakes the student asked for',
    )
    attempts_granted = models.PositiveSmallIntegerField(
        default=0,
        help_text='How many retakes the teacher approved (0 = not yet approved)',
    )
    status = models.CharField(
        max_length=20, choices=STATUS_CHOICES, default='PENDING', db_index=True,
    )
    batch_id = models.UUIDField(
        null=True, blank=True, db_index=True,
        help_text='Groups multiple requests submitted together',
    )
    requested_at = models.DateTimeField(auto_now_add=True)
    processed_at = models.DateTimeField(null=True, blank=True)
    processed_by = models.ForeignKey(
        'auth.User', null=True, blank=True,
        on_delete=models.SET_NULL, related_name='processed_retake_requests',
    )
    override_code = models.PositiveSmallIntegerField(null=True, blank=True, help_text="New code issued upon approval")
    notes = models.TextField(blank=True, default='')

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

    def __str__(self):
        return f'{self.student.code} D{self.day_number} {self.subject} ({self.status})'



class QuestionEditRequest(models.Model):
    """Stores student-proposed answers for missing questions. Requires teacher approval."""
    student = models.ForeignKey('exams.Student', on_delete=models.CASCADE)
    question = models.ForeignKey('exams.ModelQuestion', on_delete=models.CASCADE)
    proposed_answer = models.TextField()
    status = models.CharField(max_length=20, default='PENDING', db_index=True) # PENDING, APPROVED, REJECTED
    created_at = models.DateTimeField(auto_now_add=True)
    reviewed_by = models.ForeignKey('auth.User', null=True, blank=True, on_delete=models.SET_NULL)


class MemorizationState(models.Model):
    """SM-2 Spaced Repetition state for a specific keyword per student."""
    student = models.ForeignKey('exams.Student', on_delete=models.CASCADE, related_name='mem_states')
    question = models.ForeignKey('exams.ModelQuestion', on_delete=models.CASCADE)
    keyword = models.CharField(max_length=100)
    interval_days = models.FloatField(default=1.0)
    easiness = models.FloatField(default=2.5)
    next_review = models.DateTimeField(null=True, blank=True, db_index=True)
    last_quality = models.IntegerField(default=0) # 0=New, 1=Again, 3=Hard, 4=Good, 5=Easy
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)

    class Meta:
        unique_together = ('student', 'question', 'keyword')


class RetakePolicy(models.Model):
    """Global policy: must student complete memorization before retake?"""
    is_active = models.BooleanField(default=True)
    require_memorization = models.BooleanField(default=True,
        help_text='Block retake until Memorization flow is completed for all SDM questions')
    require_understanding = models.BooleanField(default=False)
    policy_message = models.TextField(
        default="Aap ko retake request karne se pehle is din ke tamam missing questions ki Memorization complete karni hogi."
    )
    updated_at = models.DateTimeField(auto_now=True)
    updated_by = models.ForeignKey('auth.User', null=True, blank=True, on_delete=models.SET_NULL)

    class Meta:
        verbose_name_plural = 'Retake Policy'

    def __str__(self):
        return f"Policy: memo={self.require_memorization}, under={self.require_understanding}"


class RetakeExemption(models.Model):
    """Teacher override: bypass RetakePolicy for specific (student, day, subject)."""
    student = models.ForeignKey('exams.Student', on_delete=models.CASCADE, related_name='retake_exemptions')
    day_number = models.PositiveIntegerField(null=True, blank=True, help_text='NULL = all days')
    subject = models.CharField(max_length=50, blank=True, help_text='Empty = all subjects')
    granted_by = models.ForeignKey('auth.User', on_delete=models.PROTECT)
    granted_at = models.DateTimeField(auto_now_add=True)
    reason = models.TextField(blank=True, default='')
    expires_at = models.DateTimeField(null=True, blank=True, help_text='NULL = never expires')

    class Meta:
        ordering = ['-granted_at']
        indexes = [models.Index(fields=['student', 'day_number', 'subject'])]

    def __str__(self):
        return f"Exemption {self.student.code} D{self.day_number or '*'}/{self.subject or '*'}"



# ═══════════════════════════════════════════════════════════════
# Fraud Cancellation Audit Trail (added 2026-11-16)
# ═══════════════════════════════════════════════════════════════

class FraudCancellation(models.Model):
    """Immutable audit record of a fraud cancellation event."""
    SCOPE_CHOICES = [
        ('SINGLE', 'Single attempt'),
        ('DAY', 'Single day'),
        ('DAY_RANGE', 'Day range'),
        ('DATE_RANGE', 'Date range'),
        ('MONTH', 'Whole curriculum month'),
    ]
    student = models.ForeignKey(Student, on_delete=models.CASCADE, related_name='fraud_cancellations')
    cancelled_by = models.ForeignKey('auth.User', null=True, blank=True,
        on_delete=models.SET_NULL, related_name='fraud_cancellations_made')
    scope = models.CharField(max_length=10, choices=SCOPE_CHOICES)
    day_from = models.PositiveIntegerField(null=True, blank=True)
    day_to = models.PositiveIntegerField(null=True, blank=True)
    subject_filter = models.CharField(max_length=50, blank=True, default='')
    reason = models.TextField()
    evidence_url = models.URLField(blank=True, default='')
    affected_attempt_ids = models.JSONField(default=list)
    trophy_events_cancelled = models.JSONField(default=list)
    token_uses_refunded = models.PositiveIntegerField(default=0)
    token_ids_refunded = models.JSONField(default=list)
    is_reversed = models.BooleanField(default=False)
    reversed_at = models.DateTimeField(null=True, blank=True)
    reversed_by = models.ForeignKey('auth.User', null=True, blank=True,
        on_delete=models.SET_NULL, related_name='fraud_cancellations_reversed')
    created_at = models.DateTimeField(auto_now_add=True, db_index=True)

    class Meta:
        ordering = ['-created_at']

    def __str__(self):
        return f"{self.student.code} {self.scope} {self.reason[:40]}"

class SubjectRequest(models.Model):
    """Model for students to request new subjects, requiring teacher approval."""
    student = models.ForeignKey(Student, on_delete=models.CASCADE, related_name='subject_requests')
    name = models.CharField(max_length=100)
    status = models.CharField(max_length=20, default='PENDING', choices=[
        ('PENDING', 'Pending'),
        ('APPROVED', 'Approved'),
        ('REJECTED', 'Rejected')
    ])
    created_at = models.DateTimeField(auto_now_add=True)
    reviewed_by = models.ForeignKey('auth.User', on_delete=models.SET_NULL, null=True, blank=True)
    reviewed_at = models.DateTimeField(null=True, blank=True)

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

from .models_finance import FineLedger, FinePayment

from .models_finance import FinePolicy, FinanceDelegation, FineLedger, FinePayment

from .models_finance import CustomLedgerField
