/**
 * IPC protocol — stdin/stdout JSON lines for Rust↔Node communication.
 * Rust launcher sends JSON requests, Node dispatches to core functions,
 * sends JSON responses back. Events pushed to stdout as well.
 *
 * Protocol:
 *   Request:  { "_action": "getMessages", "_cbid": "5", "accountId": "bobma", ... }
 *   Response: { "_type": "response", "_cbid": "5", "result": { ... } }
 *   Error:    { "_type": "error", "_cbid": "5", "error": "message" }
 *   Event:    { "_type": "event", "data": { "type": "folderCountsChanged", ... } }
 */
import * as readline from "node:readline";
import { dispatch, initialize, onEvent } from "./index.js";
export async function startIPC() {
    // Initialize core
    await initialize();
    // Push events to stdout
    onEvent((event) => {
        const line = JSON.stringify({ _type: "event", data: event });
        process.stdout.write(line + "\n");
    });
    // Read JSON lines from stdin
    const rl = readline.createInterface({ input: process.stdin, terminal: false });
    rl.on("line", async (line) => {
        let msg;
        try {
            msg = JSON.parse(line);
        }
        catch {
            return; // Skip malformed JSON
        }
        const { _action, _cbid, ...params } = msg;
        if (!_action || !_cbid)
            return;
        try {
            const result = await dispatch(_action, params);
            process.stdout.write(JSON.stringify({ _type: "response", _cbid, result }) + "\n");
        }
        catch (e) {
            process.stdout.write(JSON.stringify({ _type: "error", _cbid, error: e.message }) + "\n");
        }
    });
    rl.on("close", () => {
        console.error("IPC stdin closed, shutting down");
        process.exit(0);
    });
    console.error("IPC ready");
}
// If run directly, start IPC mode
if (import.meta.url === `file://${process.argv[1]}` || process.argv[1]?.endsWith("ipc.js")) {
    startIPC().catch(e => {
        console.error(`IPC startup error: ${e.message}`);
        process.exit(1);
    });
}
//# sourceMappingURL=ipc.js.map