"""Branded HTML email helpers for sales notifications and client acknowledgements."""

from __future__ import annotations

import logging
import re

from django.conf import settings
from django.core.mail import EmailMultiAlternatives
from django.template.loader import render_to_string

logger = logging.getLogger(__name__)


def _plain_from_html(html: str) -> str:
    text = re.sub(r'(?is)<(script|style).*?>.*?(</\1>)', ' ', html)
    text = re.sub(r'(?is)<br\s*/?>', '\n', text)
    text = re.sub(r'(?is)</p>', '\n\n', text)
    text = re.sub(r'(?is)</tr>', '\n', text)
    text = re.sub(r'(?is)</(div|h1|h2|h3|li)>', '\n', text)
    text = re.sub(r'(?is)<.*?>', ' ', text)
    text = re.sub(r'[ \t]+\n', '\n', text)
    text = re.sub(r'\n{3,}', '\n\n', text)
    text = re.sub(r'[ \t]{2,}', ' ', text)
    return text.strip()


def _send_html_email(
    *,
    subject: str,
    html: str,
    to: list[str],
    reply_to: list[str] | None = None,
) -> bool:
    plain = _plain_from_html(html)
    try:
        msg = EmailMultiAlternatives(
            subject=subject,
            body=plain,
            from_email=settings.DEFAULT_FROM_EMAIL,
            to=to,
            reply_to=reply_to or None,
        )
        msg.attach_alternative(html, 'text/html')
        sent = msg.send(fail_silently=False)
        logger.info('Email sent=%s to=%s subject=%s', sent, to, subject)
        return bool(sent)
    except Exception:
        logger.exception('Failed sending email to %s', to)
        return False


def notify_sales_inquiry(inquiry) -> bool:
    """Styled sales lead email with customer + service details."""
    phone_digits = re.sub(r'\D', '', inquiry.phone or '')
    if phone_digits.startswith('0') and len(phone_digits) == 10:
        phone_digits = '254' + phone_digits[1:]
    elif phone_digits.startswith('254'):
        pass
    elif len(phone_digits) == 9:
        phone_digits = '254' + phone_digits

    html = render_to_string(
        'website/email/sales_lead.html',
        {
            'inquiry': inquiry,
            'whatsapp_url': f'https://wa.me/{phone_digits}' if len(phone_digits) >= 11 else '',
        },
    )
    subject = f"New lead: {inquiry.name} — {inquiry.get_service_display()}"
    email = (inquiry.email or '').strip()
    reply_to = None
    if email and '@' in email and not (
        email.startswith('chat-lead+') and email.endswith('@sphereflux.co.ke')
    ):
        reply_to = [email]
    return _send_html_email(
        subject=subject,
        html=html,
        to=[settings.SALES_EMAIL or settings.CONTACT_NOTIFY_EMAIL],
        reply_to=reply_to,
    )


def send_client_acknowledgement(inquiry) -> bool:
    """Styled acknowledgement email to the customer."""
    to_email = (getattr(inquiry, 'email', None) or '').strip()
    if not to_email:
        return False
    if to_email.startswith('chat-lead+') and to_email.endswith('@sphereflux.co.ke'):
        return False
    html = render_to_string('website/email/client_ack.html', {'inquiry': inquiry})
    return _send_html_email(
        subject='We received your Sphereflux inquiry',
        html=html,
        to=[to_email],
        reply_to=[settings.SALES_EMAIL],
    )


# Backwards-compatible wrappers used by older call sites
def notify_sales(subject: str, body: str, reply_to: str | None = None) -> bool:
    """Plain fallback notify (prefer notify_sales_inquiry)."""
    html = f"""
    <html><body style="font-family:Arial,sans-serif;color:#121820;">
      <div style="max-width:600px;margin:0 auto;border:1px solid #d5dde8;border-radius:12px;overflow:hidden;">
        <div style="background:#0a274f;color:#fff;padding:18px 22px;font-weight:700;">{subject}</div>
        <div style="padding:22px;white-space:pre-wrap;line-height:1.55;">{body}</div>
        <div style="padding:14px 22px;background:#f5f7fb;font-size:12px;color:#4a5564;">
          Sphereflux Limited · sales@sphereflux.co.ke · 0718 679 683
        </div>
      </div>
    </body></html>
    """
    return _send_html_email(
        subject=subject,
        html=html,
        to=[settings.SALES_EMAIL or settings.CONTACT_NOTIFY_EMAIL],
        reply_to=[reply_to] if reply_to else None,
    )
