"""
Send custom email function.
"""

from sendgrid import SendGridAPIClient
from sendgrid.helpers.mail import Mail, To

from apexsaas.exceptions import ApexEmailError, ApexValidationError


def send_email(
    to_email: str,
    to_name: str,
    subject: str,
    html_content: str,
    sendgrid_api_key: str,
    from_email: str,
    from_name: str = "Apex",
    text_content: str = None
) -> dict:
    """
    Send custom email.
    
    Args:
        to_email: Recipient email address
        to_name: Recipient name
        subject: Email subject
        html_content: HTML email content
        sendgrid_api_key: SendGrid API key
        from_email: Sender email address
        from_name: Sender name (default: "Apex")
        text_content: Optional plain text content (defaults to HTML stripped)
    
    Returns:
        dict with success status and message details
    
    Raises:
        ApexValidationError: If required parameters are missing
        ApexEmailError: If SendGrid API call fails
    """
    if not to_email or not to_name:
        raise ApexValidationError("to_email and to_name are required")
    if not subject:
        raise ApexValidationError("subject is required")
    if not html_content:
        raise ApexValidationError("html_content is required")
    if not sendgrid_api_key:
        raise ApexValidationError("sendgrid_api_key is required")
    if not from_email:
        raise ApexValidationError("from_email is required")
    
    try:
        # Create message
        message = Mail(
            from_email=(from_email, from_name),
            to_emails=To(to_email),
            subject=subject,
            html_content=html_content,
            plain_text_content=text_content or html_content  # Fallback to HTML if no text
        )
        
        # Send email
        client = SendGridAPIClient(api_key=sendgrid_api_key)
        response = client.send(message)
        
        # Check response
        if response.status_code not in [200, 201, 202]:
            raise ApexEmailError(
                f"SendGrid API error: {response.status_code}",
                details={"service": "sendgrid", "status_code": response.status_code}
            )
        
        return {
            'success': True,
            'message_id': response.headers.get('X-Message-Id', 'unknown'),
            'message': f'Email sent to {to_email}'
        }
    
    except Exception as e:
        if isinstance(e, (ApexValidationError, ApexEmailError)):
            raise
        raise ApexEmailError(
            f"Failed to send email: {str(e)}",
            details={"service": "sendgrid", "original_error": str(e)}
        )

