"""SMTP email delivery via SSL (port 465)."""

from __future__ import annotations

import smtplib
from datetime import datetime, timezone
from email.mime.text import MIMEText

from ._config import ScheduledEmailConfig


def send_notification(
    cfg: ScheduledEmailConfig,
    *,
    login_url: str,
    raw_secret: str,
    rotate_at: datetime | None = None,
) -> None:
    """Send an email containing the current login link and metadata.

    Raises on SMTP failure so the caller can decide whether to retry.
    """
    now = datetime.now(timezone.utc)
    rotate_label = (rotate_at or now).strftime("%Y-%m-%d %H:%M:%S UTC")

    secret_display = "***masked***" if cfg.mask_secret else raw_secret

    body = (
        f"=== 免登录密钥通知 ===\n\n"
        f"轮换时间：{rotate_label}\n"
        f"SCT：{cfg.sct}\n"
        f"原始密钥：{secret_display}\n\n"
        f"免登录链接：\n{login_url}\n\n"
        f"--- 此邮件由系统自动发送 ---\n"
    )

    msg = MIMEText(body, "plain", "utf-8")
    msg["Subject"] = f"免登录密钥已轮换 - {rotate_label}"
    msg["From"] = cfg.smtp_user
    msg["To"] = cfg.recipient

    with smtplib.SMTP_SSL(cfg.smtp_host, cfg.smtp_port, timeout=30) as srv:
        srv.login(cfg.smtp_user, cfg.smtp_pass)
        srv.sendmail(cfg.smtp_user, [cfg.recipient], msg.as_string())
