#!/usr/bin/env node

const WebSocket = require("ws");

const port = Number(process.env.MOCK_NEMOTRON_PORT || 8765);
const transcript =
  process.env.MOCK_NEMOTRON_TRANSCRIPT ||
  "hello from the mock nemotron sidecar";

const server = new WebSocket.Server({ host: "127.0.0.1", port });

server.on("connection", (socket) => {
  let binaryChunks = 0;
  let finalSent = false;

  socket.on("message", (data, isBinary) => {
    if (!isBinary) {
      let message = null;
      try {
        message = JSON.parse(data.toString("utf8"));
      } catch (_) {
        socket.send(JSON.stringify({ type: "error", error: "Invalid JSON" }));
        return;
      }

      if (message.type === "start") {
        socket.send(JSON.stringify({ type: "ready" }));
      }
      return;
    }

    binaryChunks += 1;

    if (binaryChunks === 1) {
      socket.send(
        JSON.stringify({
          type: "partial",
          text: transcript.split(" ").slice(0, 3).join(" "),
        }),
      );
    }

    if (!finalSent && binaryChunks >= 5) {
      finalSent = true;
      socket.send(JSON.stringify({ type: "final", text: transcript }));
    }
  });
});

server.on("listening", () => {
  console.log(
    `Mock Nemotron sidecar listening on ws://127.0.0.1:${port}/v1/asr/stream`,
  );
});

server.on("error", (error) => {
  console.error("Mock Nemotron sidecar error:", error);
  process.exitCode = 1;
});

function shutdown() {
  server.close(() => process.exit(0));
}

process.on("SIGINT", shutdown);
process.on("SIGTERM", shutdown);
