from django.db import models
from django.urls import reverse


class PostizInstallBrief(models.Model):
    PACKAGE_MANAGER_CHOICES = [
        ("pnpm", "pnpm"),
        ("npm", "npm"),
    ]
    NODE_VERSION_CHOICES = [
        ("18 LTS", "18 LTS"),
        ("20 LTS", "20 LTS"),
        ("22 Current", "22 Current"),
    ]
    EMAIL_PROVIDER_CHOICES = [
        ("none", "Skip for now"),
        ("resend", "Resend"),
        ("smtp", "SMTP / Nodemailer"),
    ]
    UPLOAD_STRATEGY_CHOICES = [
        ("local", "Local uploads"),
        ("r2", "Cloudflare R2"),
        ("later", "Decide later"),
    ]

    title = models.CharField(max_length=120)
    public_url = models.URLField(help_text="Public URL where the reverse proxy will expose Postiz.")
    node_version = models.CharField(max_length=20, choices=NODE_VERSION_CHOICES, default="20 LTS")
    package_manager = models.CharField(max_length=10, choices=PACKAGE_MANAGER_CHOICES, default="pnpm")
    postgres_ready = models.BooleanField(default=False)
    redis_ready = models.BooleanField(default=False)
    temporal_ready = models.BooleanField(default=False)
    email_provider = models.CharField(max_length=20, choices=EMAIL_PROVIDER_CHOICES, default="none")
    upload_strategy = models.CharField(max_length=20, choices=UPLOAD_STRATEGY_CHOICES, default="local")
    notes = models.TextField(blank=True)
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)

    class Meta:
        ordering = ["-updated_at"]

    def __str__(self):
        return self.title

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

    @property
    def ready_services_count(self):
        return sum([self.postgres_ready, self.redis_ready, self.temporal_ready])

    @property
    def readiness_percent(self):
        return int((self.ready_services_count / 3) * 100)

    @property
    def status_label(self):
        if self.ready_services_count == 3:
            return "Ready for repo bootstrap"
        if self.ready_services_count == 0:
            return "Blocked by missing services"
        return "Infrastructure in progress"

    @property
    def status_tone(self):
        if self.ready_services_count == 3:
            return "success"
        if self.ready_services_count == 0:
            return "danger"
        return "warning"

    @property
    def next_milestone(self):
        if self.ready_services_count == 3:
            return "Clone the Postiz repository and run the first development boot commands."
        if not self.postgres_ready:
            return "Provision PostgreSQL and capture DATABASE_URL for the .env file."
        if not self.redis_ready:
            return "Bring Redis online so background queues can start locally."
        return "Prepare Temporal and point TEMPORAL_ADDRESS at the stack."
