from django.conf import settings
from django.contrib.auth import get_user_model
from django.core.mail import send_mail
from django.template.loader import render_to_string

from .models import ProjectBrief


def _notify_recipients():
    configured = getattr(settings, "MANAGED_PROJECTS_NOTIFY_EMAILS", None)
    if configured:
        return [email.strip() for email in configured.split(",") if email.strip()]
    User = get_user_model()
    return list(
        User.objects.filter(is_superuser=True, is_active=True)
        .exclude(email="")
        .values_list("email", flat=True)
    )


def send_new_brief_admin_email(brief: ProjectBrief):
    recipients = _notify_recipients()
    if not recipients:
        return
    subject = f"New project brief: {brief.title}"
    body = render_to_string(
        "projects/emails/new_brief_admin.txt",
        {"brief": brief},
    )
    send_mail(
        subject,
        body,
        settings.DEFAULT_FROM_EMAIL,
        recipients,
        fail_silently=False,
    )


def send_brief_status_email(brief: ProjectBrief, previous_status: str):
    client_email = brief.client.email
    if not client_email:
        return
    status_labels = dict(ProjectBrief.STATUS_CHOICES)
    subject = f"Project update: {brief.title}"
    body = render_to_string(
        "projects/emails/status_change_client.txt",
        {
            "brief": brief,
            "previous_status": status_labels.get(previous_status, previous_status),
        },
    )
    send_mail(
        subject,
        body,
        settings.DEFAULT_FROM_EMAIL,
        [client_email],
        fail_silently=False,
    )
