"""
Email service using Resend for transactional emails.
"""
import os
from typing import Optional
import httpx
import structlog

logger = structlog.get_logger(__name__)

class EmailService:
    """Send transactional emails via Resend."""
    
    def __init__(self):
        self.api_key = os.getenv("RESEND_API_KEY", "")
        self.from_email = os.getenv("FROM_EMAIL", "DataShaper AI <noreply@datashaper.ai>")
        self.api_url = "https://api.resend.com/emails"
        
    async def send_email(
        self,
        to: str,
        subject: str,
        html: str,
        reply_to: Optional[str] = None
    ) -> bool:
        """Send an email via Resend."""
        if not self.api_key:
            logger.warning("resend_api_key_not_set")
            return False
            
        try:
            async with httpx.AsyncClient() as client:
                response = await client.post(
                    self.api_url,
                    headers={
                        "Authorization": f"Bearer {self.api_key}",
                        "Content-Type": "application/json"
                    },
                    json={
                        "from": self.from_email,
                        "to": [to],
                        "subject": subject,
                        "html": html,
                        "reply_to": reply_to or "support@datashaper.ai"
                    },
                    timeout=10.0
                )
                response.raise_for_status()
                logger.info("email_sent", to=to, subject=subject)
                return True
        except Exception as e:
            logger.error("email_send_failed", to=to, error=str(e))
            return False
    
    async def send_welcome_email(self, to: str, name: str):
        """Send welcome email to new user."""
        html = f"""
        <!DOCTYPE html>
        <html>
        <head>
            <style>
                body {{ font-family: 'Inter', sans-serif; background-color: #f8fafc; }}
                .container {{ max-width: 600px; margin: 0 auto; background: white; padding: 40px; border-radius: 12px; }}
                .header {{ text-align: center; margin-bottom: 30px; }}
                .logo {{ font-size: 28px; font-weight: bold; background: linear-gradient(to right, #7c3aed, #a855f7); -webkit-background-clip: text; -webkit-text-fill-color: transparent; }}
                .btn {{ display: inline-block; background: linear-gradient(to right, #7c3aed, #a855f7); color: white; padding: 14px 28px; border-radius: 8px; text-decoration: none; font-weight: 600; }}
                .footer {{ text-align: center; color: #64748b; font-size: 14px; margin-top: 40px; }}
            </style>
        </head>
        <body>
            <div class="container">
                <div class="header">
                    <div class="logo">✨ DataShaper AI</div>
                </div>
                <h1 style="color: #1e293b; font-size: 24px;">Welcome to DataShaper AI!</h1>
                <p style="color: #475569; font-size: 16px; line-height: 1.6;">
                    Hi {name},
                </p>
                <p style="color: #475569; font-size: 16px; line-height: 1.6;">
                    Thank you for joining DataShaper AI! You now have access to the fastest data cleaning platform on the market.
                </p>
                <p style="color: #475569; font-size: 16px; line-height: 1.6;">
                    <strong>What you can do:</strong>
                </p>
                <ul style="color: #475569; font-size: 16px; line-height: 1.8;">
                    <li>Clean messy CSV files 10× faster than Pandas</li>
                    <li>Detect and fix data quality issues automatically</li>
                    <li>Generate beautiful quality reports</li>
                    <li>Track lineage and schema changes</li>
                </ul>
                <div style="text-align: center; margin: 30px 0;">
                    <a href="https://datashaper.ai/dashboard" class="btn">Get Started Now →</a>
                </div>
                <p style="color: #475569; font-size: 14px;">
                    Need help? Just reply to this email—we're here to help!
                </p>
                <div class="footer">
                    <p>DataShaper AI | Enterprise Data Healing Engine</p>
                </div>
            </div>
        </body>
        </html>
        """
        await self.send_email(to, "Welcome to DataShaper AI! 🎉", html)
    
    async def send_password_reset(self, to: str, reset_link: str):
        """Send password reset email."""
        html = f"""
        <!DOCTYPE html>
        <html>
        <head>
            <style>
                body {{ font-family: 'Inter', sans-serif; background-color: #f8fafc; }}
                .container {{ max-width: 600px; margin: 0 auto; background: white; padding: 40px; border-radius: 12px; }}
                .btn {{ display: inline-block; background: linear-gradient(to right, #7c3aed, #a855f7); color: white; padding: 14px 28px; border-radius: 8px; text-decoration: none; font-weight: 600; }}
            </style>
        </head>
        <body>
            <div class="container">
                <h1 style="color: #1e293b;">Reset Your Password</h1>
                <p style="color: #475569; font-size: 16px; line-height: 1.6;">
                    We received a request to reset your password. Click the button below to create a new password:
                </p>
                <div style="text-align: center; margin: 30px 0;">
                    <a href="{reset_link}" class="btn">Reset Password →</a>
                </div>
                <p style="color: #64748b; font-size: 14px;">
                    This link expires in 1 hour. If you didn't request this, you can safely ignore this email.
                </p>
            </div>
        </body>
        </html>
        """
        await self.send_email(to, "Reset Your Password - DataShaper AI", html)
    
    async def send_payment_receipt(self, to: str, amount: float, plan: str):
        """Send payment receipt email."""
        html = f"""
        <!DOCTYPE html>
        <html>
        <head>
            <style>
                body {{ font-family: 'Inter', sans-serif; background-color: #f8fafc; }}
                .container {{ max-width: 600px; margin: 0 auto; background: white; padding: 40px; border-radius: 12px; }}
                .receipt {{ background: #f1f5f9; padding: 20px; border-radius: 8px; margin: 20px 0; }}
            </style>
        </head>
        <body>
            <div class="container">
                <h1 style="color: #1e293b;">Payment Received ✓</h1>
                <p style="color: #475569; font-size: 16px;">
                    Thank you for your payment! Here are the details:
                </p>
                <div class="receipt">
                    <p style="margin: 10px 0;"><strong>Plan:</strong> {plan}</p>
                    <p style="margin: 10px 0;"><strong>Amount:</strong> ${amount:.2f}</p>
                    <p style="margin: 10px 0;"><strong>Status:</strong> Paid</p>
                </div>
                <p style="color: #64748b; font-size: 14px;">
                    Your subscription is now active. You can manage your billing at any time from your dashboard.
                </p>
            </div>
        </body>
        </html>
        """
        await self.send_email(to, f"Payment Receipt - ${amount:.2f}", html)

# Global email service instance
email_service = EmailService()
