"""
Optional SMTP summary email after scan_recent completes.
Configure via environment variables (see .env.example); disabled if unset or SMTP_REPORT_ENABLED=false.
"""
import logging
import os
import smtplib
import ssl
from email.mime.text import MIMEText
from typing import List, Optional

logger = logging.getLogger(__name__)


def _truthy(val: Optional[str]) -> bool:
    if val is None:
        return False
    return val.strip().lower() in ("1", "true", "yes", "on")


def _falsy(val: Optional[str]) -> bool:
    if val is None or val.strip() == "":
        return False
    return val.strip().lower() in ("0", "false", "no", "off")


def smtp_summary_enabled() -> bool:
    """True when email should be sent (all required vars set and not explicitly disabled)."""
    if _falsy(os.getenv("SMTP_REPORT_ENABLED")):
        return False
    required = (
        os.getenv("SMTP_REPORT_HOST", "").strip(),
        os.getenv("SMTP_REPORT_TO", "").strip(),
        os.getenv("SMTP_REPORT_USER", "").strip(),
        os.getenv("SMTP_REPORT_PASSWORD", "").strip(),
    )
    return all(required)


def _recipients() -> List[str]:
    raw = os.getenv("SMTP_REPORT_TO", "")
    return [x.strip() for x in raw.split(",") if x.strip()]


def send_scan_summary_email(subject: str, body: str) -> None:
    """
    Send plain-text email. Raises on failure; caller should catch and log.
    """
    host = os.environ["SMTP_REPORT_HOST"].strip()
    port = int(os.environ.get("SMTP_REPORT_PORT", "587").strip() or "587")
    user = os.environ["SMTP_REPORT_USER"].strip()
    password = os.environ["SMTP_REPORT_PASSWORD"]
    from_addr = (os.getenv("SMTP_REPORT_FROM") or user).strip()
    to_addrs = _recipients()
    if not to_addrs:
        raise ValueError("SMTP_REPORT_TO has no recipients")

    msg = MIMEText(body, "plain", "utf-8")
    msg["Subject"] = subject
    msg["From"] = from_addr
    msg["To"] = ", ".join(to_addrs)

    use_ssl = _truthy(os.getenv("SMTP_REPORT_USE_SSL")) or port == 465
    starttls = not use_ssl and not _falsy(os.getenv("SMTP_REPORT_STARTTLS"))

    context = ssl.create_default_context()
    if use_ssl:
        with smtplib.SMTP_SSL(host, port, context=context, timeout=60) as server:
            server.login(user, password)
            server.sendmail(from_addr, to_addrs, msg.as_string())
    else:
        with smtplib.SMTP(host, port, timeout=60) as server:
            server.ehlo()
            if starttls:
                server.starttls(context=context)
                server.ehlo()
            server.login(user, password)
            server.sendmail(from_addr, to_addrs, msg.as_string())

    logger.info("Sent scan summary email to %s", ", ".join(to_addrs))


def maybe_send_scan_summary_email(subject: str, body: str) -> None:
    """Send summary email if SMTP is configured; log and swallow errors."""
    if not smtp_summary_enabled():
        logger.debug("SMTP summary email skipped (not configured or disabled)")
        return
    try:
        send_scan_summary_email(subject, body)
    except Exception as e:
        logger.warning("Could not send scan summary email: %s", e)
