from django.core.mail import EmailMultiAlternatives
from django.template.loader import render_to_string
from django.conf import settings
from email.utils import formataddr
import logging
from decouple import config
import re
logger = logging.getLogger(__name__)

default_sender = config('DEFAULT_FROM_EMAIL')

def send_qrcode_email(guest):
    
    to_email = guest.email
    try:
        # unique_code = str(guest.unique_code)
        context = {
            'guest': guest,
            'unique_code': guest.unique_code,
            'qr_code_data': f"https://yialtf.wristbandsng.com/media/qrcodes/{guest.unique_code}.png",
        }

        html_content = render_to_string('emails/send_qrcode.html', context)
        text_content = re.sub(r'<[^>]+>', '', html_content)
        text_content = re.sub(r'\n\s*\n', '\n\n', text_content)

        subject = "You're Invited - YiALTF National Launch"
        from_email = formataddr(("YiALTF", default_sender))

        msg = EmailMultiAlternatives(subject, text_content, from_email, [to_email])
        msg.attach_alternative(html_content, "text/html")

        image_path = settings.BASE_DIR / 'media' / 'yialtf.png'
        with open(image_path, 'rb') as f:
            image_data = f.read()
        import mimetypes
        image_type, _ = mimetypes.guess_type(str(image_path))
        if image_type is None:
            image_type = 'image/png'
        msg.attach('yialtf.png', image_data, image_type)

        msg.send(fail_silently=False)
        logger.info(f'Email sent successfully to {to_email}')
        return True
    except Exception as e:
        logger.error(f'Failed to send email to {to_email}: {str(e)}')
        return False
