"""Mailbox helpers shared by the AI auto-reply agent and manual agent replies.

SMTP only *transmits* a message — it never files a copy in the mailbox's Sent
folder. Desktop mail clients do that themselves with an IMAP APPEND, which is
why a programmatically-sent reply reaches the customer but leaves Sent empty.

``save_to_sent`` performs that APPEND so the support mailbox reads like a real
person's: replies sit in Sent alongside the customer mail in Inbox.
"""
import imaplib
import re
import time

# Common Sent folder names, in the order we try them when the server does not
# advertise the \Sent special-use flag.
_SENT_CANDIDATES = (
    'INBOX.Sent', 'Sent', 'INBOX.Sent Items', 'Sent Items',
    'INBOX.Sent Messages', 'Sent Messages',
)

_LIST_RE = re.compile(r'^\((?P<flags>[^)]*)\)\s+"(?P<delim>[^"]*)"\s+(?P<name>.+)$')


def _connect(acct):
    if acct.imap_ssl:
        M = imaplib.IMAP4_SSL(acct.imap_host, int(acct.imap_port))
    else:
        M = imaplib.IMAP4(acct.imap_host, int(acct.imap_port))
    M.login(acct.imap_user or acct.email, acct.imap_pass)
    return M


def find_sent_folder(M):
    """Return the mailbox's Sent folder name, or None."""
    # 1. Ask the server which folder is flagged \Sent (RFC 6154 special-use).
    try:
        typ, data = M.list()
        if typ == 'OK':
            for raw in data or []:
                line = raw.decode('utf-8', 'replace') if isinstance(raw, bytes) else str(raw)
                m = _LIST_RE.match(line.strip())
                if m and '\\Sent' in m.group('flags'):
                    return m.group('name').strip().strip('"')
    except Exception:
        pass

    # 2. Fall back to the usual names — SELECT proves the folder exists.
    for cand in _SENT_CANDIDATES:
        try:
            typ, _ = M.select(f'"{cand}"', readonly=True)
            if typ == 'OK':
                return cand
        except Exception:
            continue
    return None


def save_to_sent(acct, raw_message, when=None):
    """Append an already-sent message to the account's Sent folder.

    Returns the folder name on success, or None. Never raises: the customer has
    already received the email, so a filing failure must not break the caller.
    """
    M = None
    try:
        M = _connect(acct)
        folder = find_sent_folder(M)
        if not folder:
            return None
        if isinstance(raw_message, str):
            raw_message = raw_message.encode('utf-8')
        stamp = imaplib.Time2Internaldate(when or time.time())
        # \Seen so it doesn't show as an unread message to the mailbox owner.
        typ, _ = M.append(f'"{folder}"', '\\Seen', stamp, raw_message)
        return folder if typ == 'OK' else None
    except Exception:
        return None
    finally:
        if M is not None:
            try:
                M.logout()
            except Exception:
                pass
