from django.core.mail import EmailMultiAlternatives
from django.template.loader import render_to_string
from email.utils import formataddr
import logging
import re, os
from PIL import Image

logger = logging.getLogger(__name__)

def send_registration_confirmation_email(guest):
    """
    Send registration confirmation email to guest.
    """
    try:
        context = {
            'guest': guest,
        }

        html_content = render_to_string('emails/send_registration_email.html', context)
        text_content = re.sub(r'<[^>]+>', '', html_content)
        text_content = re.sub(r'\n\s*\n', '\n\n', text_content)

        subject = f"Thank you for confirming your attendance!"
        from_email = formataddr(("Mrs Olabisi Silifat Olateju", "noreply@wristbandsng.com"))
        to_email = guest.email

        msg = EmailMultiAlternatives(subject, text_content, from_email, [to_email])
        msg.attach_alternative(html_content, "text/html")

        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

def send_birthday_invitation_email(guest):
    """
    Send birthday invitation email to guest.
    """
    try:
        context = {
            'guest': guest,
            'qr_code_url': f"https://oso80.com/oso/media/qr_codes/{guest.ticket_number}.png",
        }

        html_content = render_to_string('emails/birthday.html', context)
        text_content = re.sub(r'<[^>]+>', '', html_content)
        text_content = re.sub(r'\n\s*\n', '\n\n', text_content)

        subject = f"You're Invited - Olabisi Silifat Olateju 40th Birthday Celebration"
        from_email = formataddr(("Mrs Olabisi Silifat Olateju", "noreply@wristbandsng.com"))
        to_email = guest.email

        msg = EmailMultiAlternatives(subject, text_content, from_email, [to_email])
        msg.attach_alternative(html_content, "text/html")

        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

def merge_qr_with_invite(invite_path, qr_code_path, output_path, qr_size=(120, 120), padding=(250, 40)):
    
    output_dir = os.path.dirname(output_path)
    if not os.path.exists(output_dir):
        os.makedirs(output_dir)
    
    invite_img = Image.open(invite_path)
    qr_code_img = Image.open(qr_code_path)
    qr_code_img = qr_code_img.resize(qr_size)

    invite_width, invite_height = invite_img.size
    qr_width, qr_height = qr_code_img.size
    position = (padding[0], invite_height - qr_height - padding[1])

    invite_img.paste(qr_code_img, position, qr_code_img)
    invite_img.save(output_path)