import { createHash } from "node:crypto";
import { readFileSync } from "node:fs";
import { basename } from "node:path";
export function emailNormaliser(input) {
    const { filePath, accountId } = input;
    if (!accountId || !accountId.trim()) {
        throw new Error("email: accountId is required.");
    }
    const rawBytes = readFileSync(filePath);
    const archiveSha256 = createHash("sha256").update(rawBytes).digest("hex");
    let raw;
    try {
        raw = JSON.parse(rawBytes.toString("utf-8"));
    }
    catch (err) {
        throw new Error(`email: JSON parse failed — ${err instanceof Error ? err.message : String(err)}. file=${filePath}`);
    }
    if (!Array.isArray(raw)) {
        throw new Error(`email: expected top-level JSON array of message envelopes. file=${filePath}`);
    }
    let parseErrors = 0;
    const records = [];
    for (const m of raw) {
        const iso = parseDateHeader(m?.date);
        const email = m?.from?.email?.trim();
        const name = m?.from?.name?.trim() || email || "";
        const bodyText = m?.bodyText ?? "";
        if (!iso || !email) {
            parseErrors += 1;
            continue;
        }
        const senderPrefix = `From: ${name} <${email}>`;
        records.push({ iso, body: `${senderPrefix}\n${bodyText}` });
    }
    records.sort((a, b) => (a.iso < b.iso ? -1 : a.iso > b.iso ? 1 : 0));
    const parsedLines = records.map((r, i) => ({
        dateSent: r.iso,
        body: r.body,
        sequenceIndex: i,
    }));
    return {
        parsedLines,
        archiveSha256,
        archiveSourceFile: basename(filePath),
        counters: {
            parsed: parsedLines.length,
            systemSkipped: 0,
            mediaSkipped: 0,
            parseErrors,
        },
    };
}
function parseDateHeader(value) {
    if (!value || !value.trim())
        return null;
    const ms = Date.parse(value);
    if (!Number.isFinite(ms))
        return null;
    return new Date(ms).toISOString();
}
//# sourceMappingURL=email.js.map