"""Sending email through the company's own mail server (SMTP), with PDF attachments, and logging every message."""
import re
import smtplib
import ssl
from email.message import EmailMessage
from email.utils import formataddr, make_msgid

from flask import current_app

from .db import x
from .i18n import t
from .ledger import AccountingError, company, now

EMAIL = re.compile(r"^[^@\s,;]+@[^@\s,;]+\.[^@\s,;]+$")


def addresses(text):
    """'a@x.com; b@y.com' -> ['a@x.com', 'b@y.com'], refusing anything that is not an address."""
    out = [a.strip() for a in re.split(r"[,;\s]+", text or "") if a.strip()]
    bad = [a for a in out if not EMAIL.match(a)]
    if bad:
        raise AccountingError(f"{t('Not a valid email address')}: {', '.join(bad)}")
    return out


def configured():
    if current_app.config.get("MAIL_OUTBOX") is not None:
        return True
    c = company()
    return bool(c["smtp_host"] and c["mail_from"])


def send(to, subject, body, attachments=(), cc="", kind="other", model=None, record_id=None, partner_id=None,
         user_id=None):
    """attachments: [(filename, bytes, mime type)]. Logs the result; raises AccountingError when it fails."""
    c = company()
    to_list, cc_list = addresses(to), addresses(cc)
    if not to_list:
        raise AccountingError(t("Enter at least one email address."))
    msg = EmailMessage()
    msg["From"] = formataddr((c["mail_from_name"] or c["name_en"], c["mail_from"] or ""))
    msg["To"] = ", ".join(to_list)
    if cc_list:
        msg["Cc"] = ", ".join(cc_list)
    msg["Subject"] = subject
    msg["Message-ID"] = make_msgid(domain=(c["mail_from"] or "vertex.local").split("@")[-1])
    msg.set_content(body)
    for name, data, mime in attachments:
        main, sub = mime.split("/", 1)
        msg.add_attachment(data, maintype=main, subtype=sub, filename=name)
    bcc = addresses(c["mail_bcc"]) if c["mail_bcc"] else []
    error = None
    try:
        outbox = current_app.config.get("MAIL_OUTBOX")
        if outbox is not None:          # tests and demos: keep the message instead of sending it
            outbox.append(msg)
        else:
            _deliver(c, msg, to_list + cc_list + bcc)
    except AccountingError as e:
        error = str(e)
    except (smtplib.SMTPException, OSError) as e:
        error = f"{t('The mail server refused the message')}: {e}"
    x("INSERT INTO email_log (kind, model, record_id, partner_id, to_addr, cc, subject, attachment, state, error, sent_by, "
      "sent_at) VALUES (?,?,?,?,?,?,?,?,?,?,?,?)",
      (kind, model, record_id, partner_id, ", ".join(to_list), ", ".join(cc_list), subject,
       ", ".join(a[0] for a in attachments), "failed" if error else "sent", error, user_id, now()))
    if error:
        raise AccountingError(error)


def _deliver(c, msg, recipients):
    if not (c["smtp_host"] and c["mail_from"]):
        raise AccountingError(t("Set up the outgoing mail server in Company settings first."))
    port = c["smtp_port"] or (465 if c["smtp_security"] == "ssl" else 587 if c["smtp_security"] == "starttls" else 25)
    context = ssl.create_default_context()
    if c["smtp_security"] == "ssl":
        server = smtplib.SMTP_SSL(c["smtp_host"], port, timeout=20, context=context)
    else:
        server = smtplib.SMTP(c["smtp_host"], port, timeout=20)
    try:
        if c["smtp_security"] == "starttls":
            server.starttls(context=context)
        if c["smtp_user"]:
            server.login(c["smtp_user"], c["smtp_password"] or "")
        server.send_message(msg, to_addrs=recipients)
    finally:
        try:
            server.quit()
        except (smtplib.SMTPException, OSError):
            pass
