from django.db import models
from django.contrib.auth.models import User

class TypeJournee(models.TextChoices):
    PAUVRE = 'pauvre', 'Pauvre en glucides'
    NORMAL = 'normal', 'Normal en glucides'
    RICHE = 'riche', 'Riche en glucides'

class CategorieAliment(models.TextChoices):
    LEGUME_VERT = 'legume_vert', 'Légumes verts'
    PROTEINE = 'proteine', 'Protéines'
    LIPIDE = 'lipide', 'Lipides'
    GLUCIDE = 'glucide', 'Glucides'
    FRUIT = 'fruit', 'Fruits & Crudités'

class Aliment(models.Model):
    nom = models.CharField(max_length=200)
    categorie = models.CharField(
        max_length=20,
        choices=CategorieAliment.choices
    )
    portion_standard = models.CharField(max_length=100)
    notes = models.TextField(blank=True, null=True)
    
    class Meta:
        ordering = ['categorie', 'nom']
    
    def __str__(self):
        return f"{self.nom} ({self.get_categorie_display()})"

class Journee(models.Model):
    user = models.ForeignKey(User, on_delete=models.CASCADE)
    date = models.DateField()
    type_journee = models.CharField(
        max_length=10,
        choices=TypeJournee.choices
    )
    notes = models.TextField(blank=True, null=True)
    
    class Meta:
        ordering = ['-date']
        unique_together = ['user', 'date']
    
    def __str__(self):
        return f"{self.date} - {self.get_type_journee_display()}"

class TypeRepas(models.TextChoices):
    PETIT_DEJEUNER = 'petit_dejeuner', 'Petit-déjeuner'
    DEJEUNER = 'dejeuner', 'Déjeuner'
    COLLATION = 'collation', 'Collation'
    DINER = 'diner', 'Dîner'

class Repas(models.Model):
    journee = models.ForeignKey(Journee, on_delete=models.CASCADE, related_name='repas')
    type_repas = models.CharField(
        max_length=20,
        choices=TypeRepas.choices
    )
    heure = models.TimeField(blank=True, null=True)
    notes = models.TextField(blank=True, null=True)
    
    class Meta:
        ordering = ['heure']
    
    def __str__(self):
        return f"{self.get_type_repas_display()} - {self.journee.date}"

class CompositionRepas(models.Model):
    repas = models.ForeignKey(Repas, on_delete=models.CASCADE, related_name='compositions')
    aliment = models.ForeignKey(Aliment, on_delete=models.CASCADE)
    nombre_portions = models.DecimalField(max_digits=4, decimal_places=1, default=1.0)
    notes = models.CharField(max_length=200, blank=True)
    
    def __str__(self):
        return f"{self.nombre_portions} x {self.aliment.nom}"
