import { ThrowsPromise } from "@livekit/throws-transformer/throws";
import { AccessToken } from "livekit-server-sdk";
import { WebSocket } from "ws";
import { APIConnectionError, APIStatusError, APITimeoutError } from "../_exceptions.js";
import { getJobContext } from "../job.js";
import { version } from "../version.js";
const DEFAULT_INFERENCE_URL = "https://agent-gateway.livekit.cloud/v1";
const STAGING_INFERENCE_URL = "https://agent-gateway.staging.livekit.cloud/v1";
const INFERENCE_PROVIDER_HEADER = "X-LiveKit-Inference-Provider";
const INFERENCE_PRIORITY_HEADER = "X-LiveKit-Inference-Priority";
function getDefaultInferenceUrl() {
  const inferenceUrl = process.env.LIVEKIT_INFERENCE_URL;
  if (inferenceUrl) {
    return inferenceUrl;
  }
  const livekitUrl = process.env.LIVEKIT_URL || "";
  if (livekitUrl.includes(".staging.livekit.cloud")) {
    return STAGING_INFERENCE_URL;
  }
  return DEFAULT_INFERENCE_URL;
}
async function createAccessToken(apiKey, apiSecret, ttl = 600) {
  const token = new AccessToken(apiKey, apiSecret, { identity: "agent", ttl });
  token.addInferenceGrant({ perform: true });
  return await token.toJwt();
}
function buildMetadataHeaders() {
  var _a, _b;
  const headers = {
    "User-Agent": `livekit-agents-js/${version} (node ${process.version})`
  };
  const ctx = getJobContext(false);
  if (ctx) {
    const roomSid = (_a = ctx.job.room) == null ? void 0 : _a.sid;
    if (roomSid) {
      headers["X-LiveKit-Room-Id"] = roomSid;
    }
    if (ctx.job.id) {
      headers["X-LiveKit-Job-Id"] = ctx.job.id;
    }
    const workerToken = process.env.LIVEKIT_WORKER_TOKEN;
    if (workerToken) {
      headers["X-LiveKit-Worker-Token"] = workerToken;
    }
    const agentSid = (_b = ctx.agent) == null ? void 0 : _b.sid;
    if (ctx.room.isConnected && agentSid) {
      headers["X-LiveKit-Agent-Id"] = agentSid;
    }
  }
  return headers;
}
async function connectWs(url, headers, timeoutMs) {
  return new ThrowsPromise((resolve, reject) => {
    const socket = new WebSocket(url, { headers: { ...buildMetadataHeaders(), ...headers } });
    let opened = false;
    const timeout = setTimeout(() => {
      socket.terminate();
      reject(new APITimeoutError({ message: "Timeout connecting to LiveKit WebSocket" }));
    }, timeoutMs);
    const onOpen = () => {
      clearTimeout(timeout);
      opened = true;
      resolve(socket);
    };
    const onError = (err) => {
      clearTimeout(timeout);
      if (err && typeof err === "object" && "code" in err && err.code === 429) {
        reject(
          new APIStatusError({
            message: "LiveKit gateway quota exceeded",
            options: { statusCode: 429 }
          })
        );
      } else {
        reject(new APIConnectionError({ message: "Error connecting to LiveKit WebSocket" }));
      }
    };
    const onClose = () => {
      clearTimeout(timeout);
      if (!opened) {
        reject(
          new APIConnectionError({
            message: "Connection closed unexpectedly"
          })
        );
      }
    };
    socket.once("open", onOpen);
    socket.once("error", onError);
    socket.once("close", onClose);
  });
}
export {
  DEFAULT_INFERENCE_URL,
  INFERENCE_PRIORITY_HEADER,
  INFERENCE_PROVIDER_HEADER,
  STAGING_INFERENCE_URL,
  buildMetadataHeaders,
  connectWs,
  createAccessToken,
  getDefaultInferenceUrl
};
//# sourceMappingURL=utils.js.map