"""
Email Service
Handles email sending functionality with async operations
"""

from typing import Dict, Any
import aiosmtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.mime.base import MIMEBase
from email import encoders
from pathlib import Path
from core.config import settings

class EmailService:
    def __init__(self):
        self.smtp_server = settings.smtp_server
        self.smtp_port = settings.smtp_port
        self.smtp_username = settings.smtp_username
        self.smtp_password = settings.smtp_password
    
    async def send_website_email(
        self, 
        email: str, 
        folder_name: str, 
        website_name: str,
        host_url: str = None,
    ) -> Dict[str, Any]:
        """
        Send website ZIP via email using HTML template
        """
        try:
            # Debug: Check SMTP credentials (removed verbose prints)
            
            if not all([self.smtp_username, self.smtp_password]):
                raise Exception("SMTP credentials not configured")
            
            # Create ZIP file if it doesn't exist
            website_path = Path("templates/generated") / folder_name
            if not website_path.exists():
                raise Exception("Website folder not found")
            
            zip_path = Path("downloads") / f"{folder_name}.zip"
            zip_path.parent.mkdir(exist_ok=True)
            
            # Create ZIP file if it doesn't exist
            if not zip_path.exists():
                import zipfile
                with zipfile.ZipFile(zip_path, 'w', zipfile.ZIP_DEFLATED) as zipf:
                    for file_path in website_path.rglob('*'):
                        if file_path.is_file():
                            arcname = file_path.relative_to(website_path)
                            zipf.write(file_path, arcname)
                # ZIP created
            else:
                # ZIP already exists
                pass
            
            # Read HTML template
            template_path = Path("templates/email/email_template.html")
            if not template_path.exists():
                raise Exception("Email template not found")
            
            with open(template_path, 'r', encoding='utf-8') as f:
                html_template = f.read()
            
            # Replace placeholders
            html_content = html_template.replace("{{SITE_NAME}}", website_name)
            # Use provided host_url (dynamic from incoming request). If not provided,
            # use auto-detection from settings.
            if not host_url:
                host_url = settings.get_current_domain()

            download_link = f"{host_url.rstrip('/')}/api/download/{folder_name}"
            html_content = html_content.replace("{{DOWNLOAD_LINK}}", download_link)
            
            # Create message
            msg = MIMEMultipart()
            msg['From'] = self.smtp_username
            msg['To'] = email
            msg['Subject'] = f"Your Restaurant Website - {website_name}"
            
            # Attach HTML content
            msg.attach(MIMEText(html_content, 'html'))
            
            # Attach ZIP file
            with open(zip_path, "rb") as attachment:
                part = MIMEBase('application', 'octet-stream')
                part.set_payload(attachment.read())
            
            encoders.encode_base64(part)
            part.add_header(
                'Content-Disposition',
                f'attachment; filename= {folder_name}.zip'
            )
            msg.attach(part)
            
            # Send email asynchronously
            await aiosmtplib.send(
                msg,
                hostname=self.smtp_server,
                port=self.smtp_port,
                start_tls=True,
                username=self.smtp_username,
                password=self.smtp_password
            )
            
            return {"success": True, "message": "Email sent successfully"}
            
        except Exception as e:
            raise Exception(f"Email sending failed: {str(e)}")