# api/models.py (full corrected version)

from django.contrib.auth.models import AbstractUser, BaseUserManager
from django.db import models
from django.utils.translation import gettext_lazy as _
import logging

logger = logging.getLogger(__name__)

def content_file_path(instance, filename):
    if hasattr(instance, 'type'):
        if instance.type == 'VIDEO' and instance.file:
            return 'videos/{0}'.format(filename)
        elif instance.type == 'DOCUMENT' and instance.file:
            return 'documents/{0}'.format(filename)
    return 'learning_files/{0}'.format(filename)

class CustomUserManager(BaseUserManager):
    """Custom manager for CustomUser to support email as USERNAME_FIELD"""

    def create_user(self, email, password=None, **extra_fields):
        if not email:
            raise ValueError('The Email field must be set')
        email = self.normalize_email(email)
        user = self.model(email=email, **extra_fields)
        user.set_password(password)
        user.save(using=self._db)
        return user

    def create_superuser(self, email, password=None, **extra_fields):
        extra_fields.setdefault('is_staff', True)
        extra_fields.setdefault('is_superuser', True)
        extra_fields.setdefault('role', 'super_admin')  # Optional: default role for superusers

        if extra_fields.get('is_staff') is not True:
            raise ValueError('Superuser must have is_staff=True.')
        if extra_fields.get('is_superuser') is not True:
            raise ValueError('Superuser must have is_superuser=True.')

        return self.create_user(email, password, **extra_fields)


class CustomUser(AbstractUser):
    ROLE_CHOICES = (
        ('super_admin', 'Super Admin'),
        ('admin', 'Admin'),
        ('teacher', 'Teacher'),
        ('learner', 'Learner'),
        ('parent', 'Parent'),
    )

    username = models.CharField(_('username'), max_length=150, unique=False, blank=True, null=True)
    role = models.CharField(max_length=20, choices=ROLE_CHOICES, default='learner')
    must_change_password = models.BooleanField(default=False)
    phone = models.CharField(max_length=20, blank=True, null=True)
    parent = models.ForeignKey('self', null=True, blank=True, related_name='children', on_delete=models.SET_NULL)
    grade_level = models.CharField(max_length=20, blank=True, null=True)  # For learners
    enrolled_learning_areas = models.ManyToManyField('LearningArea', blank=True, related_name='enrolled_users')
    class_stream = models.ForeignKey('ClassStream', null=True, blank=True, on_delete=models.SET_NULL, related_name='students')

    email = models.EmailField(unique=True, blank=False, null=False)

    USERNAME_FIELD = 'email'
    REQUIRED_FIELDS = []  # No additional fields required during createsuperuser

    objects = CustomUserManager()  # Critical: use custom manager

    def get_full_name(self):
        full = f"{self.first_name} {self.last_name}".strip()
        return full if full else self.email

    def __str__(self):
        return self.email

    def save(self, *args, **kwargs):
        if self.email:
            self.email = self.email.lower().strip()  # Force entire email to lowercase and trim
        if self.role:
            self.role = self.role.lower()
        super().save(*args, **kwargs)


class Grade(models.Model):
    code = models.CharField(max_length=20, unique=True)
    name = models.CharField(max_length=50)

    def __str__(self):
        return self.name


class ClassStream(models.Model):
    grade = models.ForeignKey(Grade, on_delete=models.CASCADE)
    stream_name = models.CharField(max_length=50, blank=True, default='')

    def __str__(self):
        return f"{self.grade.name} - {self.stream_name or 'Unnamed'}"


class LearningArea(models.Model):
    name = models.CharField(max_length=100)
    description = models.TextField(blank=True)
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)

    def __str__(self):
        return self.name


class TeacherAllocation(models.Model):
    teacher = models.ForeignKey(CustomUser, on_delete=models.CASCADE, related_name='allocations', limit_choices_to={'role__in': ['teacher', 'admin']})
    class_stream = models.ForeignKey(ClassStream, on_delete=models.CASCADE)
    learning_area = models.ForeignKey(LearningArea, on_delete=models.CASCADE)

    class Meta:
        unique_together = ('teacher', 'class_stream', 'learning_area')

    def __str__(self):
        return f"{self.teacher} - {self.class_stream} - {self.learning_area}"


class LearningContent(models.Model):
    TYPE_CHOICES = (
        ('VIDEO', 'Video'),
        ('DOCUMENT', 'Document'),
    )

    title = models.CharField(max_length=200)
    description = models.TextField(blank=True)
    type = models.CharField(max_length=20, choices=TYPE_CHOICES, default='DOCUMENT')
    url = models.URLField(blank=True, null=True)
    file = models.FileField(upload_to=content_file_path, blank=True, null=True)
    learning_area = models.ForeignKey(LearningArea, on_delete=models.CASCADE, related_name='contents')
    teacher = models.ForeignKey(CustomUser, on_delete=models.SET_NULL, null=True, blank=True, related_name='created_contents')
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)

    def __str__(self):
        return self.title

    def delete(self, *args, **kwargs):
        if self.file:
            try:
                self.file.delete(save=False)
            except Exception as e:
                logger.warning(f"Could not delete file {self.file.name}: {str(e)}")
        super().delete(*args, **kwargs)


class ContentProgress(models.Model):
    user = models.ForeignKey(CustomUser, on_delete=models.CASCADE, related_name='content_progresses')
    content = models.ForeignKey(LearningContent, on_delete=models.CASCADE, related_name='progresses')
    progress = models.IntegerField(default=0)  # 0-100
    completed = models.BooleanField(default=False)
    last_updated = models.DateTimeField(auto_now=True)

    class Meta:
        unique_together = ('user', 'content')

    def __str__(self):
        return f"{self.user.email} - {self.content.title} - {self.progress}%"


# api/models.py - Add this field to your Quiz model

class Quiz(models.Model):
    title = models.CharField(max_length=200)
    description = models.TextField(blank=True, null=True)
    teacher = models.ForeignKey(CustomUser, on_delete=models.CASCADE, limit_choices_to={'role__in': ['teacher', 'admin']}, null=True, blank=True)
    learning_area = models.ForeignKey(LearningArea, on_delete=models.CASCADE)
    created_at = models.DateTimeField(auto_now_add=True)
    
    # ← ADD THIS LINE
    allow_retakes = models.BooleanField(default=True, help_text="If unchecked, students can only attempt the quiz once")
    
    def __str__(self):
        return self.title


    def __str__(self):
        return self.title


class Question(models.Model):
    QUESTION_TYPES = [
        ('MULTIPLE_CHOICE', 'Multiple Choice'),
        ('TRUE_FALSE', 'True/False'),
    ]

    quiz = models.ForeignKey(Quiz, related_name='questions', on_delete=models.CASCADE)
    text = models.TextField()
    type = models.CharField(max_length=20, choices=QUESTION_TYPES, default='MULTIPLE_CHOICE')

    def __str__(self):
        return f"{self.text[:50]}... ({self.type})"


class Option(models.Model):
    question = models.ForeignKey(Question, related_name='options', on_delete=models.CASCADE)
    text = models.CharField(max_length=500)
    is_correct = models.BooleanField(default=False)

    def __str__(self):
        return f"{self.text} {'(Correct)' if self.is_correct else ''}"


class QuizAttempt(models.Model):
    user = models.ForeignKey(CustomUser, on_delete=models.CASCADE, related_name='quiz_attempts')
    quiz = models.ForeignKey(Quiz, on_delete=models.CASCADE, related_name='attempts')
    score = models.IntegerField(default=0)
    total = models.IntegerField(default=0)
    attempted_at = models.DateTimeField(auto_now_add=True)

    def __str__(self):
        return f"{self.user} - {self.quiz} - {self.score}/{self.total}"


class Attendance(models.Model):
    STATUS_CHOICES = [
        ('PRESENT', 'Present'),
        ('ABSENT', 'Absent'),
        ('LATE', 'Late'),
    ]

    user = models.ForeignKey(CustomUser, on_delete=models.CASCADE, related_name='attendance_records', null=True, blank=True)
    date = models.DateField()
    status = models.CharField(max_length=10, choices=STATUS_CHOICES, default='PRESENT')
    remarks = models.TextField(blank=True, default='')

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

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