"""Sending mail out through a client's own mailbox.

Every outbound message in the CRM — a reply on a ticket, or a fresh email an
agent composes — leaves through the same function here. It used to be inline in
``tickets.views.send_email``; the composer under Clients -> Users / Agents needed
the identical logic, and a second copy would have meant the port-465 transport
fix (below) eventually being right in one place and wrong in the other.

Two details that are easy to get wrong and expensive to debug:

  * Port 465 is *implicit* SSL and needs ``SMTP_SSL``. Calling ``starttls()`` on
    it is the classic "the reply never sends and nobody knows why" bug.
  * SMTP alone leaves the mailbox's Sent folder empty, so the client looks in
    webmail and cannot see what their agent sent. We IMAP-APPEND a copy.
"""

import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.utils import make_msgid, formataddr


def _addr_list(value):
    """Split a comma/semicolon separated address string into a clean list."""
    if not value:
        return []
    if isinstance(value, (list, tuple)):
        raw = value
    else:
        raw = str(value).replace(';', ',').split(',')
    return [a.strip() for a in raw if a and a.strip()]


def build_message(acct, to, subject, body, cc=None, in_reply_to=None, from_name=None):
    """Build the MIME message. Returns ``(msg, message_id, recipients)``.

    ``from_name`` lets an agent's own name appear on the message while the
    address stays the client's shared mailbox — so a customer replying still
    lands back in a mailbox the CRM ingests, not in a personal inbox.
    """
    to_list = _addr_list(to)
    cc_list = _addr_list(cc)

    msg = MIMEMultipart('alternative')
    msg['Subject'] = subject
    msg['From'] = formataddr((from_name or acct.name, acct.email))
    msg['To'] = ', '.join(to_list)
    if cc_list:
        msg['Cc'] = ', '.join(cc_list)
    msg['Reply-To'] = acct.email

    message_id = make_msgid(domain=(acct.email.split('@')[-1] or None))
    msg['Message-ID'] = message_id
    if in_reply_to:
        msg['In-Reply-To'] = in_reply_to
        msg['References'] = in_reply_to

    msg.attach(MIMEText(body, 'plain', 'utf-8'))
    html_body = body.replace('\n', '<br>')
    msg.attach(MIMEText(
        f'<div style="font-family:sans-serif;font-size:14px;line-height:1.6">{html_body}</div>',
        'html', 'utf-8',
    ))
    return msg, message_id, to_list + cc_list


def send_outbound_email(acct, to, subject, body, cc=None, in_reply_to=None,
                        from_name=None, save_sent=True):
    """Send one message through ``acct``'s SMTP. Returns the Message-ID.

    Raises on failure — callers turn the exception into a 400 and, for the
    composer, record it on the OutboundEmail row so the agent sees why.
    """
    msg, message_id, recipients = build_message(
        acct, to, subject, body, cc=cc, in_reply_to=in_reply_to, from_name=from_name,
    )
    if not recipients:
        raise ValueError('No recipient address.')

    raw = msg.as_string()
    port = int(acct.smtp_port)
    if port == 465:
        server = smtplib.SMTP_SSL(acct.smtp_host, port, timeout=20)
    else:
        server = smtplib.SMTP(acct.smtp_host, port, timeout=20)
        if acct.smtp_tls:
            server.starttls()
    try:
        server.login(acct.smtp_user or acct.email, acct.smtp_pass)
        server.sendmail(acct.email, recipients, raw)
    finally:
        try:
            server.quit()
        except Exception:
            pass

    if save_sent:
        # A mailbox that rejects APPEND must not fail a message already
        # delivered to the customer.
        try:
            from core.mailbox import save_to_sent
            save_to_sent(acct, raw)
        except Exception:
            pass

    return message_id
