"""Email notifications for new leads.

All sends use ``fail_silently=True`` so a misconfigured mail server never breaks
the public inquiry endpoint — the lead is still saved either way.
"""
import logging
from email.utils import parseaddr

from django.conf import settings
from django.core.mail import EmailMessage

logger = logging.getLogger(__name__)


def _self_email() -> str:
    """The company's own mailbox — the bare address from DEFAULT_FROM_EMAIL
    (e.g. "SirObix <noreply@…>" → "noreply@…"). Used to keep a copy."""
    return parseaddr(getattr(settings, 'DEFAULT_FROM_EMAIL', ''))[1]


def send_inquiry_notifications(inquiry) -> None:
    """Notify staff of a new inquiry and send the customer an acknowledgement."""
    _notify_staff(inquiry)
    _acknowledge_customer(inquiry)


def _notify_staff(inquiry) -> None:
    # Visible recipients = the configured notification addresses. Keep a copy in
    # the company's own mailbox via BCC (not To) — sending To==From trips spam
    # filters (the SpamAssassin TO_EQ_FROM rule, which adds the ***SPAM*** tag).
    to = list(dict.fromkeys(r for r in getattr(settings, 'LEAD_NOTIFY_EMAILS', []) if r))
    self_email = _self_email()
    bcc = [self_email] if self_email and self_email not in to else []
    if not to:
        # No configured recipients — fall back to the self mailbox as the visible To.
        to, bcc = ([self_email] if self_email else []), []
    if not to:
        return

    service_line = f'\nService: {inquiry.service.name}' if inquiry.service_id else ''
    company_line = f'\nCompany: {inquiry.company}' if inquiry.company else ''
    budget_line = (
        f'\nBudget: {inquiry.get_budget_range_display()}' if inquiry.budget_range else ''
    )
    subject = f'New {inquiry.get_inquiry_type_display()} — {inquiry.name}'
    body = (
        f'A new lead has come in via the website.\n\n'
        f'Name: {inquiry.name}\n'
        f'Email: {inquiry.email}\n'
        f'Phone: {inquiry.phone or "—"}\n'
        f'Type: {inquiry.get_inquiry_type_display()}\n'
        f'Subject: {inquiry.get_subject_display() if inquiry.subject else "—"}'
        f'{company_line}{service_line}{budget_line}\n\n'
        f'Message:\n{inquiry.message or "—"}\n'
    )
    try:
        # reply_to the customer so staff can respond directly from the copy.
        EmailMessage(
            subject=subject,
            body=body,
            from_email=settings.DEFAULT_FROM_EMAIL,
            to=to,
            bcc=bcc or None,
            reply_to=[inquiry.email] if inquiry.email else None,
        ).send(fail_silently=True)
    except Exception:  # pragma: no cover - defensive
        logger.exception('Failed to send staff lead notification')


def _acknowledge_customer(inquiry) -> None:
    if not inquiry.email:
        return
    subject = 'We received your message — SirObix'
    body = (
        f'Hi {inquiry.name},\n\n'
        f'Thank you for reaching out to SirObix. We have received your '
        f'message and a member of our team will get back to you shortly.\n\n'
        f'Warm regards,\n'
        f'SirObix\n'
    )
    # BCC the company so we keep a copy of the reply that went to the customer.
    self_email = _self_email()
    try:
        EmailMessage(
            subject=subject,
            body=body,
            from_email=settings.DEFAULT_FROM_EMAIL,
            to=[inquiry.email],
            bcc=[self_email] if self_email else None,
        ).send(fail_silently=True)
    except Exception:  # pragma: no cover - defensive
        logger.exception('Failed to send customer acknowledgement')
