"use strict";
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __export = (target, all) => {
  for (var name in all)
    __defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
  if (from && typeof from === "object" || typeof from === "function") {
    for (let key of __getOwnPropNames(from))
      if (!__hasOwnProp.call(to, key) && key !== except)
        __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
  }
  return to;
};
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
var otel_http_exporter_exports = {};
__export(otel_http_exporter_exports, {
  SimpleOTLPHttpLogExporter: () => SimpleOTLPHttpLogExporter
});
module.exports = __toCommonJS(otel_http_exporter_exports);
var import_api_logs = require("@opentelemetry/api-logs");
var import_livekit_server_sdk = require("livekit-server-sdk");
class SimpleOTLPHttpLogExporter {
  config;
  jwt = null;
  static FORCE_DOUBLE_KEYS = /* @__PURE__ */ new Set([
    "transcriptConfidence",
    "transcriptionDelay",
    "endOfTurnDelay",
    "onUserTurnCompletedDelay",
    "llmNodeTtft",
    "ttsNodeTtfb",
    "e2eLatency"
  ]);
  constructor(config) {
    this.config = config;
  }
  /**
   * Export simple log records
   */
  async export(records) {
    if (records.length === 0) return;
    await this.ensureJwt();
    const endpoint = `https://${this.config.cloudHostname}/observability/logs/otlp/v0`;
    const payload = this.buildPayload(records);
    const payloadJson = JSON.stringify(payload);
    const response = await fetch(endpoint, {
      method: "POST",
      headers: {
        Authorization: `Bearer ${this.jwt}`,
        "Content-Type": "application/json"
      },
      body: payloadJson
    });
    if (!response.ok) {
      const text = await response.text();
      throw new Error(
        `OTLP log export failed: ${response.status} ${response.statusText} - ${text}`
      );
    }
  }
  async ensureJwt() {
    if (this.jwt) return;
    const apiKey = process.env.LIVEKIT_API_KEY;
    const apiSecret = process.env.LIVEKIT_API_SECRET;
    if (!apiKey || !apiSecret) {
      throw new Error("LIVEKIT_API_KEY and LIVEKIT_API_SECRET must be set");
    }
    const token = new import_livekit_server_sdk.AccessToken(apiKey, apiSecret, { ttl: "6h" });
    token.addObservabilityGrant({ write: true });
    this.jwt = await token.toJwt();
  }
  buildPayload(records) {
    const resourceAttrs = Object.entries(this.config.resourceAttributes).map(([key, value]) => ({
      key,
      value: { stringValue: value }
    }));
    if (!this.config.resourceAttributes["service.name"]) {
      resourceAttrs.push({ key: "service.name", value: { stringValue: "livekit-agents" } });
    }
    const scopeAttrs = this.config.scopeAttributes ? Object.entries(this.config.scopeAttributes).map(([key, value]) => ({
      key,
      value: { stringValue: value }
    })) : [];
    const logRecords = records.map((record) => {
      const timestampMs = Number.isFinite(record.timestampMs) ? record.timestampMs : Date.now();
      return {
        timeUnixNano: String(BigInt(Math.floor(timestampMs * 1e6))),
        observedTimeUnixNano: String(BigInt(Date.now()) * BigInt(1e6)),
        severityNumber: record.severityNumber ?? import_api_logs.SeverityNumber.UNSPECIFIED,
        severityText: record.severityText ?? "unspecified",
        body: { stringValue: record.body },
        attributes: this.convertAttributes(record.attributes),
        traceId: "",
        spanId: ""
      };
    });
    return {
      resourceLogs: [
        {
          resource: { attributes: resourceAttrs },
          scopeLogs: [
            {
              scope: {
                name: this.config.scopeName,
                attributes: scopeAttrs
              },
              logRecords
            }
          ]
        }
      ]
    };
  }
  convertAttributes(attrs) {
    return Object.entries(attrs).map(([key, value]) => ({
      key,
      value: this.convertValue(value, key)
    }));
  }
  convertValue(value, path = "") {
    var _a;
    if (value === null || value === void 0) {
      return { stringValue: "" };
    }
    if (typeof value === "string") {
      return { stringValue: value };
    }
    if (typeof value === "number") {
      const leafKey = ((_a = path.split(".").pop()) == null ? void 0 : _a.replace(/\[\d+\]$/, "")) ?? path;
      if (SimpleOTLPHttpLogExporter.FORCE_DOUBLE_KEYS.has(leafKey)) {
        return { doubleValue: value };
      }
      return Number.isInteger(value) ? { intValue: String(value) } : { doubleValue: value };
    }
    if (typeof value === "boolean") {
      return { boolValue: value };
    }
    if (Array.isArray(value)) {
      return {
        arrayValue: {
          values: value.map((v, i) => this.convertValue(v, `${path}[${i}]`))
        }
      };
    }
    if (typeof value === "object") {
      const toJSON = value.toJSON;
      if (typeof toJSON === "function") {
        return this.convertValue(value.toJSON(), path);
      }
      return {
        kvlistValue: {
          values: Object.entries(value).map(([k, v]) => ({
            key: k,
            value: this.convertValue(v, path ? `${path}.${k}` : k)
          }))
        }
      };
    }
    return { stringValue: String(value) };
  }
}
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
  SimpleOTLPHttpLogExporter
});
//# sourceMappingURL=otel_http_exporter.cjs.map