// DewLink Discord engine entry — spawned per Discord account by the macOS app.
// Emits @@DEWLINK@@ events on stdout; reads newline-JSON commands on stdin.
//   {"cmd":"send","chatId":"<discord channel id>","text":"..."}

import readline from "node:readline";
import { startDiscord, sendDiscord, reactDiscord } from "./discord.ts";
import { emitEvent } from "./events.ts";
import { discordProviderMsgId, emitOutboundMessage, errorMessage, sendWithAck } from "./sendAck.ts";

async function main() {
  try {
    await startDiscord();
  } catch (err: any) {
    emitEvent({ type: "log", level: "error", msg: `discord 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, () => sendDiscord(cmd.chatId, cmd.text), discordProviderMsgId);
          emitOutboundMessage({
            convExternalId: String(cmd.chatId),
            convTitle: String(cmd.chatId),
            body: cmd.text,
            providerMsgId: sent.providerMsgId,
          });
          emitEvent({ type: "log", level: "info", msg: `[discord] sent to ${cmd.chatId}` });
        } catch (err: any) {
          emitEvent({ type: "log", level: "error", msg: `[discord] send failed: ${errorMessage(err)}` });
        }
      } else if (cmd.cmd === "react" && cmd.chatId && cmd.messageId && typeof cmd.emoji === "string") {
        await reactDiscord(cmd.chatId, String(cmd.messageId), cmd.emoji);
        emitEvent({ type: "log", level: "info", msg: `[discord] reacted ${cmd.emoji}` });
      }
    } 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: `discord fatal: ${e?.message}` }); process.exit(1); });
