// DewLink SMS (Twilio) engine entry — spawned per Twilio number by the macOS app.
// Emits @@DEWLINK@@ events on stdout; reads newline-JSON commands on stdin.
//   {"cmd":"send","chatId":"<recipient phone>","text":"..."}

import readline from "node:readline";
import { startTwilio, sendTwilio } from "./twilio.ts";
import { emitEvent } from "./events.ts";
import { emitOutboundMessage, errorMessage, sendWithAck, twilioProviderMsgId } from "./sendAck.ts";

async function main() {
  try {
    await startTwilio();
  } catch (err: any) {
    emitEvent({ type: "log", level: "error", msg: `twilio 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, () => sendTwilio(cmd.chatId, cmd.text), twilioProviderMsgId);
          emitOutboundMessage({
            convExternalId: String(cmd.chatId),
            convTitle: String(cmd.chatId),
            body: cmd.text,
            sender: process.env.TWILIO_FROM || null,
            providerMsgId: sent.providerMsgId,
          });
          emitEvent({ type: "log", level: "info", msg: `[sms] sent to ${cmd.chatId}` });
        } catch (err: any) {
          emitEvent({ type: "log", level: "error", msg: `[sms] 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: `twilio fatal: ${e?.message}` }); process.exit(1); });
