from django.db import models

from apps.common.images import webp_spec
from apps.common.models import OrderedModel

LINES_HELP = "Un élément par ligne, au format « Titre | description » (description facultative)."


def parse_lines(text: str) -> list[dict[str, str]]:
    """« Titre | description » par ligne → [{"title": …, "description": …}]."""
    items = []
    for line in text.splitlines():
        title, _, description = line.partition("|")
        if title.strip():
            items.append({"title": title.strip(), "description": description.strip()})
    return items


class Promo(OrderedModel):
    """Vitrine d'un produit maison sur l'accueil (ex. Rapid-Alert)."""

    eyebrow = models.CharField("badge", max_length=60, default="Notre produit maison")
    title = models.CharField("titre", max_length=150)
    text = models.TextField("texte")
    highlight = models.CharField("chiffre ou phrase forte", max_length=60, blank=True)
    tags = models.CharField(
        "étiquettes", max_length=200, blank=True, help_text="Séparées par des virgules"
    )
    benefits = models.TextField("atouts", blank=True, help_text=LINES_HELP)
    steps = models.TextField("étapes « Comment ça marche »", blank=True, help_text=LINES_HELP)
    image = models.ImageField("capture d'écran", upload_to="promo/", blank=True)
    image_webp = webp_spec("image", 1400)
    cta_label = models.CharField("texte du bouton", max_length=50, default="Nous contacter")
    cta_url = models.CharField("lien du bouton", max_length=255, default="/contact")
    link_label = models.CharField("texte du lien secondaire", max_length=50, blank=True)
    link_url = models.URLField("lien secondaire", blank=True)
    is_active = models.BooleanField("actif", default=True)

    class Meta(OrderedModel.Meta):
        verbose_name = "bloc produit"
        verbose_name_plural = "blocs produit"

    def __str__(self) -> str:
        return self.title

    @property
    def benefit_list(self) -> list[dict[str, str]]:
        return parse_lines(self.benefits)

    @property
    def step_list(self) -> list[dict[str, str]]:
        return parse_lines(self.steps)

    @property
    def tag_list(self) -> list[str]:
        return [tag.strip() for tag in self.tags.split(",") if tag.strip()]
