from django.db import models
from academics.models import Subject, Standard, AcademicClass
from people.models import Teacher
from .utils.study_material_paths import (
    study_material_upload_path,
    previous_year_paper_upload_path,
)


class StudyMaterial(models.Model):

    MATERIAL_TYPES = [
        ("NOTES", "Class Notes"),
        ("TEXTBOOK", "Textbook"),
        ("REFERENCE", "Reference Material"),
        ("WORKSHEET", "Worksheet"),
        ("SYLLABUS", "Syllabus"),
        ("OTHER", "Other"),
    ]

    title = models.CharField(max_length=255)
    description = models.TextField(blank=True)

    subject = models.ForeignKey(
        Subject, on_delete=models.CASCADE, related_name="study_materials"
    )
    academic_class = models.ForeignKey(
        AcademicClass,
        null=True,
        blank=True,
        on_delete=models.SET_NULL,
        related_name="study_materials",
    )

    material_type = models.CharField(
        max_length=20, choices=MATERIAL_TYPES, default="NOTES"
    )

    file = models.FileField(upload_to=study_material_upload_path)

    uploaded_by = models.ForeignKey(
        Teacher,
        null=True,
        blank=True,
        on_delete=models.SET_NULL,
        related_name="uploaded_study_materials",
    )

    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.subject.name}"


class PreviousYearPaper(models.Model):

    EXAM_TYPES = [
        ("ANNUAL", "Annual Exam"),
        ("HALF_YEARLY", "Half Yearly"),
        ("QUARTERLY", "Quarterly"),
        ("MIDTERM", "Mid-Term"),
        ("UNIT_TEST", "Unit Test"),
        ("BOARD", "Board Exam"),
        ("OTHER", "Other"),
    ]

    title = models.CharField(max_length=255, blank=True)
    subject = models.ForeignKey(
        Subject, on_delete=models.CASCADE, related_name="previous_year_papers"
    )
    standard = models.ForeignKey(
        Standard, on_delete=models.CASCADE, related_name="previous_year_papers"
    )

    year = models.PositiveIntegerField(help_text="Year of the exam, e.g. 2023")
    exam_type = models.CharField(max_length=20, choices=EXAM_TYPES, default="ANNUAL")

    file = models.FileField(upload_to=previous_year_paper_upload_path)

    uploaded_by = models.ForeignKey(
        Teacher,
        null=True,
        blank=True,
        on_delete=models.SET_NULL,
        related_name="uploaded_pyq_papers",
    )

    is_active = models.BooleanField(default=True)
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)

    class Meta:
        ordering = ["-year", "-created_at"]

    def __str__(self):
        return f"{self.subject.name} — {self.get_exam_type_display()} {self.year}"
