# -*- coding: utf-8 -*-
"""
Notificare pe email cand un raspuns nou la chestionar este adaugat.

Foloseste smtplib (stdlib) cu SMTP-ul propriu al domeniului (ex. casuta
chestionare@alincurt.com de pe Namecheap/cPanel). Configurat prin variabile
de mediu. Trimiterea ruleaza pe un thread daemon si e in try/except, deci
NU blocheaza si NU strica trimiterea chestionarului daca emailul esueaza.

Variabile de mediu:
    MAIL_ENABLED   1 ca sa trimita (orice altceva = dezactivat, util local)
    SMTP_HOST      ex. mail.alincurt.com
    SMTP_PORT      465 (SSL) sau 587 (STARTTLS)
    SMTP_SSL       1 = SSL direct (465); 0 = STARTTLS (587)
    SMTP_USER      utilizatorul casutei (ex. chestionare@alincurt.com)
    SMTP_PASS      parola casutei
    MAIL_FROM      implicit = SMTP_USER
    MAIL_TO        implicit = chestionare@alincurt.com
    PUBLIC_URL     ex. https://alincurt.com (pentru linkul catre /admin)
"""
import os
import ssl
import smtplib
import logging
from email.message import EmailMessage

log = logging.getLogger("mailer")


def _env(name, default=""):
    return os.environ.get(name, default).strip()


def is_enabled():
    return _env("MAIL_ENABLED") == "1"


def _build_message(answers, form_name=""):
    # Notificare minima: doar ca un raspuns a fost adaugat (fara date despre client).
    subject = "Chestionar nou completat"
    if form_name:
        subject += " — [%s]" % form_name

    lines = ["A fost completat un chestionar nou."]
    if form_name:
        lines.append("Chestionar: %s" % form_name)
    public = _env("PUBLIC_URL")
    if public:
        lines += ["", "Vezi răspunsurile: %s/admin" % public.rstrip("/")]

    msg = EmailMessage()
    msg["Subject"] = subject
    msg["From"] = _env("MAIL_FROM") or _env("SMTP_USER")
    msg["To"] = _env("MAIL_TO") or "chestionare@alincurt.com"
    msg.set_content("\n".join(lines))
    return msg


def _send_sync(answers, form_name=""):
    try:
        if not is_enabled():
            return
        host = _env("SMTP_HOST")
        port = int(_env("SMTP_PORT") or "465")
        user = _env("SMTP_USER")
        password = _env("SMTP_PASS")
        if not (host and user and password):
            log.warning("SMTP neconfigurat complet; nu trimit email.")
            return

        msg = _build_message(answers, form_name)
        ctx = ssl.create_default_context()
        if _env("SMTP_SSL", "1") == "1":
            with smtplib.SMTP_SSL(host, port, context=ctx, timeout=15) as s:
                s.login(user, password)
                s.send_message(msg)
        else:
            with smtplib.SMTP(host, port, timeout=15) as s:
                s.starttls(context=ctx)
                s.login(user, password)
                s.send_message(msg)
        log.info("Email de notificare trimis catre %s", msg["To"])
    except Exception as exc:                       # niciodata nu propaga eroarea
        log.exception("Eroare la trimiterea emailului de notificare: %s", exc)


def send_new_submission(form, answers):
    """Trimite notificarea SINCRON (in timpul cererii).

    Pe Passenger/cPanel procesul e adesea suspendat imediat dupa raspuns, deci
    un thread de fundal nu apuca sa termine trimiterea. Trimiterea sincrona
    garanteaza ca emailul pleaca; e best-effort (erorile sunt prinse in
    `_send_sync`, deci nu afecteaza salvarea/raspunsul) si rapida (~1s).
    """
    if not is_enabled():
        return
    form_name = form.get("name", "") if isinstance(form, dict) else ""
    _send_sync(dict(answers), form_name)
