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

User = get_user_model()


class Category(models.Model):
    """
    Categorías de especialización de Lo Justo.
    """
    title = models.CharField(max_length=100, verbose_name="Título")
    slug = models.SlugField(unique=True, verbose_name="Slug (URL)")
    description = models.TextField(blank=True, verbose_name="Descripción")
    icon = models.CharField(
        max_length=50,
        default="rmx.book-open",
        verbose_name="Ícono"
    )

    class Meta:
        verbose_name = "Categoría"
        verbose_name_plural = "Categorías"
        ordering = ["title"]

    def __str__(self):
        return self.title


class Course(models.Model):
    """
    Curso acreditado.
    """
    title = models.CharField(max_length=200, verbose_name="Título del Curso")
    slug = models.SlugField(unique=True, verbose_name="Slug (URL)")
    category = models.ForeignKey(
        Category,
        on_delete=models.CASCADE,
        related_name="courses",
        verbose_name="Categoría"
    )
    instructor = models.ForeignKey(
        User,
        on_delete=models.SET_NULL,
        null=True,
        blank=True,
        related_name="teaching_courses",
        verbose_name="Docente / Instructor"
    )
    short_description = models.CharField(max_length=300, verbose_name="Resumen Ejecutivo")
    description = models.TextField(verbose_name="Temario y Objetivos")
    thumbnail = models.ImageField(
        upload_to="courses/thumbnails/",
        blank=True,
        null=True,
        verbose_name="Imagen Portada"
    )
    iso_standard = models.CharField(
        max_length=50,
        default="ISO/IEC 17025",
        verbose_name="Normativa Asociada"
    )
    price = models.DecimalField(
        max_digits=8, 
        decimal_places=2, 
        default=0.00, 
        verbose_name="Precio (PEN)"
    )
    discount_price = models.DecimalField(
        max_digits=8, 
        decimal_places=2, 
        null=True, 
        blank=True, 
        verbose_name="Precio con Descuento (PEN)"
    )
    is_published = models.BooleanField(default=True, verbose_name="Publicado")
    created_at = models.DateTimeField(auto_now_add=True, verbose_name="Creado el")
    updated_at = models.DateTimeField(auto_now=True, verbose_name="Actualizado el")

    class Meta:
        verbose_name = "Curso"
        verbose_name_plural = "Cursos"
        ordering = ["-created_at"]

    def __str__(self):
        return self.title

    def get_total_lessons(self):
        return Lesson.objects.filter(module__course=self).count()


class Module(models.Model):
    """
    Módulo o sección de un curso.
    """
    course = models.ForeignKey(
        Course,
        on_delete=models.CASCADE,
        related_name="modules",
        verbose_name="Curso"
    )
    title = models.CharField(max_length=200, verbose_name="Título del Módulo")
    order = models.PositiveIntegerField(default=1, verbose_name="Orden")

    class Meta:
        verbose_name = "Módulo"
        verbose_name_plural = "Módulos"
        ordering = ["order", "id"]

    def __str__(self):
        return f"{self.course.title} - Módulo {self.order}: {self.title}"


class Lesson(models.Model):
    """
    Lección individual o clase dentro de un módulo.
    """
    module = models.ForeignKey(
        Module,
        on_delete=models.CASCADE,
        related_name="lessons",
        verbose_name="Módulo"
    )
    title = models.CharField(max_length=200, verbose_name="Título de la Lección")
    slug = models.SlugField(verbose_name="Slug (URL)")
    video_url = models.URLField(blank=True, verbose_name="URL de Video (MP4/YouTube/Vimeo)")
    content = models.TextField(blank=True, verbose_name="Contenido / Material de Apoyo (Markdown/HTML)")
    order = models.PositiveIntegerField(default=1, verbose_name="Orden en el Módulo")

    class Meta:
        verbose_name = "Lección"
        verbose_name_plural = "Lecciones"
        ordering = ["order", "id"]
        unique_together = ("module", "slug")

    def __str__(self):
        return f"{self.module.course.title} -> {self.title}"


class Evaluation(models.Model):
    """
    Cuestionario o Examen de certificación metrológica.
    """
    course = models.ForeignKey(
        Course,
        on_delete=models.CASCADE,
        related_name="evaluations",
        verbose_name="Curso"
    )
    title = models.CharField(max_length=200, verbose_name="Título del Examen")
    questions = models.JSONField(verbose_name="Preguntas (Estructura JSON)")
    passing_score = models.PositiveIntegerField(
        default=80,
        verbose_name="Puntaje Mínimo (%)"
    )

    class Meta:
        verbose_name = "Evaluación"
        verbose_name_plural = "Evaluaciones"

    def __str__(self):
        return f"Examen: {self.title} ({self.course.title})"
