import { runAppleScript, escapeForAppleScript, withLaunch, FIELD_SEP } from "../lib/applescript.js";
export async function readMessage(account, mailbox, messageId) {
const acct = escapeForAppleScript(account);
const mbox = escapeForAppleScript(mailbox);
const msgId = escapeForAppleScript(messageId);
const script = withLaunch("Mail", tell application "Mail" set msgs to (messages of mailbox "${mbox}" of account "${acct}" whose message id is "${msgId}") if (count of msgs) is 0 then return "NOT_FOUND" end if set m to item 1 of msgs set toRecips to "" try repeat with r in to recipients of m try set toRecips to toRecips & address of r & "," end try end repeat end try set ccRecips to "" try repeat with r in cc recipients of m try set ccRecips to ccRecips & address of r & "," end try end repeat end try set mSubject to "" try set mSubject to subject of m as string if mSubject is "missing value" then set mSubject to "" end try set mSender to "" try set mSender to sender of m as string if mSender is "missing value" then set mSender to "" end try set mDate to "" try set mDate to (date received of m) as string end try set mContent to "" try set mContent to content of m as string if mContent is "missing value" then set mContent to "" end try return mSubject & "${FIELD_SEP}" & mSender & "${FIELD_SEP}" & toRecips & "${FIELD_SEP}" & ccRecips & "${FIELD_SEP}" & mDate & "${FIELD_SEP}" & mContent end tell);
const raw = await runAppleScript(script);
if (raw === "NOT_FOUND") {
return null;
}
const parts = raw.split(FIELD_SEP);
return {
subject: (parts[0] ?? "").trim(),
sender: (parts[1] ?? "").trim(),
to: (parts[2] ?? "").trim().split(",").filter(Boolean),
cc: (parts[3] ?? "").trim().split(",").filter(Boolean),
dateReceived: (parts[4] ?? "").trim(),
body: (parts[5] ?? "").trim(),
};
}