from django.db import models
from django.core.validators import MinValueValidator
from academics.models import AcademicClass, Subject, StudentEnrollment
from people.models import Teacher, Student
from .utils.file_upload_paths import student_homework_upload_path, teacher_task_attachment_upload_path, specific_task_attachment_upload_path, specific_task_question_attachment_upload_path


class TaskType(models.Model):

    name = models.CharField(max_length=100, unique=True)
    code = models.CharField(max_length=20, unique=True)
    description = models.TextField(null=True, blank=True)

    is_active = models.BooleanField(default=True)

    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)

    class Meta:
        ordering = ["name"]

    def __str__(self):
        return self.name


# =====================================================
# CLASS TASK
# =====================================================


class ClassTask(models.Model):

    academic_class = models.ForeignKey(
        AcademicClass,
        on_delete=models.CASCADE,
        related_name="tasks",
    )

    subject = models.ForeignKey(
        Subject,
        null=True,
        on_delete=models.CASCADE,
        related_name="tasks",
    )

    task_type = models.ForeignKey(
        TaskType,
        on_delete=models.SET_NULL,
        null=True,
        blank=True,
        related_name="tasks",
    )

    posted_by = models.ForeignKey(
        Teacher,
        on_delete=models.SET_NULL,
        null=True,
        blank=True,
        related_name="posted_tasks",
    )

    title = models.CharField(max_length=255)
    description = models.TextField(null=True, blank=True)

    document = models.FileField(
        upload_to=teacher_task_attachment_upload_path,
        null=True,
        blank=True,
    )

    due_date = models.DateField(null=True, blank=True)

    total_marks = models.PositiveIntegerField(
        null=True,
        blank=True,
        validators=[MinValueValidator(0)],
    )

    is_published = models.BooleanField(default=False)
    is_active = models.BooleanField(default=True)

    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)

    class Meta:
        ordering = ["-created_at"]

    def __str__(self):
        return f"{self.academic_class} - {self.subject.name} - {self.title}"


# =====================================================
# TASK ITEMS (Questions)
# =====================================================


class TaskItem(models.Model):

    class_task = models.ForeignKey(
        ClassTask,
        on_delete=models.CASCADE,
        related_name="task_items",
    )

    question_text = models.TextField()

    attachment = models.FileField(
        upload_to=teacher_task_attachment_upload_path,
        null=True,
        blank=True,
    )

    marks = models.PositiveIntegerField(
        null=True,
        blank=True,
        validators=[MinValueValidator(0)],
    )

    order = models.PositiveIntegerField(default=1)

    is_active = models.BooleanField(default=True)

    created_at = models.DateTimeField(auto_now_add=True)

    class Meta:
        ordering = ["order"]

    def __str__(self):
        return f"{self.class_task.title} - Q{self.order}"


# =====================================================
# STUDENT TASK (Tracking per student)
# =====================================================


class StudentTask(models.Model):

    class_task = models.ForeignKey(
        ClassTask,
        on_delete=models.CASCADE,
        related_name="student_tasks",
    )

    student = models.ForeignKey(
        Student,
        on_delete=models.CASCADE,
        related_name="student_tasks",
    )

    enrollment = models.ForeignKey(
        StudentEnrollment,
        on_delete=models.CASCADE,
        related_name="student_tasks",
    )

    status = models.CharField(
        max_length=20,
        choices=[
            ("PENDING", "Pending"),
            ("SUBMITTED", "Submitted"),
            ("GRADED", "Graded"),
        ],
        default="PENDING",
    )

    total_marks_obtained = models.DecimalField(
        max_digits=5,
        decimal_places=2,
        null=True,
        blank=True,
    )

    submitted_at = models.DateTimeField(null=True, blank=True)
    graded_at = models.DateTimeField(null=True, blank=True)

    teacher_remark = models.TextField(null=True, blank=True)

    is_active = models.BooleanField(default=True)

    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)

    class Meta:
        unique_together = ("class_task", "student")
        ordering = ["-created_at"]

    def __str__(self):
        return f"{self.student} - {self.class_task.title}"


# =====================================================
# STUDENT TASK ITEM (Answer per Question)
# =====================================================


class StudentTaskItem(models.Model):

    student_task = models.ForeignKey(
        StudentTask,
        on_delete=models.CASCADE,
        related_name="answers",
    )

    task_item = models.ForeignKey(
        TaskItem,
        on_delete=models.CASCADE,
        related_name="student_answers",
    )

    answer_text = models.TextField(null=True, blank=True)

    answer_file = models.FileField(
        upload_to=student_homework_upload_path, null=True, blank=True, max_length=500
    )

    marks_obtained = models.DecimalField(
        max_digits=5,
        decimal_places=2,
        null=True,
        blank=True,
    )

    teacher_remark = models.TextField(null=True, blank=True)

    submitted_at = models.DateTimeField(null=True, blank=True)

    created_at = models.DateTimeField(auto_now_add=True)

    class Meta:
        unique_together = ("student_task", "task_item")

    def __str__(self):
        return f"{self.student_task.student} - Q{self.task_item.order}"


# =====================================================
# TASK SUBMISSION (Evaluation Layer)
# =====================================================


class TaskSubmission(models.Model):

    task = models.ForeignKey(
        ClassTask,
        on_delete=models.CASCADE,
        related_name="submissions",
    )
    student_task = models.OneToOneField(
        StudentTask,
        on_delete=models.SET_NULL,
        null=True,
        blank=True,
        related_name="task_submission",
    )
    enrollment = models.ForeignKey(
        StudentEnrollment,
        on_delete=models.CASCADE,
        related_name="task_submissions",
    )

    submitted_at = models.DateTimeField(null=True, blank=True)

    submission_delay_days = models.IntegerField(null=True, blank=True)

    marks_obtained = models.DecimalField(
        max_digits=5,
        decimal_places=2,
        null=True,
        blank=True,
    )

    checked_by = models.ForeignKey(
        Teacher,
        on_delete=models.SET_NULL,
        null=True,
        blank=True,
        related_name="checked_submissions",
    )

    checked_at = models.DateTimeField(null=True, blank=True)

    status = models.CharField(
        max_length=20,
        choices=[
            ("PENDING", "Pending"),
            ("SUBMITTED", "Submitted"),
            ("CHECKED", "Checked"),
            ("LATE", "Late"),
        ],
        default="PENDING",
    )

    remarks = models.TextField(null=True, blank=True)

    is_active = models.BooleanField(default=True)

    created_at = models.DateTimeField(auto_now_add=True)

    class Meta:
        unique_together = ("task", "enrollment")
        ordering = ["-created_at"]

    def __str__(self):
        return f"{self.enrollment} - {self.task.title}"


class StudentTaskSubmission(models.Model):
    """
    Final submission record for a student task.
    Created when student clicks FINAL SUBMIT.
    """

    student_task = models.OneToOneField(
        StudentTask,
        on_delete=models.CASCADE,
        related_name="submission",
    )

    submitted_at = models.DateTimeField(null=True, blank=True)

    submission_delay_days = models.IntegerField(null=True, blank=True)

    marks_obtained = models.DecimalField(
        max_digits=5,
        decimal_places=2,
        null=True,
        blank=True,
    )

    checked_by = models.ForeignKey(
        Teacher,
        on_delete=models.SET_NULL,
        null=True,
        blank=True,
        related_name="evaluated_submissions",
    )

    checked_at = models.DateTimeField(null=True, blank=True)

    status = models.CharField(
        max_length=20,
        choices=[
            ("PENDING", "Pending"),
            ("SUBMITTED", "Submitted"),
            ("CHECKED", "Checked"),
            ("LATE", "Late"),
        ],
        default="PENDING",
    )

    remarks = models.TextField(null=True, blank=True)

    is_active = models.BooleanField(default=True)

    created_at = models.DateTimeField(auto_now_add=True)

    class Meta:
        ordering = ["-created_at"]

    def __str__(self):
        return f"{self.student_task.student} - {self.student_task.class_task.title}"


# =====================================================
# SPECIFIC STUDENT TASK (Created for specific students)
# =====================================================


class SpecificStudentTask(models.Model):
    """
    Task created for specific student(s) by a teacher
    """

    created_by = models.ForeignKey(
        Teacher,
        on_delete=models.SET_NULL,
        null=True,
        related_name="created_specific_tasks",
    )

    subject = models.ForeignKey(
        Subject,
        on_delete=models.SET_NULL,
        null=True,
        blank=True,
        related_name="specific_tasks",
    )

    title = models.CharField(max_length=255)
    description = models.TextField(null=True, blank=True)
    document = models.FileField(upload_to=specific_task_attachment_upload_path, null=True, blank=True)
    due_date = models.DateField(null=True, blank=True)
    total_marks = models.PositiveIntegerField(null=True, blank=True)

    is_active = models.BooleanField(default=True)
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)

    class Meta:
        ordering = ["-created_at"]

    def __str__(self):
        return f"{self.title} - {self.created_by}"


# =====================================================
# SPECIFIC STUDENT TASK ASSIGNMENT (Links to specific students)
# =====================================================


class SpecificStudentTaskAssignment(models.Model):
    """
    Assigns a specific task to individual students with their enrollment
    """

    specific_task = models.ForeignKey(
        SpecificStudentTask, on_delete=models.CASCADE, related_name="assignments"
    )

    student = models.ForeignKey(
        Student, on_delete=models.CASCADE, related_name="specific_task_assignments"
    )

    enrollment = models.ForeignKey(
        StudentEnrollment,
        on_delete=models.CASCADE,
        related_name="specific_task_assignments",
    )

    academic_class = models.ForeignKey(
        AcademicClass,
        on_delete=models.CASCADE,
        related_name="specific_task_assignments",
    )

    status = models.CharField(
        max_length=20,
        choices=[
            ("PENDING", "Pending"),
            ("SUBMITTED", "Submitted"),
            ("GRADED", "Graded"),
        ],
        default="PENDING",
    )

    assigned_at = models.DateTimeField(auto_now_add=True)

    class Meta:
        unique_together = ("specific_task", "student")

    def __str__(self):
        return f"{self.student} - {self.specific_task.title}"


# =====================================================
# SPECIFIC STUDENT TASK ITEMS (Questions/Answers)
# =====================================================


class SpecificStudentTaskItem(models.Model):
    """
    Questions/items for specific student tasks and their answers
    """

    specific_task = models.ForeignKey(
        SpecificStudentTask, on_delete=models.CASCADE, related_name="task_items"
    )

    assignment = models.ForeignKey(
        SpecificStudentTaskAssignment,
        on_delete=models.CASCADE,
        related_name="answers",
        null=True,  # Null when just creating questions
        blank=True,
    )

    question_text = models.TextField()
    attachment = models.FileField(
        upload_to="tasks/specific_questions/", null=True, blank=True
    )
    marks = models.PositiveIntegerField(null=True, blank=True)
    order = models.PositiveIntegerField(default=1)

    # Answer fields (filled by student)
    answer_text = models.TextField(null=True, blank=True)
    answer_file = models.FileField(
        upload_to=student_homework_upload_path,  # ← Use it here
        null=True,
        blank=True,
        max_length=500,
    )
    marks_obtained = models.DecimalField(
        max_digits=5, decimal_places=2, null=True, blank=True
    )
    teacher_remark = models.TextField(null=True, blank=True)

    submitted_at = models.DateTimeField(null=True, blank=True)

    class Meta:
        ordering = ["order"]

    def __str__(self):
        return f"{self.specific_task.title} - Q{self.order}"
