// Usage: node connect.mjs <port> <bearer> <runs>
// Per run: mint a ws ticket, open /ws, send subscribeServerConfig, time the first snapshot chunk.
const [port, bearer, runs = "3"] = process.argv.slice(2);
const base = `http://127.0.0.1:${port}`;
for (let i = 0; i < Number(runs); i++) {
  const t0 = performance.now();
  const res = await fetch(`${base}/api/auth/websocket-ticket/rpc`, {
    method: "POST",
    headers: { authorization: `Bearer ${bearer}` },
  });
  if (!res.ok) throw new Error(`ticket ${res.status} ${await res.text()}`);
  const { ticket } = await res.json();
  const ws = new WebSocket(`ws://127.0.0.1:${port}/ws?orchestrationProtocol=2&wsTicket=${encodeURIComponent(ticket)}`);
  const ms = await new Promise((resolve, reject) => {
    ws.onopen = () =>
      ws.send(JSON.stringify({ _tag: "Request", id: "1", tag: "subscribeServerConfig", payload: {}, headers: [] }));
    ws.onerror = (e) => reject(new Error(`ws error ${e.message ?? ""}`));
    ws.onmessage = (m) => {
      const text = String(m.data);
      for (const line of text.split("\n").filter(Boolean)) {
        const msg = JSON.parse(line);
        if (msg._tag === "Chunk" || (msg._tag === "Exit")) {
          const snap = msg.values?.[0];
          resolve({ ms: Math.round(performance.now() - t0), tag: msg._tag, type: snap?.type,
            directEndpoints: snap?.config?.directEndpoints, remoteOpenTargets: snap?.config?.remoteOpenTargets,
            exit: msg._tag === "Exit" ? JSON.stringify(msg.exit).slice(0, 300) : undefined });
        }
      }
    };
  });
  ws.close();
  console.log(`run ${i + 1}: first subscribeServerConfig chunk after ${ms.ms} ms`, JSON.stringify({ ...ms, ms: undefined }));
}
