from django.core.mail import EmailMultiAlternatives
from django.template.loader import render_to_string
from email.utils import formataddr
import logging
import re, os, json
from PIL import Image
from decouple import config
from twilio.rest import Client

account_sid = config('TWILIO_ACCOUNT_SID')
auth_token = config('TWILIO_AUTH_TOKEN')
messaging_service_sid = config('TWILIO_MESSAGING_SERVICE_SID')
client = Client(account_sid, auth_token)

logger = logging.getLogger(__name__)

# Send Confirmation Email
def send_confirmation_email(guest):
    """
    Send registration confirmation email to guest.
    """
    to_email = guest.email if guest.email else 'unknown'
    try:
        context = {
            'full_name': guest.full_name,
        }

        html_content = render_to_string('emails/confirmation.html', context)
        text_content = re.sub(r'<[^>]+>', '', html_content)
        text_content = re.sub(r'\n\s*\n', '\n\n', text_content)

        subject = f"Your RSVP has been received!"
        from_email = formataddr(("The Awoniyi Family", "noreply@wristbandsng.com"))

        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

# Send Invitation Email
def send_invitation_email(guest):
    """
    Send birthday invitation email to guest.
    """
    to_email = guest.email if guest.email else 'unknown'
    try:
        context = {
            'guest': guest,
            'qr_code_url': f"https://theawoniyifamily.wristbandsng.com/theawoyinifamily/media/qr_codes/{guest.ticket_number}.png",
        }

        html_content = render_to_string('emails/invitation.html', context)
        text_content = re.sub(r'<[^>]+>', '', html_content)
        text_content = re.sub(r'\n\s*\n', '\n\n', text_content)

        subject = f"Your Digital Access!"
        from_email = formataddr(("The Awoniyi Family", "noreply@wristbandsng.com"))

        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

# Send Invite
def send_invite_message(guest):
    """
    Send birthday invitation email to guest.
    """
    to_email = guest.email if guest.email else 'unknown'
    try:
        context = {
            'guest': guest,
        }

        html_content = render_to_string('emails/invite.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 Specially Invited!"
        from_email = formataddr(("The Awoniyi Family", "noreply@wristbandsng.com"))

        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

# Send WhatsApp Message
def send_whatsapp_message(guest, content_sid):
    
    to_number = f"whatsapp:{guest.phone}"
        
    content_variables = json.dumps({
        "1": getattr(guest, 'full_name', getattr(guest, 'name', '')),
        "2": f"access/{getattr(guest, 'ticket_number', '')}",
        "3": "https://theawoniyifamily.wristbandsng.com/"
    })
        
    try:
        message = client.messages.create(
            messaging_service_sid=messaging_service_sid,
            to=to_number,
            content_sid=content_sid,
            content_variables=content_variables
        )
        
        guest.message_sid = message.sid
        guest.save()
        return True
    except Exception as e:
        logger.error(f"Error sending WhatsApp message: {e}")
        return False

# Merge QR Code with Invitation
def merge_qr_with_invite(invite_path, qr_code_path, output_path, qr_size=(520, 520), padding=(250, 2100)):
    
    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)
    
    
