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

import readline from "node:readline";
import { startTelegram, sendTelegram, reactTelegram } from "./telegram.ts";
import { emitEvent } from "./events.ts";
import { emitOutboundMessage, errorMessage, sendWithAck, telegramProviderMsgId } from "./sendAck.ts";

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