"""
SendGrid Email Service - Automated email delivery.

Email Types:
- License delivery
- Welcome email
- Payment failed notification
- Renewal reminders
"""

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

logger = structlog.get_logger(__name__)


class SendGridService:
    """SendGrid email integration."""
    
    def __init__(self, api_key: Optional[str] = None):
        self.api_key = api_key or os.getenv('SENDGRID_API_KEY')
        self.from_email = os.getenv('SENDGRID_FROM_EMAIL', 'noreply@datashaper.ai')
        self.from_name = 'DataShaper AI'
        
        if self.api_key:
            self.client = SendGridAPIClient(self.api_key)
        else:
            self.client = None
            logger.warning("sendgrid_not_configured", message="SENDGRID_API_KEY not set")
    
    def send_license_email(
        self,
        to_email: str,
        license_key: str,
        tier: str,
        period: str
    ) -> bool:
        """
        Send license key delivery email.
        
        Args:
            to_email: Customer email
            license_key: Generated license key
            tier: pro or enterprise
            period: monthly, annual, or lifetime
        """
        subject = f"🎉 Your DataShaper AI {tier.upper()} License Key"
        
        html_content = f"""
        <html>
        <head>
            <style>
                body {{ font-family: 'Arial', sans-serif; line-height: 1.6; color: #333; }}
                .container {{ max-width: 600px; margin: 0 auto; padding: 20px; }}
                .header {{ background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); 
                           color: white; padding: 30px; text-align: center; border-radius: 10px; }}
                .content {{ background: #f9fafb; padding: 30px; margin: 20px 0; border-radius: 10px; }}
                .license-box {{ background: white; padding: 20px; border: 2px dashed #667eea; 
                                border-radius: 8px; text-align: center; margin: 20px 0; }}
                .license-key {{ font-family: 'Courier New', monospace; font-size: 18px; 
                                font-weight: bold; color: #667eea; word-break: break-all; }}
                .button {{ background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); 
                          color: white; padding: 15px 30px; text-decoration: none; 
                          border-radius: 8px; display: inline-block; margin: 20px 0; }}
                .footer {{ text-align: center; color: #6b7280; font-size: 12px; margin-top: 30px; }}
            </style>
        </head>
        <body>
            <div class="container">
                <div class="header">
                    <h1>✨ Welcome to DataShaper AI {tier.upper()}!</h1>
                    <p>Your {period} subscription is now active</p>
                </div>
                
                <div class="content">
                    <h2>🎁 Your License Key</h2>
                    <p>Thank you for subscribing! Here's your license key:</p>
                    
                    <div class="license-box">
                        <p class="license-key">{license_key}</p>
                    </div>
                    
                    <h3>📝 How to Activate:</h3>
                    <ol>
                        <li>Open DataShaper AI</li>
                        <li>Go to Settings → License</li>
                        <li>Paste your license key</li>
                        <li>Click "Activate"</li>
                    </ol>
                    
                    <h3>✨ What You Get:</h3>
                    <ul>
                        <li>✅ Unlimited file size</li>
                        <li>✅ 10x faster processing with Polars</li>
                        <li>✅ Enterprise schema reconciliation</li>
                        <li>✅ Professional HTML reports</li>
                        <li>✅ API access for integrations</li>
                        <li>✅ Priority email support</li>
                        <li>✅ Column lineage tracking</li>
                        <li>✅ Schema versioning</li>
                    </ul>
                    
                    <center>
                        <a href="https://datashaper.ai/docs" class="button">📖 View Documentation</a>
                    </center>
                </div>
                
                <div class="footer">
                    <p>Questions? Reply to this email or visit our support center.</p>
                    <p>&copy; 2024 DataShaper AI. All rights reserved.</p>
                </div>
            </div>
        </body>
        </html>
        """
        
        return self._send_email(to_email, subject, html_content, 'license_delivery')
    
    def send_welcome_email(self, to_email: str, tier: str) -> bool:
        """Send welcome email to new users."""
        subject = "Welcome to DataShaper AI! 🎉"
        
        html_content = f"""
        <html>
        <body style="font-family: Arial, sans-serif; line-height: 1.6;">
            <h2>Welcome to DataShaper AI!</h2>
            <p>You're now on the <strong>{tier.upper()}</strong> plan.</p>
            <p>Get started:</p>
            <ul>
                <li>📊 Upload your messy CSV files</li>
                <li>⚙️ Configure settings</li>
                <li>🚀 Get clean data in seconds</li>
            </ul>
            <p>Need help? Check out our <a href="https://datashaper.ai/docs">documentation</a>.</p>
        </body>
        </html>
        """
        
        return self._send_email(to_email, subject, html_content, 'welcome')
    
    def send_payment_failed_email(self, to_email: str) -> bool:
        """Send payment failure notification."""
        subject = "⚠️ Payment Failed - DataShaper AI"
        
        html_content = """
        <html>
        <body style="font-family: Arial, sans-serif; line-height: 1.6;">
            <h2>Payment Issue with Your Subscription</h2>
            <p>We were unable to process your recent payment.</p>
            <p>Please update your payment method to continue using DataShaper AI PRO.</p>
            <p><a href="https://billing.stripe.com" style="background: #667eea; color: white; 
               padding: 10px 20px; text-decoration: none; border-radius: 5px;">
               Update Payment Method</a></p>
            <p>If you have questions, please contact support.</p>
        </body>
        </html>
        """
        
        return self._send_email(to_email, subject, html_content, 'payment_failed')
    
    def send_renewal_reminder(self, to_email: str, days_remaining: int) -> bool:
        """Send subscription renewal reminder."""
        subject = f"🔔 Your DataShaper AI subscription renews in {days_remaining} days"
        
        html_content = f"""
        <html>
        <body style="font-family: Arial, sans-serif; line-height: 1.6;">
            <h2>Subscription Renewal Reminder</h2>
            <p>Your DataShaper AI PRO subscription will renew in <strong>{days_remaining} days</strong>.</p>
            <p>Your credit card will be charged automatically.</p>
            <p>Want to make changes? <a href="https://billing.stripe.com">Manage Subscription</a></p>
            <p>Thank you for using DataShaper AI! ✨</p>
        </body>
        </html>
        """
        
        return self._send_email(to_email, subject, html_content, 'renewal_reminder')
    
    def _send_email(
        self,
        to_email: str,
        subject: str,
        html_content: str,
        email_type: str
    ) -> bool:
        """
        Internal method to send email via SendGrid.
        
        Args:
            to_email: Recipient email
            subject: Email subject
            html_content: HTML content
            email_type: Type for logging
            
        Returns:
            Success status
        """
        if not self.client:
            logger.error("sendgrid_not_configured", email_type=email_type)
            # In development, just log the email
            logger.info("email_would_send",
                to=to_email,
                subject=subject,
                type=email_type)
            return False
        
        try:
            message = Mail(
                from_email=Email(self.from_email, self.from_name),
                to_emails=To(to_email),
                subject=subject,
                html_content=Content("text/html", html_content)
            )
            
            response = self.client.send(message)
            
            logger.info("email_sent",
                to=to_email,
                type=email_type,
                status_code=response.status_code)
            
            return response.status_code in [200, 201, 202]
        
        except Exception as e:
            logger.error("email_send_error",
                to=to_email,
                type=email_type,
                error=str(e))
            return False
