# Copyright (c) 2025 Patrick Motsch
# All rights reserved.
"""
Azure Communication Services Email Connector
Handles email sending via Azure Communication Services
"""

import logging
from typing import Optional
from azure.communication.email import EmailClient
from modules.shared.configuration import APP_CONFIG

logger = logging.getLogger(__name__)


class ConnectorMessagingEmail:
    """
    Azure Communication Services Email connector.
    Handles email sending.
    """
    
    def __init__(self):
        """
        Initialize Azure Communication Services Email client using APP_CONFIG.
        """
        try:
            connectionString = APP_CONFIG.get("MESSAGING_ACS_CONNECTION_STRING")
            senderEmail = APP_CONFIG.get("MESSAGING_ACS_SENDER_EMAIL")
            
            if not connectionString or not senderEmail:
                logger.warning("Azure Communication Services credentials not configured for email")
                self._client = None
                self._senderEmail = None
                return
            
            self._client = EmailClient.from_connection_string(connectionString)
            self._senderEmail = senderEmail
            
            logger.info("Azure Communication Services Email client initialized successfully")
            
        except Exception as e:
            logger.error(f"Failed to initialize Azure Communication Services Email client: {e}")
            self._client = None
            self._senderEmail = None
    
    def send(self, recipient: str, subject: str, message: str) -> bool:
        """
        Send an email via Azure Communication Services.
        
        Args:
            recipient: Recipient email address
            subject: Email subject
            message: Email message content (can be HTML)
        
        Returns:
            bool: True if successful, False otherwise
        """
        if not self._client or not self._senderEmail:
            logger.error("Azure Communication Services Email client not initialized")
            return False
        
        try:
            messageData = {
                "senderAddress": self._senderEmail,
                "recipients": {
                    "to": [{"address": recipient}]
                },
                "content": {
                    "subject": subject,
                    "html": message
                }
            }
            
            # Try both API versions for compatibility
            try:
                poller = self._client.begin_send(messageData)
                poller.result()
            except AttributeError:
                poller = self._client.begin_send_message(messageData)
                poller.result()
            
            logger.info(f"Email sent successfully to {recipient}")
            return True
            
        except Exception as e:
            logger.error(f"Failed to send email to {recipient}: {e}")
            return False

