import os from "node:os";

function required(env, name) {
  const value = String(env[name] || "").trim();
  if (!value) throw new Error(`${name} is required`);
  return value;
}

function port(env, name, fallback) {
  const value = Number.parseInt(env[name] || String(fallback), 10);
  if (!Number.isInteger(value) || value < 1 || value > 65535) throw new Error(`${name} must be a valid port`);
  return value;
}

function interval(env, name, fallback, minimum) {
  const value = Number.parseInt(env[name] || String(fallback), 10);
  if (!Number.isInteger(value) || value < minimum) throw new Error(`${name} must be at least ${minimum}`);
  return value;
}

function optionalInterface(env, name, fallback) {
  const value = String(env[name] || fallback).trim();
  if (!/^[a-zA-Z0-9_.-]{1,15}$/.test(value)) throw new Error(`${name} must be a valid interface name`);
  return value;
}

export function loadConfig(env = process.env) {
  const cloudUrl = required(env, "VIMIFY_CLOUD_URL").replace(/\/+$/, "");
  if (!/^https:\/\//i.test(cloudUrl) && env.VIMIFY_ALLOW_INSECURE_HTTP !== "true") {
    throw new Error("VIMIFY_CLOUD_URL must use HTTPS");
  }

  const clients = required(env, "VIMIFY_RADIUS_CLIENTS").split(",").map((value) => value.trim()).filter(Boolean);
  const syncIntervalMs = interval(env, "VIMIFY_SYNC_INTERVAL_MS", 15000, 5000);
  const heartbeatIntervalMs = interval(env, "VIMIFY_HEARTBEAT_INTERVAL_MS", 60000, 15000);
  const vpnEnabled = String(env.VIMIFY_VPN_ENABLED || "false").toLowerCase() === "true";

  return {
    cloudUrl,
    hotspotId: required(env, "VIMIFY_HOTSPOT_ID"),
    edgeToken: required(env, "VIMIFY_EDGE_TOKEN"),
    radiusSecret: required(env, "VIMIFY_RADIUS_SECRET"),
    radiusClients: new Set(clients),
    radiusHost: String(env.VIMIFY_RADIUS_HOST || "0.0.0.0"),
    authPort: port(env, "VIMIFY_AUTH_PORT", 1812),
    accountingPort: port(env, "VIMIFY_ACCT_PORT", 1813),
    syncIntervalMs,
    heartbeatIntervalMs,
    stateDir: String(env.VIMIFY_STATE_DIR || "/var/lib/vimify-edge"),
    edgeDeviceId: String(env.VIMIFY_EDGE_DEVICE_ID || os.hostname()),
    vpn: {
      enabled: vpnEnabled,
      interface: optionalInterface(env, "VIMIFY_VPN_INTERFACE", "wg-vimify"),
      tunnelIp: String(env.VIMIFY_VPN_TUNNEL_IP || "").trim(),
      hubEndpoint: String(env.VIMIFY_VPN_HUB_ENDPOINT || "").trim(),
      statusFile: String(env.VIMIFY_VPN_STATUS_FILE || "/run/vimify-vpn/status.json"),
    },
  };
}
