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 ?? "",
  webAllowedOrigins: process.env.WEB_ALLOWED_ORIGINS ?? "",
  watcherSecretKey: process.env.WATCHER_SECRET_KEY ?? "",
  watcherEnabled: (process.env.WATCHER_ENABLED ?? "true").toLowerCase() !== "false",
  watcherTickMs: envNumber(process.env.WATCHER_TICK_MS, 30_000),
  watcherTimeoutMs: envNumber(process.env.WATCHER_TIMEOUT_MS, 180_000),
  watcherRuntimeDir: process.env.WATCHER_RUNTIME_DIR ?? "/tmp/qbuffer-watchers",
  wscraperServiceBaseUrl:
    process.env.WSCRAPER_SERVICE_BASE_URL ?? "http://host.docker.internal:8787",
  wscraperServiceToken: process.env.WSCRAPER_SERVICE_TOKEN ?? "",
  dataDir: "/app/data",
  dbPath: "/app/data/db.json",
  logsPath: "/app/data/logs.json",
  loopLogsDir: "/app/data/loop-logs",
  loopLogsArchiveDir: "/app/data/loop-logs-archive",
  torrentArchiveDir: "/app/data/torrents",
  watcherDownloadsDir: "/app/data/watcher-downloads",
  webPublicDir: path.resolve("/app/apps/server/public"),
};

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