import { loadCredentials } from "../lib/credentials.js";
import { fetchRecent, MAX_LIMIT } from "../lib/imap.js";
import { getThreadInfo, stripAngleBrackets } from "../lib/graph.js";
export async function emailRead(params) {
    const result = await loadCredentials(params.accountId);
    if ("error" in result)
        throw new Error(result.error);
    const { config, password } = result.credentials;
    // Clamp limit to hard cap — silently, per spec
    const requestedLimit = Math.max(1, params.limit ?? 20);
    const limit = Math.min(requestedLimit, MAX_LIMIT);
    // Use agent address for TO filtering when alias is configured
    // Coerce empty string to undefined to avoid matching nothing silently
    const to = (params.to || undefined) ?? (config.agentAddress !== config.email ? config.agentAddress : undefined);
    const { messages, nextBeforeUid } = await fetchRecent(config, password, {
        limit,
        sender: params.sender,
        subjectPattern: params.subjectPattern,
        since: params.since ? new Date(params.since) : undefined,
        before: params.before ? new Date(params.before) : undefined,
        to,
        folder: params.folder,
        beforeUid: params.before_uid,
    });
    if (messages.length === 0) {
        const filters = [];
        if (params.sender)
            filters.push(`from: ${params.sender}`);
        if (params.subjectPattern)
            filters.push(`subject: ${params.subjectPattern}`);
        if (params.since)
            filters.push(`since: ${params.since}`);
        if (params.before)
            filters.push(`before: ${params.before}`);
        if (params.to)
            filters.push(`to: ${params.to}`);
        if (params.folder)
            filters.push(`folder: ${params.folder}`);
        return `No messages found${filters.length > 0 ? ` matching ${filters.join(", ")}` : ""}.`;
    }
    // Enrich with thread info from the graph (best-effort — failures return empty map)
    const messageIds = messages.map((m) => m.messageId).filter((id) => !!id);
    let threadMap = new Map();
    try {
        threadMap = await getThreadInfo(messageIds, params.accountId);
    }
    catch {
        // Thread enrichment is optional — continue without it
    }
    const lines = messages
        .map((m) => {
        let entry = `UID: ${m.uid}\nFrom: ${m.from}\nSubject: ${m.subject}\nDate: ${m.date}`;
        if (m.messageId)
            entry += `\nMessage-ID: ${m.messageId}`;
        if (m.inReplyTo)
            entry += `\nIn-Reply-To: ${m.inReplyTo}`;
        const normalisedMid = stripAngleBrackets(m.messageId);
        if (normalisedMid) {
            const thread = threadMap.get(normalisedMid);
            if (thread) {
                entry += `\nThread-Depth: ${thread.threadDepth}`;
                entry += `\nThread-ID: ${thread.threadId}`;
            }
        }
        if (m.bodyPreview)
            entry += `\n\n${m.bodyPreview}`;
        return entry + "\n---";
    })
        .join("\n\n");
    if (nextBeforeUid) {
        return `${lines}\n\nPagination: next_before_uid=${nextBeforeUid} (pass as before_uid to get older messages)`;
    }
    return lines;
}
//# sourceMappingURL=email-read.js.map