import { appendFileSync, mkdirSync } from "node:fs";
import { join } from "node:path";
import { getConfig } from "../config.js";
let _endpoint;
function isTelemetryEnabled() {
  return process.env.WIGOLO_TELEMETRY === "1";
}
function configureRemote(endpoint) {
  _endpoint = endpoint;
}
function utcDateStamp(d) {
  const y = d.getUTCFullYear().toString().padStart(4, "0");
  const m = (d.getUTCMonth() + 1).toString().padStart(2, "0");
  const day = d.getUTCDate().toString().padStart(2, "0");
  return `${y}${m}${day}`;
}
function writeLocal(event) {
  try {
    const dir = join(getConfig().dataDir, "telemetry");
    mkdirSync(dir, { recursive: true });
    const file = join(dir, `events-${utcDateStamp(new Date(event.ts))}.ndjson`);
    appendFileSync(file, JSON.stringify(event) + "\n");
  } catch {
  }
}
function postRemote(endpoint, event) {
  try {
    const result = fetch(endpoint, {
      method: "POST",
      body: JSON.stringify(event),
      headers: { "Content-Type": "application/json" }
    });
    if (result && typeof result.catch === "function") {
      result.catch(() => {
      });
    }
  } catch {
  }
}
function emit(event, props) {
  if (!isTelemetryEnabled()) return;
  const evt = props !== void 0 ? { ts: (/* @__PURE__ */ new Date()).toISOString(), event, props } : { ts: (/* @__PURE__ */ new Date()).toISOString(), event };
  writeLocal(evt);
  const endpoint = _endpoint ?? process.env.WIGOLO_TELEMETRY_ENDPOINT;
  if (endpoint) postRemote(endpoint, evt);
}
function _resetTelemetryForTest() {
  _endpoint = void 0;
}
export {
  _resetTelemetryForTest,
  configureRemote,
  emit,
  isTelemetryEnabled
};
//# sourceMappingURL=telemetry.js.map