"""
SendGrid Integration
Handles sending responses via SendGrid API
"""

import os
from typing import Optional, List
from sendgrid import SendGridAPIClient
from sendgrid.helpers.mail import Mail, Email, To, Content


class SendGridClient:
    """Handles SendGrid email sending"""

    def __init__(self, api_key: Optional[str] = None,
                 from_email: str = "support@agentsolutions.tech",
                 from_name: str = "Agent Solutions Team"):
        """
        Initialize SendGrid client

        Args:
            api_key: SendGrid API key (or use SENDGRID_API_KEY env var)
            from_email: Default sender email address
            from_name: Default sender name
        """
        self.api_key = api_key or os.getenv("SENDGRID_API_KEY")
        if not self.api_key:
            raise ValueError("SENDGRID_API_KEY environment variable not set")

        self.client = SendGridAPIClient(self.api_key)
        self.from_email = from_email
        self.from_name = from_name

    def send_email(self,
                   to_email: str,
                   to_name: str,
                   subject: str,
                   body: str,
                   reply_to: Optional[str] = None) -> bool:
        """
        Send an email via SendGrid

        Args:
            to_email: Recipient email address
            to_name: Recipient name
            subject: Email subject
            body: Email body (HTML or plain text)
            reply_to: Optional reply-to email address

        Returns:
            True if sent successfully, False otherwise
        """
        try:
            from_email_obj = Email(self.from_email, self.from_name)
            to_email_obj = To(to_email, to_name)
            subject_obj = subject
            content = Content("text/html", body)

            mail = Mail(from_email_obj, to_email_obj, subject_obj, content)

            if reply_to:
                mail.reply_to = Email(reply_to)

            response = self.client.send(mail)

            # Check if successful (2xx status code)
            return 200 <= response.status_code < 300

        except Exception as e:
            print(f"Error sending email: {e}")
            return False

    def send_template_email(self,
                            to_email: str,
                            to_name: str,
                            template_id: str,
                            dynamic_data: dict) -> bool:
        """
        Send email using SendGrid template

        Args:
            to_email: Recipient email address
            to_name: Recipient name
            template_id: SendGrid template ID
            dynamic_data: Template variables

        Returns:
            True if sent successfully, False otherwise
        """
        try:
            from_email_obj = Email(self.from_email, self.from_name)
            to_email_obj = To(to_email, to_name)

            mail = Mail(from_email=from_email_obj, to_emails=to_email_obj)
            mail.template_id = template_id

            # Add dynamic template data
            for key, value in dynamic_data.items():
                mail.dynamic_template_data = dynamic_data

            response = self.client.send(mail)
            return 200 <= response.status_code < 300

        except Exception as e:
            print(f"Error sending template email: {e}")
            return False

    def send_batch_emails(self, recipients: List[dict]) -> dict:
        """
        Send multiple emails

        Args:
            recipients: List of dicts with 'to_email', 'to_name', 'subject', 'body'

        Returns:
            Dict with 'sent' and 'failed' counts
        """
        results = {'sent': 0, 'failed': 0}

        for recipient in recipients:
            success = self.send_email(
                to_email=recipient['to_email'],
                to_name=recipient['to_name'],
                subject=recipient['subject'],
                body=recipient['body'],
                reply_to=recipient.get('reply_to')
            )

            if success:
                results['sent'] += 1
            else:
                results['failed'] += 1

        return results
