"""Helper notificare email admin la signup.

Livrare DEGRADATA: daca smtp_host nu e configurat, functia e no-op (log doar).
Orice eroare SMTP e prinsa si logata — signup-ul NU e blocat niciodata.
"""

from __future__ import annotations

import smtplib
import textwrap
from email.message import EmailMessage

from .config import get_settings
from .observ import log_event


def notify_signup(admin_emails: list[str], account_id: int, email: str) -> None:
    """Notifica adminii despre un cont nou in asteptare (best-effort).

    Daca smtp_host e None SAU admin_emails e gol -> log si return (degradat).
    Daca SMTP ridica exceptie -> log eroare si return (NU se propaga).
    Timeout mic (5s) pe conexiunea SMTP.
    """
    settings = get_settings()

    if not settings.smtp_host or not admin_emails:
        log_event(
            "signup_notify_degradat",
            account_id=account_id,
            mesaj="fara SMTP configurat",
            context={"admins": len(admin_emails)},
        )
        return

    try:
        msg = EmailMessage()
        expeditor = settings.smtp_from or settings.smtp_user or "autopass@localhost"
        msg["From"] = expeditor
        msg["To"] = ", ".join(admin_emails)
        msg["Subject"] = f"AutoPass: cont nou {account_id} in asteptare"
        msg.set_content(textwrap.dedent(f"""\
            Cont nou inregistrat si in asteptare de activare.

            ID cont: {account_id}
            Email: {email}

            Actioneaza din panoul admin /admin sau din CLI:
              python3 -m tools.account activate --account {account_id}
        """))

        with smtplib.SMTP(settings.smtp_host, settings.smtp_port, timeout=5) as smtp:
            if settings.smtp_user and settings.smtp_password:
                smtp.starttls()
                smtp.login(settings.smtp_user, settings.smtp_password)
            smtp.send_message(msg)

    except Exception as exc:
        print(
            f"SIGNUP-NOTIFY esuat cont={account_id}: {type(exc).__name__}",
            flush=True,
        )
