import os
import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from app.core.config import settings
from app.core.i18n import locale_manager # Feltételezve, hogy létrehoztad az i18n.py-t

class EmailManager:
    @staticmethod
    def _get_html_template(template_key: str, variables: dict, lang: str = "hu") -> str:
        # A JSON-ból vesszük a szövegeket
        greeting = locale_manager.get(f"email.{template_key}_greeting", lang=lang, **variables)
        body = locale_manager.get(f"email.{template_key}_body", lang=lang, **variables)
        button_text = locale_manager.get(f"email.{template_key}_button", lang=lang)
        footer = locale_manager.get(f"email.{template_key}_footer", lang=lang)
        
        # Egységes HTML váz gombbal
        return f"""
        <html>
        <body style="font-family: Arial, sans-serif; color: #333;">
            <div style="max-width: 600px; margin: 0 auto; border: 1px solid #ddd; padding: 20px;">
                <h2>{greeting}</h2>
                <p>{body}</p>
                <div style="text-align: center; margin: 30px 0;">
                    <a href="{variables.get('link', '#')}" 
                       style="background-color: #3498db; color: white; padding: 12px 25px; text-decoration: none; border-radius: 5px; font-weight: bold;">
                       {button_text}
                    </a>
                </div>
                <p style="font-size: 0.9em; color: #666;">{variables.get('link')}</p>
                <hr style="border: 0; border-top: 1px solid #eee;">
                <p style="font-size: 0.8em; color: #999;">{footer}</p>
            </div>
        </body>
        </html>
        """

    @staticmethod
    async def send_email(recipient: str, template_key: str, variables: dict, lang: str = "hu"):
        if settings.EMAIL_PROVIDER == "disabled": return
        
        html = EmailManager._get_html_template(template_key, variables, lang)
        subject = locale_manager.get(f"email.{template_key}_subject", lang=lang)

        # SendGrid küldés
        if settings.EMAIL_PROVIDER == "sendgrid" and settings.SENDGRID_API_KEY:
            try:
                from sendgrid import SendGridAPIClient
                from sendgrid.helpers.mail import Mail
                message = Mail(
                    from_email=(settings.EMAILS_FROM_EMAIL, settings.EMAILS_FROM_NAME),
                    to_emails=recipient,
                    subject=subject,
                    html_content=html
                )
                sg = SendGridAPIClient(settings.SENDGRID_API_KEY)
                sg.send(message)
                return {"status": "success"}
            except Exception as e:
                print(f"SendGrid Error: {e}")

        # SMTP Fallback
        # ... (az eredeti SMTP kódod ide jön változatlanul)
        # 2) SMTP fallback
        if not settings.SMTP_HOST or not settings.SMTP_USER or not settings.SMTP_PASSWORD:
            return {"status": "error", "provider": "smtp", "message": "SMTP not configured"}

        try:
            msg = MIMEMultipart()
            msg["From"] = f"{settings.EMAILS_FROM_NAME} <{settings.EMAILS_FROM_EMAIL}>"
            msg["To"] = recipient
            msg["Subject"] = subject
            msg.attach(MIMEText(html or "Üzenet", "html"))

            with smtplib.SMTP(settings.SMTP_HOST, settings.SMTP_PORT, timeout=15) as server:
                if settings.SMTP_USE_TLS:
                    server.starttls()
                server.login(settings.SMTP_USER, settings.SMTP_PASSWORD)
                server.send_message(msg)

            return {"status": "success", "provider": "smtp"}
        except Exception as e:
            return {"status": "error", "provider": "smtp", "message": str(e)}

email_manager = EmailManager()
