"""
Transactional email dispatch.

In development (SMTP_HOST not configured) emails are logged to console.
In production set SMTP_HOST / SMTP_PORT / SMTP_USER / SMTP_PASSWORD / EMAIL_FROM.
"""
import asyncio
import logging
import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.utils import parseaddr

from src.core.config import settings

logger = logging.getLogger(__name__)


async def send_welcome_email(
    to: str,
    first_name: str,
    organization_name: str,
    workspace_url: str,
    temp_password: str,
) -> None:
    """Dispatch the post-signup welcome email.

    Contains workspace URL, login email, and temporary password.
    Plain-text password is sent ONLY in this email — never stored in plaintext,
    never returned in API responses.
    """
    subject = f"Your INDELIS workspace is ready \u2014 {organization_name}"
    login_url = f"{workspace_url}/login"

    body_text = (
        f"Hi {first_name},\n\n"
        f"Your INDELIS workspace has been created. Here are your login details:\n\n"
        f"  Workspace URL:  {workspace_url}\n"
        f"  Email:          {to}\n"
        f"  Temp password:  {temp_password}\n\n"
        f"Log in now: {login_url}\n\n"
        f"You will be prompted to change your password on first login.\n\n"
        f"Questions? Reply to this email or call 1-800-INDELIS (Mon\u2013Fri, 9\u20135 ET).\n\n"
        f"\u2014 The INDELIS Team\n"
    )

    body_html = f"""<!DOCTYPE html>
<html>
<body style="font-family:sans-serif;line-height:1.6;color:#1a1a1a;max-width:560px;margin:auto;padding:24px">
  <h2 style="color:#2563eb">Your INDELIS workspace is ready</h2>
  <p>Hi {first_name},</p>
  <p>Your INDELIS workspace for <strong>{organization_name}</strong> has been created.</p>
  <table style="border-collapse:collapse;width:100%;margin:16px 0">
    <tr><td style="padding:8px;background:#f3f4f6;font-weight:600;width:40%">Workspace URL</td>
        <td style="padding:8px"><a href="{workspace_url}">{workspace_url}</a></td></tr>
    <tr><td style="padding:8px;background:#f3f4f6;font-weight:600">Email</td>
        <td style="padding:8px">{to}</td></tr>
    <tr><td style="padding:8px;background:#f3f4f6;font-weight:600">Temp password</td>
        <td style="padding:8px;font-family:monospace">{temp_password}</td></tr>
  </table>
  <p>
    <a href="{login_url}"
       style="display:inline-block;background:#2563eb;color:#fff;padding:12px 24px;
              border-radius:6px;text-decoration:none;font-weight:600">
      Log in to your workspace &rarr;
    </a>
  </p>
  <p style="color:#6b7280;font-size:13px">
    You will be prompted to change your password on first login.
  </p>
  <p style="color:#6b7280;font-size:13px">
    Questions? Reply to this email or call 1-800-INDELIS (Mon&ndash;Fri, 9&ndash;5 ET).
  </p>
  <p style="color:#6b7280;font-size:13px">&mdash; The INDELIS Team</p>
</body>
</html>"""

    if not settings.SMTP_HOST:
        # Development / test — log instead of sending
        logger.info(
            "[EMAIL-DEV] To=%s | Subject=%s | Workspace=%s | Password=REDACTED",
            to,
            subject,
            workspace_url,
        )
        return

    def _send_sync() -> None:
        msg = MIMEMultipart("alternative")
        msg["Subject"] = subject
        msg["From"] = settings.EMAIL_FROM
        msg["To"] = to
        msg.attach(MIMEText(body_text, "plain", "utf-8"))
        msg.attach(MIMEText(body_html, "html", "utf-8"))

        with smtplib.SMTP(settings.SMTP_HOST, settings.SMTP_PORT) as smtp:
            smtp.ehlo()
            smtp.starttls()
            smtp.ehlo()
            if settings.SMTP_USER:
                smtp.login(settings.SMTP_USER, settings.SMTP_PASSWORD)
            _, from_addr = parseaddr(settings.EMAIL_FROM)
            smtp.sendmail(from_addr or settings.EMAIL_FROM, to, msg.as_string())

    loop = asyncio.get_event_loop()
    await loop.run_in_executor(None, _send_sync)
