/** Deep-compare worker vs in-process envelopes to catch any field the
 *  structured-clone boundary drops/alters (suspected highlight regression). */
import fs from "node:fs";
import path from "node:path";
import os from "node:os";
import { MailxDB, Store, FileMessageStore } from "../packages/mailx-store/index.js";
import { spawnDbWorker } from "../packages/mailx-service/db-worker-client.js";

const liveDir = process.env.RMFMAIL_DIR || path.join(os.homedir(), ".rmfmail");
const tmp = fs.mkdtempSync(path.join(os.tmpdir(), "rmf-deep-"));
for (const s of ["", "-wal", "-shm"]) {
    const src = path.join(liveDir, "mailx.db" + s);
    if (fs.existsSync(src)) try { fs.copyFileSync(src, path.join(tmp, "mailx.db" + s)); } catch {}
}
const db = new MailxDB(tmp);
const store = new Store(db, new FileMessageStore(path.join(tmp, "store")));
const worker = await spawnDbWorker({ dbPath: tmp, storePath: path.join(tmp, "store") });

const ip = store.getUnifiedInbox(1, 10, false);
const wk = await worker.bus.request("db:getUnifiedInbox", { page: 1, pageSize: 10, flaggedOnly: false });

function describe(v) {
    if (v === null) return "null";
    if (v instanceof Date) return `Date(${v.getTime()})`;
    if (Array.isArray(v)) return `Array[${v.length}]`;
    return typeof v;
}
let mismatches = 0;
for (let i = 0; i < Math.min(ip.items.length, wk.items.length); i++) {
    const a = ip.items[i], b = wk.items[i];
    const keys = new Set([...Object.keys(a), ...Object.keys(b)]);
    for (const k of keys) {
        const sa = JSON.stringify(a[k]), sb = JSON.stringify(b[k]);
        if (sa !== sb) {
            mismatches++;
            console.log(`  item[${i}].${k}: in-proc=${describe(a[k])} ${sa}  ||  worker=${describe(b[k])} ${sb}`);
        }
    }
}
console.log(mismatches === 0
    ? `\n✓ ALL fields identical across ${ip.items.length} envelopes — highlighting is NOT a worker data issue`
    : `\n✗ ${mismatches} field mismatch(es) — likely the highlight cause`);

// Show which fields exist + the flags shape (unread highlight driver).
console.log("\nfields on envelope[0]:", Object.keys(ip.items[0] || {}).join(", "));
console.log("flags[0]:", JSON.stringify(ip.items[0]?.flags), "| unread driver candidates:",
    ["unread", "seen", "isRead", "flags"].filter(k => k in (ip.items[0] || {})).join(", "));

await worker.close();
try { fs.rmSync(tmp, { recursive: true, force: true }); } catch {}
process.exit(0);
