from django.core.mail import EmailMultiAlternatives
from django.template.loader import render_to_string
from django.utils.html import strip_tags
from django.conf import settings


def send_appointment_email(to_email, subject, template_name, context):
    """Envoi email HTML à partir d'un template appointments."""
    html_content = render_to_string(template_name, context)
    text_content = strip_tags(html_content)
    from_email = getattr(settings, "DEFAULT_FROM_EMAIL", "noreply@senegalacademy.com")
    try:
        msg = EmailMultiAlternatives(subject, text_content, from_email, [to_email])
        msg.attach_alternative(html_content, "text/html")
        msg.send()
        return True
    except Exception as e:
        print(f"Erreur envoi email rendez-vous: {e}")
        return False


def send_appointment_confirmation(appointment):
    """Après réservation : rappel avec date/heure, lien Meet ou lieu."""
    slot = appointment.slot
    context = {
        "guest_name": appointment.guest_name or appointment.guest_email,
        "date": slot.date,
        "start_time": slot.start_time,
        "end_time": slot.end_time,
        "is_online": slot.is_online,
        "meet_link": slot.meet_link or "",
        "location_notes": slot.location_notes or "",
    }
    subject = f"Senegal Academy – Rendez-vous confirmé le {slot.date} à {slot.start_time.strftime('%H:%M')}"
    return send_appointment_email(
        appointment.guest_email,
        subject,
        "emails/appointments/confirmation.html",
        context,
    )
