"""Chiffres du tableau de bord du back-office."""

from datetime import date, timedelta

from django.db.models import Count, Q
from django.db.models.functions import TruncWeek
from django.utils import timezone

from apps.leads.models import ContactMessage
from apps.portfolio.models import Project, Testimonial
from apps.services.models import Service

WEEKS = 12
TOP_SERVICES = 5


def _trend(current: int, previous: int) -> int | None:
    """Évolution en %, ou None quand il n'y a rien à comparer."""
    return round((current - previous) * 100 / previous) if previous else None


def _kpi(key: str, label: str, value: int, trend: int | None = None) -> dict:
    return {"key": key, "label": label, "value": value, "trend": trend}


def kpis(today: date) -> list[dict]:
    messages = ContactMessage.objects.all()
    month_start = today.replace(day=1)
    previous_start = (month_start - timedelta(days=1)).replace(day=1)
    this_month = messages.filter(created_at__date__gte=month_start).count()
    last_month = messages.filter(
        created_at__date__gte=previous_start, created_at__date__lt=month_start
    ).count()
    published = {"is_published": True}
    return [
        _kpi("new", "Demandes à traiter", messages.filter(status="new").count()),
        _kpi("month", "Demandes ce mois-ci", this_month, _trend(this_month, last_month)),
        _kpi("services", "Services publiés", Service.objects.filter(**published).count()),
        _kpi("projects", "Réalisations publiées", Project.objects.filter(**published).count()),
        _kpi("testimonials", "Témoignages", Testimonial.objects.filter(**published).count()),
    ]


def weekly(today: date) -> list[dict]:
    """Demandes reçues par semaine (lundi), et combien sont traitées ; semaines vides comprises."""
    first = today - timedelta(days=today.weekday(), weeks=WEEKS - 1)
    rows = (
        ContactMessage.objects.filter(created_at__date__gte=first)
        .annotate(week=TruncWeek("created_at"))
        .values("week")
        .annotate(total=Count("id"), done=Count("id", filter=Q(status="done")))
    )
    counts = {row["week"].date(): row for row in rows}
    weeks = [first + timedelta(weeks=i) for i in range(WEEKS)]
    return [
        {
            "week": week,
            "total": counts.get(week, {}).get("total", 0),
            "done": counts.get(week, {}).get("done", 0),
        }
        for week in weeks
    ]


def statuses() -> list[dict]:
    counts = dict(ContactMessage.objects.values_list("status").annotate(n=Count("id")))
    return [
        {"key": value, "label": label, "count": counts.get(value, 0)}
        for value, label in ContactMessage.Status.choices
    ]


def services() -> list[dict]:
    """Services les plus demandés."""
    rows = (
        ContactMessage.objects.values("service__slug", "service__title")
        .annotate(count=Count("id"))
        .order_by("-count")[:TOP_SERVICES]
    )
    return [
        {
            "key": row["service__slug"] or "general",
            "label": row["service__title"] or "Demande générale",
            "count": row["count"],
        }
        for row in rows
    ]


def dashboard() -> dict:
    today = timezone.localdate()
    return {
        "kpis": kpis(today),
        "weekly": weekly(today),
        "statuses": statuses(),
        "services": services(),
        "recent": ContactMessage.objects.select_related("service")[:6],
    }
