# core/email_utils.py

from django.conf import settings
from django.core.mail import EmailMultiAlternatives
from django.template.loader import render_to_string
from django.utils.html import strip_tags

try:
    from premailer import transform
except ImportError:
    transform = None


def send_html_email(
    subject,
    template_name,
    context,
    to_email,
    from_email=None,
    cc=None,
    bcc=None,
    use_premailer=True,
):
    if not from_email:
        from_email = getattr(settings, "DEFAULT_FROM_EMAIL", None)

    if isinstance(to_email, str):
        to_email = [to_email]

    cc = cc or []
    bcc = bcc or []

    html_content = render_to_string(template_name, context)

    if use_premailer and transform:
        html_content = transform(html_content)

    text_content = strip_tags(html_content)

    email = EmailMultiAlternatives(
        subject=subject,
        body=text_content,
        from_email=from_email,
        to=to_email,
        cc=cc,
        bcc=bcc,
    )

    email.attach_alternative(html_content, "text/html")
    email.send()

    return True