from django.db import models
import uuid
from students.models import Course, Student, StudentPayment


class Batch(models.Model):
    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    name = models.CharField(max_length=255)
    description = models.TextField(blank=True, null=True)
    trainer = models.ForeignKey(
        'subscriptions.Profile', on_delete=models.CASCADE, related_name='batches')
    start_date = models.DateField()
    end_date = models.DateField()
    max_students = models.PositiveIntegerField(default=50)
    is_active = models.BooleanField(default=True)
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)

    def __str__(self):
        return self.name

    class Meta:
        ordering = ['-created_at']


class AllCourse(models.Model):
    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    name = models.CharField(max_length=255)
    description = models.TextField()
    trainer = models.ForeignKey(
        'subscriptions.Profile', on_delete=models.CASCADE, related_name='all_courses')
    price = models.DecimalField(max_digits=10, decimal_places=2)
    course_video = models.FileField(
        upload_to='media/course/videos/', null=True, blank=True)
    thumbnail = models.ImageField(
        upload_to='media/course/thumbnails/', null=True, blank=True)
    batch = models.ForeignKey(
        Batch, on_delete=models.CASCADE, related_name='courses', null=True, blank=True)
    is_published = models.BooleanField(default=False)
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)

    def __str__(self):
        return self.name

    class Meta:
        ordering = ['-created_at']

    def get_trainer(self):
        return self.trainer.name

    def get_total_chapters(self):
        return self.chapters.count()

    def get_total_lessons(self):
        return sum(chapter.lessons.count() for chapter in self.chapters.all())


class Chapter(models.Model):
    """Represents a chapter/week in a course"""
    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    course = models.ForeignKey(
        AllCourse, on_delete=models.CASCADE, related_name='chapters')
    title = models.CharField(max_length=255)  # e.g., "Week 1 - Live Classes"
    description = models.TextField(blank=True, null=True)
    order = models.PositiveIntegerField(default=1)
    is_published = models.BooleanField(default=True)
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)

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

    class Meta:
        ordering = ['order']


class Lesson(models.Model):
    """Represents individual lessons within chapters"""
    LESSON_TYPES = [
        ('video', 'Video'),
        ('text', 'Text'),
        ('quiz', 'Quiz'),
        ('assignment', 'Assignment'),
    ]

    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    chapter = models.ForeignKey(
        Chapter, on_delete=models.CASCADE, related_name='lessons')
    # e.g., "Week 1 - Day 1 - Canva Graphic Design (Part I)"
    title = models.CharField(max_length=255)
    description = models.TextField(blank=True, null=True)
    lesson_type = models.CharField(
        max_length=20, choices=LESSON_TYPES, default='video')
    video_file = models.FileField(
        upload_to='media/course/lessons/videos/', null=True, blank=True)
    video_url = models.URLField(blank=True, null=True)
    content = models.TextField(blank=True, null=True)  # For text lessons
    duration_minutes = models.PositiveIntegerField(default=0)
    order = models.PositiveIntegerField(default=1)
    is_published = models.BooleanField(default=True)
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)

    def __str__(self):
        return self.title

    class Meta:
        ordering = ['order']


class CourseEnrollment(models.Model):
    """Student enrollment in courses"""
    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    course = models.ForeignKey(
        AllCourse, on_delete=models.CASCADE, related_name='course_enrollments')
    student = models.ForeignKey(
        Student, on_delete=models.CASCADE, related_name='course_enrollments')
    enrollment_date = models.DateTimeField(auto_now_add=True)
    is_active = models.BooleanField(default=True)
    is_deleted = models.BooleanField(default=False)
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)

    def __str__(self):
        return f"{self.student.student_name} - {self.course.name}"

    class Meta:
        ordering = ['-enrollment_date']
        unique_together = ['course', 'student']

    def get_student(self):
        return self.student.student_name

    def get_course(self):
        return self.course.name

    def get_progress_percentage(self):
        """Calculate overall progress percentage"""
        total_lessons = self.course.get_total_lessons()
        if total_lessons == 0:
            return 0

        completed_lessons = LessonProgress.objects.filter(
            enrollment=self,
            is_completed=True
        ).count()

        return round((completed_lessons / total_lessons) * 100, 2)

    def is_course_completed(self):
        """Check if student has completed the full course"""
        return self.get_progress_percentage() == 100.0

    def can_take_exam(self):
        """Check if student can take exam (course completed and no active exam)"""
        if not self.is_course_completed():
            return False

        from course.models.exam import Exam
        active_exam = Exam.objects.filter(
            enrollment=self,
            submitted_at__isnull=True
        ).first()

        return active_exam is None or active_exam.is_expired


class LessonProgress(models.Model):
    """Tracks individual lesson completion for students"""
    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    enrollment = models.ForeignKey(
        CourseEnrollment, on_delete=models.CASCADE, related_name='lesson_progress')
    lesson = models.ForeignKey(
        Lesson, on_delete=models.CASCADE, related_name='progress')
    is_completed = models.BooleanField(default=False)
    completed_at = models.DateTimeField(null=True, blank=True)
    time_watched = models.PositiveIntegerField(default=0)  # in seconds
    last_position = models.PositiveIntegerField(
        default=0)  # last watched position in seconds
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)

    def __str__(self):
        return f"{self.enrollment.student.name} - {self.lesson.title}"

    class Meta:
        unique_together = ['enrollment', 'lesson']
        ordering = ['lesson__order']

    def mark_completed(self):
        """Mark lesson as completed"""
        from django.utils import timezone
        self.is_completed = True
        self.completed_at = timezone.now()
        self.save()
