// DewLink LinkedIn engine entry — spawned per LinkedIn account by the macOS app.
// Mirrors main.ts: emits @@DEWLINK@@ events on stdout, reads newline-JSON commands on stdin.
//
// Commands:
//   {"cmd":"sync"}                                  → re-scan messaging into the inbox
//   {"cmd":"draft","threadId":"...","text":"..."}   → place a DRAFT in a thread (never sends)
//
// Draft-only by design (hard wall #1). Login is performed by the user in a headful Chrome window.

import readline from "node:readline";
import { startLinkedIn, placeDraft, type LinkedInSession } from "./linkedin.ts";
import { emitEvent } from "./events.ts";
import { errorMessage } from "./sendAck.ts";

async function main() {
  let session: LinkedInSession | null = null;
  try {
    session = await startLinkedIn();
  } catch (err: any) {
    emitEvent({ type: "log", level: "error", msg: `linkedin init failed: ${err?.message}` });
    process.exit(1);
  }

  const rl = readline.createInterface({ input: process.stdin });
  rl.on("line", async (line) => {
    const trimmed = line.trim();
    if (!trimmed || !session) return;
    try {
      const cmd = JSON.parse(trimmed);
      if (cmd.cmd === "draft" && cmd.threadId && typeof cmd.text === "string") {
        const placed = await placeDraft(session.page, cmd.threadId, cmd.text);
        emitEvent({
          type: "sendAck",
          draftId: typeof cmd.draftId === "string" ? cmd.draftId : undefined,
          providerMsgId: placed ? `li:placed:${cmd.threadId}` : undefined,
          status: placed ? "placed" : "failed",
          error: placed ? undefined : "LinkedIn draft was not placed",
        });
      } else if (cmd.cmd === "sync") {
        // Reconnect path: re-run the start flow's sync by reloading messaging.
        emitEvent({ type: "log", level: "info", msg: "[linkedin] manual sync requested" });
        const again = await startLinkedIn();
        if (again) session = again;
      }
    } catch (err: any) {
      emitEvent({ type: "log", level: "error", msg: `bad command: ${err?.message}` });
      try {
        const cmd = JSON.parse(trimmed);
        if (typeof cmd?.draftId === "string") {
          emitEvent({ type: "sendAck", draftId: cmd.draftId, status: "failed", error: errorMessage(err) });
        }
      } catch {}
    }
  });

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

function shutdown() {
  process.exit(0);
}
process.on("SIGINT", shutdown);
process.on("SIGTERM", shutdown);

main().catch((error) => {
  emitEvent({ type: "log", level: "error", msg: `linkedin fatal: ${error?.message}` });
  process.exit(1);
});
