import path from "node:path";

const envNumber = (value: string | undefined, fallback: number) => {
  const parsed = Number(value);
  return Number.isFinite(parsed) ? parsed : fallback;
};

export const config = {
  port: envNumber(process.env.SERVER_PORT, 3001),
  nodeEnv: process.env.NODE_ENV ?? "development",
  qbitBaseUrl: process.env.QBIT_BASE_URL ?? "",
  qbitUsername: process.env.QBIT_USERNAME ?? "",
  qbitPassword: process.env.QBIT_PASSWORD ?? "",
  appUsername: process.env.APP_USERNAME ?? "",
  appPassword: process.env.APP_PASSWORD ?? "",
  jwtSecret: process.env.JWT_SECRET ?? "",
  pollIntervalMs: envNumber(process.env.POLL_INTERVAL_MS, 3000),
  enforceIntervalMs: envNumber(process.env.ENFORCE_INTERVAL_MS, 2000),
  defaultDelayMs: envNumber(process.env.DEFAULT_DELAY_MS, 3000),
  maxLoopLimit: envNumber(process.env.MAX_LOOP_LIMIT, 20),
  stalledRecoveryMs: envNumber(process.env.STALLED_RECOVERY_MS, 300_000),
  timerPollMs: envNumber(process.env.TIMER_POLL_MS, 60_000),
  webPort: envNumber(process.env.WEB_PORT, 5173),
  webOrigin: process.env.WEB_ORIGIN ?? "",
  dataDir: "/app/data",
  dbPath: "/app/data/db.json",
  logsPath: "/app/data/logs.json",
  torrentArchiveDir: "/app/data/torrents",
  webPublicDir: path.resolve("/app/apps/server/public"),
};

export const isDev = config.nodeEnv !== "production";
