import path from "node:path";

const dataDir = process.env.DATA_DIR || path.resolve(".vpn-proxy");
const parsePort = (value, fallback) => {
  const parsed = Number.parseInt(value, 10);
  return Number.isInteger(parsed) ? parsed : fallback;
};
const proxyPort = parsePort(process.env.PROXY_PORT, 8080);
const clientProxyPortStart = parsePort(
  process.env.CLIENT_PROXY_PORT_START,
  proxyPort,
);
const clientProxyPortEnd = parsePort(
  process.env.CLIENT_PROXY_PORT_END,
  clientProxyPortStart,
);

export const settings = {
  appMode: process.env.APP_MODE === "client" ? "client" : "gateway",
  port: parsePort(process.env.PORT, 3456),
  proxyPort,
  clientProxyPortStart,
  clientProxyPortEnd,
  tproxyPort: parsePort(process.env.TPROXY_PORT, 7895),
  tproxyChain: process.env.TPROXY_CHAIN || "VPN_PROXY_TPROXY",
  tproxySourceBypassChain:
    process.env.TPROXY_SOURCE_BYPASS_CHAIN || "VPN_PROXY_SRC_BYPASS",
  tproxySourceForwardChain:
    process.env.TPROXY_SOURCE_FORWARD_CHAIN || "VPN_PROXY_FWD_BYPASS",
  tproxySourceNatChain:
    process.env.TPROXY_SOURCE_NAT_CHAIN || "VPN_PROXY_NAT_BYPASS",
  bindIp: process.env.PROXY_BIND_IP || "0.0.0.0",
  dataDir,
  distDir: process.env.DIST_DIR || "/app/dist",
  configPath:
    process.env.SING_BOX_CONFIG || path.join(dataDir, "sing-box-config.json"),
  cachePath: process.env.SING_BOX_CACHE || "/var/lib/sing-box/cache.db",
  statePath: path.join(dataDir, "state.json"),
  customRulesPath: path.join(dataDir, "custom-rules.json"),
  customRuleSetsPath: path.join(dataDir, "custom-rule-sets.json"),
  clientSettingsPath: path.join(dataDir, "client-settings.json"),
  devicesPath: path.join(dataDir, "devices.json"),
  deviceRulesPath: path.join(dataDir, "device-rules.json"),
  subscriptionCachePath: path.join(dataDir, "subscription-cache.json"),
  sharedProxyHost: process.env.SHARED_PROXY_HOST || "",
  hwidPath: path.join(dataDir, "hwid"),
  routingRuDirect: String(process.env.ROUTING_RU_DIRECT || "true") !== "false",
  ruleSetDownloadDetour: process.env.RULE_SET_DOWNLOAD_DETOUR || "vpn",
  logLevel: process.env.LOG_LEVEL || "info",
  appName: "VPN Proxy Gateway",
};
