import fs from "node:fs/promises";

async function optionalText(path, readFile) {
  try {
    return String(await readFile(path, "utf8")).trim();
  } catch {
    return "";
  }
}

function timestamp(value) {
  const parsed = Date.parse(String(value || ""));
  return Number.isFinite(parsed) && parsed <= Date.now() + 5 * 60_000 ? new Date(parsed).toISOString() : null;
}

export async function collectVpnTelemetry(config, io = {}) {
  const vpn = config.vpn || {};
  if (!vpn.enabled) return { enabled: false, state: "disabled" };
  const readFile = io.readFile || fs.readFile;
  const operstate = await optionalText(`/sys/class/net/${vpn.interface}/operstate`, readFile);
  const interfaceUp = Boolean(operstate && operstate !== "down" && operstate !== "notpresent");
  let status = {};
  try {
    status = JSON.parse(await optionalText(vpn.statusFile, readFile) || "{}");
  } catch {
    status = {};
  }
  const lastHandshakeAt = timestamp(status.lastHandshakeAt);
  const handshakeAge = lastHandshakeAt ? Date.now() - Date.parse(lastHandshakeAt) : Number.POSITIVE_INFINITY;
  const state = !interfaceUp
    ? "down"
    : !lastHandshakeAt
      ? "connecting"
      : handshakeAge <= 3 * 60_000
        ? "healthy"
        : "stale";

  return {
    enabled: true,
    interface: vpn.interface,
    tunnelIp: vpn.tunnelIp || null,
    hubEndpoint: vpn.hubEndpoint || status.endpoint || null,
    state,
    lastHandshakeAt,
  };
}
