import { loadCredentials, readPollState } from "../lib/credentials.js";
import { fetchSinceUid } from "../lib/imap.js";
import { putBatch } from "../lib/ingest-batch.js";
/**
 * List new inbox messages since a UID high-water mark, without writing to
 * the graph. Caches the batch in-memory so a follow-up email-ingest call
 * can apply operator decisions.
 *
 * No classification, no embeddings, no graph writes. The operator triages
 * by eye from the returned summary.
 */
export async function emailFetch(params) {
    const credResult = await loadCredentials(params.accountId);
    if ("error" in credResult)
        throw new Error(credResult.error);
    const { config, password } = credResult.credentials;
    const pollState = await readPollState(params.accountId);
    const sinceUid = params.since_uid ?? pollState?.lastFetchedUid ?? 0;
    const { uidValidity, emails, maxUid } = await fetchSinceUid(config, password, sinceUid, config.agentAddress);
    console.error(`[email-fetch] tag=email-fetch listed=${emails.length} sinceUid=${sinceUid}`);
    if (emails.length === 0) {
        return `No new messages since UID ${sinceUid}.`;
    }
    // Stash for the follow-up email-ingest call.
    putBatch(params.accountId, {
        uidValidity,
        maxUid,
        recipientAddress: config.agentAddress,
        messages: emails,
    });
    const lines = emails.map((m) => {
        const header = [
            `UID: ${m.uid}`,
            `Message-ID: ${m.messageId ?? "(missing)"}`,
            `From: ${m.fromName ? `${m.fromName} <${m.fromAddress}>` : m.fromAddress}`,
            `Subject: ${m.subject}`,
            `Date: ${m.date}`,
        ].join("\n");
        const body = m.bodyPreview ? `\n\n${m.bodyPreview}` : "";
        const attachLine = m.attachments.length > 0
            ? `\n\nAttachments (${m.attachments.length}): ${m.attachments
                .map((a) => `${a.filename} (${a.mimeType}, ${a.sizeBytes} bytes)`)
                .join("; ")}`
            : "";
        return `${header}${body}${attachLine}\n---`;
    }).join("\n\n");
    const footer = [
        "",
        `Listed ${emails.length} new message(s) since UID ${sinceUid}. Nothing has been written to the graph.`,
        `Call email-ingest with a disposition ("ingest" or "discard") for every Message-ID above to apply the operator's decisions.`,
    ].join("\n");
    return `${lines}\n${footer}`;
}
//# sourceMappingURL=email-fetch.js.map