from django.db import models
from django.conf import settings

class TaskDelegation(models.Model):
    TASK_CHOICES = [
        # Attendance & Time
        ('ATTENDANCE', 'Attendance Verification'),
        ('LATE_MINUTES', 'Late Minutes Tracking'),
        ('EXAM_SUPERVISION', 'Exam Supervision'),
        # Discipline & Conduct
        ('UNIFORM_CHECK', 'Uniform Check'),
        ('BEHAVIOR_LOGGING', 'Behavior Incident Logging'),
        ('DAILY_TASKS_CHECK', 'Daily Tasks Verification'),
        # Academics & Grading
        ('PAPER_GRADING', 'Paper Grading'),
        ('GLOSSARY_ASSIGN', 'Assign Books/Glossary'),
        ('PEER_REVIEW', 'Peer Review Management'),
        # Administration & Finance
        ('FEE_VERIFICATION', 'Fees Verification'),
        ('DEVICE_APPROVAL', 'Device Approval'),
        ('DOCUMENT_VAULT', 'Document Vault Management'),
        # Student Support
        ('SUPPORT_TICKETS', 'Support Ticket Resolution'),
        ('LECTURE_REQUESTS', 'Lecture Request Approval'),
        ('PAPER_UPLOAD', 'Upload Model Paper'),
        ('QUESTION_UPLOAD', 'Upload Single Question Answer'),
        ('CUSTOM_PAGE', 'Custom Page / System Page'),
        ('BULK_DIARY', 'Bulk Diary (Write diary for whole class)'),
        ('DIARY_UPLOAD', 'AI Diary Upload (Student)'),
    ]
    assignee = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name='delegated_tasks')
    task_type = models.CharField(max_length=50, choices=TASK_CHOICES)
    target_class = models.CharField(max_length=20, default='ALL')

    DELEGATION_MODE_CHOICES = [
        ('INDIVIDUAL', 'Individual — each question graded separately'),
        ('CHOICE', 'Choice Test — submit 1, credit all in same subject'),
    ]
    delegation_mode = models.CharField(
        max_length=15,
        choices=DELEGATION_MODE_CHOICES,
        default='INDIVIDUAL',
        help_text='CHOICE: score from 1 answer is copied to all active locks in the same subject',
    )
    custom_url = models.CharField(max_length=255, blank=True, default='', help_text='Optional: Override URL')
    notes = models.TextField(blank=True, default='', help_text='Internal note for why this delegation was granted') 
    uses_remaining = models.PositiveSmallIntegerField(
        default=4,
        help_text='Number of uploads remaining. 0 = depleted.',
    )
    expires_at = models.DateTimeField()
    created_by = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name='created_delegations')
    created_at = models.DateTimeField(auto_now_add=True)

# --- Standardized Duty Routing (PBAC) ---
    DUTY_ROUTES = {
        'ATTENDANCE': ('/discipline/attendance/', 'Mark Attendance'),
        'LATE_MINUTES': ('/discipline/attendance/', 'Log Late Minutes'),
        'EXAM_SUPERVISION': ('/discipline/sessions/', 'Supervise Exam'),
        'UNIFORM_CHECK': ('/discipline/daily/', 'Uniform Check'),
        'BEHAVIOR_LOGGING': ('/discipline/violations/', 'Log Incident'),
        'DAILY_TASKS_CHECK': ('/discipline/daily/', 'Verify Tasks'),
        'PAPER_GRADING': ('/discipline/daily/', 'Grade Papers'),
        'GLOSSARY_ASSIGN': ('/discipline/daily/', 'Assign Glossary'),
        'PAPER_UPLOAD': ('/api/portal/model-paper/submit/', 'Upload Paper'),
        'QUESTION_UPLOAD': ('/api/portal/upload-physical/', 'Upload Question Answer'),
        'DIARY_UPLOAD': ('/api/portal/diary-upload/', 'Open AI Diary Upload'),
    }

    @property
    def target_url(self):
        if self.custom_url:
            return self.custom_url
        return self.DUTY_ROUTES.get(self.task_type, ('/discipline/', 'View Duty'))[0]

    @property
    def action_label(self):
        if self.custom_url:
            return 'Open Task'
        return self.DUTY_ROUTES.get(self.task_type, ('/discipline/', 'View Duty'))[1]

    def __str__(self):
        return f"{self.assignee.username} - {self.task_type} ({self.target_class})"

    # ── Peer Review Fields (added 2026-11-17) ──
    attempt_log = models.ForeignKey(
        'exams.AttemptLog',
        on_delete=models.SET_NULL,
        null=True,
        blank=True,
        related_name='peer_review_delegations',
        help_text='The paper being reviewed (null = not a peer-review task)',
    )
    review_verdict = models.CharField(
        max_length=20,
        choices=[
            ('PENDING', 'Pending Review'),
            ('VERIFIED', 'Verified Legitimate'),
            ('FLAGGED', 'Flagged for Fraud'),
            ('CANCELLED', 'Cancelled by Reviewer'),
        ],
        default='PENDING',
        db_index=True,
    )
    review_comment = models.TextField(blank=True, default='')
    reviewed_at = models.DateTimeField(null=True, blank=True)
    reviewed_by = models.ForeignKey(
        'auth.User',
        on_delete=models.SET_NULL,
        null=True,
        blank=True,
        related_name='peer_reviews_submitted',
    )
    pending_fraud_id = models.PositiveIntegerField(
        null=True,
        blank=True,
        help_text='If FLAGGED, points to FraudCancellation awaiting teacher approval',
    )

