"""Kaifiyat e Discipline - non-academic composite (bounded context).

DDD bounded context. Only integration: FK to academy.AcademyStudent (read-only).
All writes stay inside this app. Rule K: isolated from Kaifiyat_e_Mizan.

Standards: ISO/IEC/IEEE 42010; DDD (Evans); FERPA (separation);
ISO/IEC 19479:2019; NIST SP 800-53 AU-2/AU-3/AU-12; ISO 15489-1 §9;
ALCOA+; Rule 9, 10, 13, 28.
"""
from django.conf import settings
from django.db import models


class DisciplineCategory(models.Model):
    """One of the 15 charter-form categories (positive or negative).

    Standards: Mississippi MDE Discipline Code Mapping; Charter Schools Form.
    """
    KIND_CHOICES = [("POSITIVE", "Positive"), ("NEGATIVE", "Negative")]
    code = models.CharField(max_length=32, unique=True)
    label_en = models.CharField(max_length=80)
    label_ur = models.CharField(max_length=120)
    kind = models.CharField(max_length=8, choices=KIND_CHOICES)
    points = models.SmallIntegerField()  # +ve positive, -ve negative
    sort_order = models.PositiveSmallIntegerField(default=100)
    active = models.BooleanField(default=True)
    created_at = models.DateTimeField(auto_now_add=True)

    class Meta:
        ordering = ["kind", "sort_order", "code"]
        verbose_name = "Discipline Category"
        verbose_name_plural = "Discipline Categories"


    @property
    def target_url(self):
        MAP = {
            'attendance_entry': '/discipline/attendance/',
            'convert_apply': '/discipline/convert-apply/',
            'points_award': '/discipline/points/',
            'daily_check': '/discipline/daily/',
            'paper_grading': '/discipline/daily/',
            'exam_supervision': '/discipline/sessions/',
            'behavior_logging': '/discipline/violations/',
            'uniform_check': '/discipline/daily/',
            'class_monitor': '/api/portal/all-pages/',
            'library_duty': '/api/portal/all-pages/',
            'message_relay': '/api/portal/parent/messages/',
            'glossary_assign': '/discipline/daily/',
            'fee_verification': '/academy/?tab=fees',
            'support_tickets': '/api/portal/support/',
            'student_management': '/discipline/students/',
            'handwriting_assign': '/discipline/class-homework/bulk/',
            'escalation_manage': '/discipline/escalation/',
            'policy_view': '/discipline/policies/',
            'diary_view': '/discipline/class-homework/',
            'glossary_manage': '/api/portal/teacher/assign-glossary/',
        }
        return MAP.get(self.scope, '/discipline/')

    @property
    def action_label(self):
        MAP = {
            'attendance_entry': 'Mark Attendance',
            'convert_apply': 'Log Late Minutes',
            'points_award': 'Award Points',
            'daily_check': 'Daily Check',
            'paper_grading': 'Grade Papers',
            'exam_supervision': 'Supervise Exam',
            'behavior_logging': 'Log Incident',
            'uniform_check': 'Uniform Check',
            'class_monitor': 'Class Monitor',
            'library_duty': 'Library Duty',
            'message_relay': 'Messages',
            'glossary_assign': 'Assign Glossary',
            'fee_verification': 'Verify Fees',
            'support_tickets': 'Support Tickets',
            'student_management': 'Manage Students',
            'handwriting_assign': 'Assign Handwriting',
            'escalation_manage': 'Manage Escalations',
            'policy_view': 'View Policies',
            'diary_view': 'View Diaries',
            'glossary_manage': 'Manage Glossary',
        }
        return MAP.get(self.scope, 'Go to Duty')

    def __str__(self):

        return f"[{self.kind}] {self.code} {self.points:+d}"


class DisciplineIncident(models.Model):
    """One incident per (student, category, date). Append-only.

    Standards: WVDE incident-based SIS; NIST AU-2; ALCOA+ Original.
    """
    student = models.ForeignKey("academy.AcademyStudent",
        on_delete=models.PROTECT, related_name="discipline_incidents")
    category = models.ForeignKey(DisciplineCategory,
        on_delete=models.PROTECT, related_name="incidents")
    date = models.DateField()
    minutes_late = models.PositiveSmallIntegerField(null=True, blank=True)
    note = models.CharField(max_length=240, blank=True, default="")
    photo_ref = models.CharField(max_length=200, blank=True, default="")
    voice_note_ref = models.CharField(max_length=200, blank=True, default="")
    points_snapshot = models.SmallIntegerField()  # frozen at write time
    recorded_by = models.ForeignKey(settings.AUTH_USER_MODEL,
        on_delete=models.PROTECT, null=True, blank=True,
        related_name="discipline_incidents_recorded")
    recorded_at = models.DateTimeField(auto_now_add=True)

    class Meta:
        ordering = ["-date", "student__code"]
        indexes = [
            models.Index(fields=["student", "date"]),
            models.Index(fields=["category", "date"]),
        ]
        verbose_name = "Discipline Incident"
        verbose_name_plural = "Discipline Incidents"

    def __str__(self):
        return f"{self.student_id} {self.category.code} {self.date} {self.points_snapshot:+d}"


class DisciplineEscalation(models.Model):
    """5-tier escalation status per student.

    Standards: PBIS 3-tier; TN DOE BIP; APA Zero Tolerance 2008.
    """
    TIER_CHOICES = [(1, "T1 Verbal Counsel"), (2, "T2 Written Note"),
                    (3, "T3 Parent Call"), (4, "T4 Parent Meeting"),
                    (5, "T5 BIP + Committee")]
    student = models.ForeignKey("academy.AcademyStudent",
        on_delete=models.CASCADE, related_name="discipline_escalations")
    tier = models.PositiveSmallIntegerField(choices=TIER_CHOICES)
    reason = models.CharField(max_length=240)
    active_from = models.DateField()
    active_until = models.DateField(null=True, blank=True)
    resolved = models.BooleanField(default=False)
    bip_doc_ref = models.CharField(max_length=200, blank=True, default="")
    fba_doc_ref = models.CharField(max_length=200, blank=True, default="")
    created_at = models.DateTimeField(auto_now_add=True)
    created_by = models.ForeignKey(settings.AUTH_USER_MODEL,
        on_delete=models.PROTECT, null=True, blank=True,
        related_name="discipline_escalations_created")

    class Meta:
        ordering = ["-active_from", "-tier"]
        indexes = [models.Index(fields=["student", "resolved"])]
        verbose_name = "Discipline Escalation"
        verbose_name_plural = "Discipline Escalations"

    def __str__(self):
        return f"{self.student_id} T{self.tier}"


class DisciplinePolicy(models.Model):
    """Policy text + consequences per category.

    Standards: Maryland HB 197; UNESCO Positive Discipline 2024.
    """
    category = models.OneToOneField(DisciplineCategory,
        on_delete=models.CASCADE, related_name="policy")
    policy_ur = models.TextField()
    consequence_first = models.CharField(max_length=200, blank=True, default="")
    consequence_repeat = models.CharField(max_length=200, blank=True, default="")
    updated_at = models.DateTimeField(auto_now=True)

    class Meta:
        verbose_name = "Discipline Policy"
        verbose_name_plural = "Discipline Policies"

    def __str__(self):
        return f"Policy {self.category.code}"


class DisciplineLedger(models.Model):
    """Append-only points ledger. Corrections = new rows (Rule 9).

    Standards: ALCOA+ Original; NIST AU-2; ISO 15489-1 §9.
    """
    SOURCE_CHOICES = [("award", "Award"), ("deduct", "Deduct"),
                      ("convert", "Convert"), ("voice", "Voice note"),
                      ("manual", "Manual correction")]
    student = models.ForeignKey("academy.AcademyStudent",
        on_delete=models.CASCADE, related_name="discipline_ledger")
    delta = models.SmallIntegerField()
    reason_text = models.CharField(max_length=240, blank=True, default="")
    reason_category = models.ForeignKey(DisciplineCategory,
        on_delete=models.SET_NULL, null=True, blank=True,
        related_name="ledger_entries")
    converted_minutes = models.PositiveSmallIntegerField(default=0)
    source = models.CharField(max_length=16, choices=SOURCE_CHOICES, default="award")
    ref_incident = models.ForeignKey(DisciplineIncident,
        on_delete=models.SET_NULL, null=True, blank=True,
        related_name="ledger_entries")
    created_by = models.ForeignKey(settings.AUTH_USER_MODEL,
        on_delete=models.PROTECT, null=True, blank=True,
        related_name="discipline_ledger_created")
    created_at = models.DateTimeField(auto_now_add=True)

    class Meta:
        ordering = ["-created_at"]
        indexes = [
            models.Index(fields=["student", "created_at"]),
            models.Index(fields=["source"]),
        ]
        verbose_name = "Discipline Ledger"
        verbose_name_plural = "Discipline Ledger"

    def __str__(self):
        return f"{self.student_id} {self.delta:+d} ({self.source})"


class DisciplineSettings(models.Model):
    """Singleton config: conversion rate + daily/weekly caps.

    Standards: Satchel One thresholds; Rule 10.
    """
    aesthetic_points_per_unit = models.PositiveSmallIntegerField(default=10)
    minutes_per_unit = models.PositiveSmallIntegerField(default=3)
    daily_point_cap = models.PositiveSmallIntegerField(default=50)
    weekly_point_cap = models.PositiveSmallIntegerField(default=150)
    voice_note_clears_one = models.BooleanField(default=True)
    updated_at = models.DateTimeField(auto_now=True)
    updated_by = models.ForeignKey(settings.AUTH_USER_MODEL,
        on_delete=models.SET_NULL, null=True, blank=True,
        related_name="discipline_settings_updated")

    class Meta:
        verbose_name = "Discipline Settings"
        verbose_name_plural = "Discipline Settings"

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

    def __str__(self):
        return f"DisciplineSettings {self.aesthetic_points_per_unit}pts={self.minutes_per_unit}min"


# ==== Student Delegation (Phase SD) ====
from django.contrib.auth import get_user_model as _get_user
_User = _get_user()



class DisciplineAuditEvent(models.Model):
    """Append-only access-control audit for the discipline context.

    Standards: NIST AU-2, AU-3, AU-12; ALCOA+ Attributable; 21 CFR 11.10(e);
    ISO 15489-1 9; ISO 27001 A.8.15; Rule 9 (append-only).
    """
    ACTION_DELEGATION_GRANTED = "DELEGATION_GRANTED"
    ACTION_DELEGATION_REVOKED = "DELEGATION_REVOKED"
    ACTION_DELEGATION_EXPIRED = "DELEGATION_EXPIRED"
    ACTION_DELEGATED_WRITE = "DELEGATED_WRITE"
    ACTION_DENIED_WRITE = "DENIED_WRITE"
    ACTION_READ_OWN = "READ_OWN"
    ACTION_CHOICES = [
        (ACTION_DELEGATION_GRANTED, "Delegation granted"),
        (ACTION_DELEGATION_REVOKED, "Delegation revoked"),
        (ACTION_DELEGATION_EXPIRED, "Delegation expired"),
        (ACTION_DELEGATED_WRITE, "Delegated write"),
        (ACTION_DENIED_WRITE, "Denied write"),
        (ACTION_READ_OWN, "Read own record"),
    ]

    actor = models.ForeignKey(_User, on_delete=models.PROTECT, related_name="discipline_audit_events")
    action = models.CharField(max_length=32, choices=ACTION_CHOICES)
    target_student = models.ForeignKey("academy.AcademyStudent", on_delete=models.PROTECT, null=True, blank=True, related_name="discipline_audit_events")

    target_model = models.CharField(max_length=64, blank=True, default="")
    target_id = models.PositiveBigIntegerField(null=True, blank=True)
    payload_hash = models.CharField(max_length=64, blank=True, default="")
    detail = models.TextField(blank=True, default="")
    created_at = models.DateTimeField(auto_now_add=True)

    class Meta:
        ordering = ["-created_at"]
        indexes = [
            models.Index(fields=["actor", "created_at"], name="dae_actor_idx"),
            models.Index(fields=["action", "created_at"], name="dae_action_idx"),
            models.Index(fields=["target_student", "created_at"], name="dae_student_idx"),
        ]

    def __str__(self):
        return f"{self.created_at:%Y-%m-%d %H:%M} {self.action}"


class AcademyPinAttempt(models.Model):
    """Rate-limit ledger for teacher PIN checks.

    Standards: NIST SP 800-63B-4 5.2.2; NIST SP 800-53 AC-7; OWASP ASVS V2.2.1.
    """
    user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE,
                             related_name="academy_pin_attempts")
    ok = models.BooleanField()
    at = models.DateTimeField(auto_now_add=True)

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


class ViolationAlert(models.Model):
    """Teacher violation inbox - one row per alert (Constitution Art. III.3).

    Standards: NIST AU-6 (audit review); ISO 27001 A.5.25;
    ISO 9241-112 6.3; Rule 10, 13, 23, 28, 31.
    """
    CLASS_CHOICES = [("INFO","Info"),("NOTICE","Notice"),
                     ("WARNING","Warning"),("CRITICAL","Critical")]
    STATUS_CHOICES = [("OPEN","Open"),("APPROVED","Approved"),
                      ("REJECTED","Rejected"),("DISMISSED","Dismissed"),
                      ("ESCALATED","Escalated"),("EXPIRED","Expired")]
    source = models.CharField(max_length=60, db_index=True)
    signal = models.CharField(max_length=60, db_index=True)
    alert_class = models.CharField(max_length=10, choices=CLASS_CHOICES, default="WARNING")
    student = models.ForeignKey("academy.AcademyStudent", null=True, blank=True,
                                on_delete=models.SET_NULL, related_name="violation_alerts")
    evidence = models.JSONField(default=dict, blank=True)
    context = models.TextField(blank=True, default="")
    confidence = models.CharField(max_length=10, blank=True, default="medium")
    recommended = models.CharField(max_length=200, blank=True, default="")
    action_url = models.CharField(max_length=400, blank=True, default="")
    status = models.CharField(max_length=10, choices=STATUS_CHOICES, default="OPEN", db_index=True)
    action_by = models.ForeignKey("auth.User", null=True, blank=True,
                                  on_delete=models.SET_NULL, related_name="+")
    action_at = models.DateTimeField(null=True, blank=True)
    action_reason = models.TextField(blank=True, default="")
    expires_at = models.DateTimeField(null=True, blank=True)
    expiry_action = models.CharField(max_length=40, blank=True, default="")
    created_at = models.DateTimeField(auto_now_add=True, db_index=True)

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

    def __str__(self):
        return f"ALERT #{self.pk} {self.alert_class} {self.signal}"

# ============================================================
# Class & Homework tracking (Session 23 owner directive)
# Standards: PBIS token economy; DASH-2 (handwriting EN);
# BISE 5-tier handwriting rubric (Urdu); Nielsen Norman 5-star
# scale; Saltzer & Schroeder 1975 (fail-safe defaults);
# Rule 9 (log first); Rule 10 (one canonical writer); Rule 28.
# ============================================================
class ClassHomeworkRecord(models.Model):
    """One row per student per day per subject (or overall).

    subject="" means overall day; else it is the subject code (MT-9 etc.).
    All toggles positive-only — negative points remain on the
    discipline incidents page for safety/behaviour cases.
    """
    student = models.ForeignKey(
        "academy.AcademyStudent", on_delete=models.CASCADE,
        related_name="class_homework_records",
    )
    date = models.DateField(db_index=True)
    subject = models.CharField(max_length=16, blank=True, default="", db_index=True)

    # 5 Standard Metrics per subject
    handwriting_done = models.BooleanField(default=False)
    memorization_done = models.BooleanField(default=False)
    understanding_done = models.BooleanField(default=False)
    homework_done = models.BooleanField(default=False)
    classwork_done = models.BooleanField(default=False)


    # 0 = unrated; 1-5 star scale; NN/g + Airbnb convention.
    star_rating = models.PositiveSmallIntegerField(default=0)

    # Diary / report opt-in
    diary_text = models.TextField(blank=True, default="")
    diary_visible = models.BooleanField(default=False)

    saved_by = models.ForeignKey(
        "auth.User", on_delete=models.PROTECT,
        null=True, blank=True, related_name="class_homework_saved",
    )
    saved_at = models.DateTimeField(auto_now=True)

    class Meta:
        ordering = ["-date", "student__code", "subject"]
        unique_together = [("student", "date", "subject")]
        verbose_name = "Class & Homework Record"
        verbose_name_plural = "Class & Homework Records"

    # ---- point formula (single source of truth) ----
    # 2026-10-29: Quality-first scoring (industry standard: Formative Assessment)
    # Stars = quality metric = the ONLY factor that decides points.
    # Toggles = informational indicators of what work was done. They do NOT add points.
    # Scale: 0★=0, 1★=2, 2★=4, 3★=6, 4★=8, 5★=10
    POINTS_PER_STAR = 2
    MAX_STARS = 5

    @property
    def points(self):
        return self.star_rating * self.POINTS_PER_STAR

    @property
    def max_points(self):
        return self.MAX_STARS * self.POINTS_PER_STAR

    def __str__(self):
        return f"{self.student.code} {self.date} {self.subject or 'ALL'} +{self.points}"

class DiaryAssignment(models.Model):
    """Granular tracking of daily diary assignments (LMS Standard)."""
    TASK_TYPES = [
        ('READ', 'Reading'),
        ('MCQ', 'MCQs'),
        ('SHORT', 'Short Questions'),
        ('LONG', 'Long / Open Ended'),
        ('WRITING', 'Writing Practice'),
        ('PAPER', 'Paper Checking (Attempt & Grade)'),
    ]
    
    student = models.ForeignKey('academy.AcademyStudent', on_delete=models.CASCADE, related_name='diary_assignments')
    date = models.DateField(db_index=True)
    subject = models.CharField(max_length=50, db_index=True)
    
    task_type = models.CharField(max_length=16, choices=TASK_TYPES, default='READ')
    page_from = models.PositiveIntegerField(null=True, blank=True)
    page_to = models.PositiveIntegerField(null=True, blank=True)
    details = models.CharField(max_length=255, blank=True, help_text="e.g., 'MCQ 1 to 5', 'Revise paragraph 3'")
    paper_score = models.CharField(max_length=20, blank=True, default="", help_text="e.g. '45/50'")
    
    is_completed = models.BooleanField(default=False)
    allow_repeat = models.BooleanField(default=False, help_text="If checked, this exact task can be assigned again.")
    
    # NEW: 5 Task Dimensions assigned by teacher
    assigned_handwriting = models.BooleanField(default=False)
    assigned_memorization = models.BooleanField(default=False)
    assigned_understanding = models.BooleanField(default=False)
    assigned_homework = models.BooleanField(default=False)
    assigned_classwork = models.BooleanField(default=False)
    
    # NEW: For the AI Diary Pipeline
    ai_pending_json = models.JSONField(null=True, blank=True, help_text="Holds the AI JSON until the teacher approves it.")
    
    # NEW: Mastery Stage Fields
    ai_story = models.TextField(blank=True, null=True, help_text="The 3-act story generated by AI.")
    ai_mcqs = models.JSONField(null=True, blank=True, help_text="The 5 MCQs generated by AI.")
    mastery_passed = models.BooleanField(default=False, help_text="True if student passed the MCQ quiz.")
    teacher_approved = models.BooleanField(default=False)
    
    created_by = models.ForeignKey('auth.User', on_delete=models.PROTECT, related_name='created_diary_assignments')
    created_at = models.DateTimeField(auto_now_add=True)

    class Meta:
        ordering = ['-date', 'subject']
        # Prevent exact duplicates on the same day unless allow_repeat is True
        unique_together = ('student', 'date', 'subject', 'task_type', 'page_from', 'page_to', 'details')
