from django.core.validators import MaxValueValidator, MinValueValidator
from django.db import models
from django.urls import reverse


class Category(models.Model):
    name = models.CharField(max_length=80, unique=True)
    slug = models.SlugField(max_length=80, unique=True)
    description = models.CharField(max_length=160)
    accent_color = models.CharField(max_length=7, default="#0F766E")

    class Meta:
        ordering = ["name"]

    def __str__(self):
        return self.name


class MomentumEntry(models.Model):
    category = models.ForeignKey(Category, on_delete=models.PROTECT, related_name="entries")
    title = models.CharField(max_length=120)
    entry_date = models.DateField()
    focus_score = models.PositiveSmallIntegerField(
        validators=[MinValueValidator(1), MaxValueValidator(10)]
    )
    energy_score = models.PositiveSmallIntegerField(
        validators=[MinValueValidator(1), MaxValueValidator(10)]
    )
    deep_work_minutes = models.PositiveIntegerField(
        validators=[MinValueValidator(0), MaxValueValidator(960)]
    )
    takeaway = models.CharField(max_length=160)
    reflection = models.TextField(blank=True)
    created_at = models.DateTimeField(auto_now_add=True)

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

    def __str__(self):
        return f"{self.title} ({self.entry_date:%Y-%m-%d})"

    @property
    def momentum_score(self):
        return round((self.focus_score + self.energy_score) / 2, 1)

    def get_absolute_url(self):
        return reverse("entry_detail", args=[self.pk])
