// DewLink Email engine entry — spawned per email account by the macOS app.
// Mirrors main.ts: emits @@DEWLINK@@ events on stdout, reads newline-JSON commands on stdin.
//   {"cmd":"send","chatId":"<recipient email>","text":"...","subject":"..."}

import readline from "node:readline";
import { startEmail, sendEmail } from "./email.ts";
import { emitEvent } from "./events.ts";
import { emailProviderMsgId, emitOutboundMessage, errorMessage, sendWithAck } from "./sendAck.ts";

async function main() {
  try {
    await startEmail();
  } catch (err: any) {
    emitEvent({ type: "log", level: "error", msg: `email init failed: ${err?.message}` });
  }

  const rl = readline.createInterface({ input: process.stdin });
  rl.on("line", async (line) => {
    const trimmed = line.trim();
    if (!trimmed) return;
    try {
      const cmd = JSON.parse(trimmed);
      if (cmd.cmd === "send" && cmd.chatId && typeof cmd.text === "string") {
        try {
          const sent = await sendWithAck(cmd, () => sendEmail(cmd.chatId, cmd.text, cmd.subject), emailProviderMsgId);
          const subject = typeof cmd.subject === "string" && cmd.subject.trim() ? cmd.subject.trim() : "Re:";
          emitOutboundMessage({
            convExternalId: String(cmd.chatId).toLowerCase(),
            convTitle: String(cmd.chatId),
            body: `${subject}\n${cmd.text}`,
            sender: process.env.EMAIL_USER || null,
            providerMsgId: sent.providerMsgId,
          });
          emitEvent({ type: "log", level: "info", msg: `[email] sent to ${cmd.chatId}` });
        } catch (err: any) {
          emitEvent({ type: "log", level: "error", msg: `[email] send failed: ${errorMessage(err)}` });
        }
      }
    } catch (err: any) {
      emitEvent({ type: "log", level: "error", msg: `bad command: ${err?.message}` });
    }
  });

  emitEvent({ type: "ready" });
}

process.on("SIGINT", () => process.exit(0));
process.on("SIGTERM", () => process.exit(0));
main().catch((e) => { emitEvent({ type: "log", level: "error", msg: `email fatal: ${e?.message}` }); process.exit(1); });
