from django.contrib.auth import get_user_model
from django.db import models

from courses.models import Course, Lesson

User = get_user_model()


class Enrollment(models.Model):
    """
    Inscripción de un técnico o auditor en un curso acreditado.
    """
    user = models.ForeignKey(
        User,
        on_delete=models.CASCADE,
        related_name="enrollments",
        verbose_name="Estudiante / Técnico"
    )
    course = models.ForeignKey(
        Course,
        on_delete=models.CASCADE,
        related_name="enrollments",
        verbose_name="Curso"
    )
    enrolled_at = models.DateTimeField(auto_now_add=True, verbose_name="Fecha de Inscripción")

    class Meta:
        verbose_name = "Matrícula"
        verbose_name_plural = "Matrículas"
        unique_together = ("user", "course")
        ordering = ["-enrolled_at"]

    def __str__(self):
        return f"{self.user.username} en {self.course.title}"

    def get_progress_percentage(self):
        total_lessons = self.course.get_total_lessons()
        if total_lessons == 0:
            return 0
        completed = self.progress.filter(is_completed=True).count()
        return int((completed / total_lessons) * 100)


class LessonProgress(models.Model):
    """
    Seguimiento del avance de un estudiante en cada lección.
    """
    enrollment = models.ForeignKey(
        Enrollment,
        on_delete=models.CASCADE,
        related_name="progress",
        verbose_name="Matrícula"
    )
    lesson = models.ForeignKey(
        Lesson,
        on_delete=models.CASCADE,
        verbose_name="Lección"
    )
    is_completed = models.BooleanField(default=False, verbose_name="Completada")
    completed_at = models.DateTimeField(null=True, blank=True, verbose_name="Fecha de Finalización")

    class Meta:
        verbose_name = "Progreso de Lección"
        verbose_name_plural = "Progresos de Lección"
        unique_together = ("enrollment", "lesson")

    def __str__(self):
        status = "✅" if self.is_completed else "⏳"
        return f"{status} {self.enrollment.user.username} - {self.lesson.title}"
