import os
import smtplib
import logging
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

logger = logging.getLogger(__name__)

class EmailManager:
    @staticmethod
    def _get_html_template(template_key: str, variables: dict, lang: str = "hu") -> str:
        """HTML sablon generálása a fordítási fájlok alapján."""
        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)
        
        # ÚJ: A link fallback szöveg is a nyelvi fájlból jön
        link_fallback_text = locale_manager.get("email.link_fallback", lang=lang)
        
        return f"""
        <html>
        <body style="font-family: Arial, sans-serif; color: #333; line-height: 1.6;">
            <div style="max-width: 600px; margin: 0 auto; border: 1px solid #ddd; padding: 30px; border-radius: 10px;">
                <h2 style="color: #2c3e50;">{greeting}</h2>
                <p>{body}</p>
                <div style="text-align: center; margin: 40px 0;">
                    <a href="{variables.get('link', '#')}" 
                       style="background-color: #3498db; color: white; padding: 15px 30px; text-decoration: none; border-radius: 5px; font-weight: bold; font-size: 16px;">
                        {button_text}
                    </a>
                </div>
                <p style="font-size: 0.85em; color: #777; word-break: break-all;">
                    {link_fallback_text}<br>
                    <a href="{variables.get('link')}" style="color: #3498db;">{variables.get('link')}</a>
                </p>
                <hr style="border: 0; border-top: 1px solid #eee; margin: 30px 0;">
                <p style="font-size: 0.8em; color: #999; text-align: center;">{footer}</p>
            </div>
        </body>
        </html>
        """

    @staticmethod
    async def send_email(recipient: str, template_key: str, variables: dict, lang: str = "hu"):
        """E-mail küldése SendGrid-en keresztül, SMTP fallback-el."""
        if settings.EMAIL_PROVIDER == "disabled": 
            logger.info("Email küldés letiltva.")
            return
        
        html = EmailManager._get_html_template(template_key, variables, lang)
        subject = locale_manager.get(f"email.{template_key}_subject", lang=lang)

        # 1. 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)
                response = sg.send(message)
                
                logger.info(f"SendGrid Status: {response.status_code} for {recipient}")
                return {"status": "success", "provider": "sendgrid", "code": response.status_code}
            except Exception as e:
                logger.error(f"SendGrid Kritikus Hiba: {str(e)}")

        # 2. SMTP Fallback
        try:
            msg = MIMEMultipart()
            msg["From"] = f"{settings.EMAILS_FROM_NAME} <{settings.EMAILS_FROM_EMAIL}>"
            msg["To"] = recipient
            msg["Subject"] = subject
            msg.attach(MIMEText(html, "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)

            logger.info(f"Email sikeresen kiküldve (SMTP) ide: {recipient}")
            return {"status": "success", "provider": "smtp"}
        except Exception as e:
            logger.error(f"SMTP Hiba: {str(e)}")
            return {"status": "error", "message": str(e)}

email_manager = EmailManager()