from django.db import models
from .category import FormulaCategory
from users.models import User
from django.utils import timezone
from .symbol import Symbol

class Formula(models.Model):
    formula_id = models.CharField(max_length=100)
    title = models.CharField(max_length=255)
    description = models.TextField(blank=True)
    meta = models.TextField(blank=True)
    category = models.ForeignKey(FormulaCategory, on_delete=models.PROTECT)
    tags = models.JSONField(default=list)
    latex = models.TextField()
    raw_latex = models.TextField()
    symbols = models.ManyToManyField(Symbol, related_name='formulas')
    calculator = models.CharField(max_length=100)
    revision = models.PositiveIntegerField(default=1)
    code = models.CharField(max_length=10, unique=True)
    created_by = models.ForeignKey(User, on_delete=models.SET_NULL, null=True)
    created_at = models.DateTimeField(default=timezone.now)
    

    def save(self, *args, **kwargs):
        if not self.code:
            base_prefix = f"{self.category.prefix:02d}"
            existing_codes = Formula.objects.filter(category=self.category).values_list('code', flat=True)
            index = 1
            while True:
                proposed_code = f"{base_prefix}{index:02d}{self.revision:02d}"
                if proposed_code not in existing_codes:
                    self.code = proposed_code
                    break
                index += 1
        super().save(*args, **kwargs)

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