import { homedir } from "node:os";
import { join } from "node:path";
import { parseBrowserTypes } from "./fetch/browser-types.js";
import { readPersistedConfig, resetPersistedConfig, defaultConfigPath } from "./persisted-config.js";
function envStr(key, fallback, settings, settingsKey) {
  const envVal = process.env[key];
  if (envVal !== void 0) return envVal;
  const sk = settingsKey ?? key;
  const persisted = settings[sk];
  if (typeof persisted === "string") return persisted;
  return fallback;
}
function envInt(key, fallback, settings, settingsKey) {
  const envVal = process.env[key];
  if (envVal !== void 0) {
    const parsed = parseInt(envVal, 10);
    return isNaN(parsed) ? fallback : parsed;
  }
  const sk = settingsKey ?? key;
  const persisted = settings[sk];
  if (typeof persisted === "number" && !isNaN(persisted)) return persisted;
  return fallback;
}
function envIntArray(key, fallback, settings, settingsKey) {
  const envVal = process.env[key];
  if (envVal !== void 0) {
    const parts = envVal.split(",").map((s) => parseInt(s.trim(), 10));
    if (parts.some((n) => isNaN(n))) return fallback;
    return parts;
  }
  const sk = settingsKey ?? key;
  const persisted = settings[sk];
  if (Array.isArray(persisted) && persisted.every((n) => typeof n === "number" && !isNaN(n))) {
    return persisted;
  }
  return fallback;
}
function envBool(key, fallback, settings, settingsKey) {
  const envVal = process.env[key];
  if (envVal !== void 0) return envVal.toLowerCase() !== "false" && envVal !== "0";
  const sk = settingsKey ?? key;
  const persisted = settings[sk];
  if (typeof persisted === "boolean") return persisted;
  return fallback;
}
const TLS_BROWSER_PATTERN = /^(chrome|firefox|safari|edge|opera)_\d+$/;
function validateTlsBrowser(raw, fallback) {
  if (!raw) return fallback;
  if (TLS_BROWSER_PATTERN.test(raw)) return raw;
  process.stderr.write(
    `[wigolo] WIGOLO_TLS_BROWSER=${JSON.stringify(raw)} is not in the allowlist (${TLS_BROWSER_PATTERN.source}); falling back to ${fallback}
`
  );
  return fallback;
}
let cachedConfig = null;
function getConfig() {
  if (cachedConfig) return cachedConfig;
  const { settings } = readPersistedConfig(defaultConfigPath());
  const cdpRaw = envStr("WIGOLO_CDP_URL", null, settings, "cdpUrl");
  const dataDirRaw = envStr("WIGOLO_DATA_DIR", null, settings, "dataDir");
  const dataDir = dataDirRaw ?? join(homedir(), ".wigolo");
  cachedConfig = {
    searxngUrl: envStr("SEARXNG_URL", null, settings, "searxngUrl"),
    searxngMode: envStr("SEARXNG_MODE", "native", settings, "searxngMode"),
    searxngPort: envInt("SEARXNG_PORT", 8888, settings, "searxngPort"),
    fetchTimeoutMs: envInt("FETCH_TIMEOUT_MS", 1e4, settings, "fetchTimeoutMs"),
    fetchMaxRetries: envInt("FETCH_MAX_RETRIES", 2, settings, "fetchMaxRetries"),
    maxRedirects: envInt("MAX_REDIRECTS", 5, settings, "maxRedirects"),
    playwrightLoadTimeoutMs: envInt("PLAYWRIGHT_LOAD_TIMEOUT_MS", 15e3, settings, "playwrightLoadTimeoutMs"),
    playwrightNavTimeoutMs: envInt("PLAYWRIGHT_NAV_TIMEOUT_MS", 3e4, settings, "playwrightNavTimeoutMs"),
    searxngQueryTimeoutMs: envInt("SEARXNG_QUERY_TIMEOUT_MS", 8e3, settings, "searxngQueryTimeoutMs"),
    searchFetchTimeoutMs: envInt("SEARCH_FETCH_TIMEOUT_MS", 15e3, settings, "searchFetchTimeoutMs"),
    searchTotalTimeoutMs: envInt("SEARCH_TOTAL_TIMEOUT_MS", 3e4, settings, "searchTotalTimeoutMs"),
    validateTimeoutMs: envInt("VALIDATE_TIMEOUT_MS", 5e3, settings, "validateTimeoutMs"),
    maxBrowsers: envInt("MAX_BROWSERS", 3, settings, "maxBrowsers"),
    browserIdleTimeoutMs: envInt("BROWSER_IDLE_TIMEOUT", 6e4, settings, "browserIdleTimeoutMs"),
    browserFallbackThreshold: envInt("BROWSER_FALLBACK_THRESHOLD", 3, settings, "browserFallbackThreshold"),
    authStatePath: envStr("WIGOLO_AUTH_STATE_PATH", null, settings, "authStatePath"),
    chromeProfilePath: envStr("WIGOLO_CHROME_PROFILE_PATH", null, settings, "chromeProfilePath"),
    cdpUrl: cdpRaw || null,
    dataDir,
    cacheTtlSearch: envInt("CACHE_TTL_SEARCH", 86400, settings, "cacheTtlSearch"),
    cacheTtlContent: envInt("CACHE_TTL_CONTENT", 604800, settings, "cacheTtlContent"),
    fastStaleMaxHours: envInt("WIGOLO_FAST_STALE_MAX_HOURS", 24, settings, "fastStaleMaxHours"),
    fastTimeoutMs: envInt("WIGOLO_FAST_TIMEOUT_MS", 800, settings, "fastTimeoutMs"),
    crawlConcurrency: envInt("CRAWL_CONCURRENCY", 2, settings, "crawlConcurrency"),
    crawlDelayMs: envInt("CRAWL_DELAY_MS", 500, settings, "crawlDelayMs"),
    crawlPrivateConcurrency: envInt("CRAWL_PRIVATE_CONCURRENCY", 10, settings, "crawlPrivateConcurrency"),
    crawlPrivateDelayMs: envInt("CRAWL_PRIVATE_DELAY_MS", 0, settings, "crawlPrivateDelayMs"),
    useProxy: envBool("USE_PROXY", false, settings, "useProxy"),
    proxyUrl: envStr("PROXY_URL", null, settings, "proxyUrl"),
    userAgent: envStr("USER_AGENT", null, settings, "userAgent"),
    validateLinks: envBool("VALIDATE_LINKS", true, settings, "validateLinks"),
    respectRobotsTxt: envBool("RESPECT_ROBOTS_TXT", true, settings, "respectRobotsTxt"),
    braveApiKey: envStr("BRAVE_API_KEY", null, settings, "braveApiKey"),
    githubToken: envStr("WIGOLO_GITHUB_TOKEN", null, settings, "githubToken"),
    logLevel: envStr("LOG_LEVEL", "info", settings, "logLevel"),
    logFormat: envStr("LOG_FORMAT", "json", settings, "logFormat"),
    reranker: (() => {
      const raw = envStr("WIGOLO_RERANKER", null, settings, "reranker") ?? "onnx";
      if (raw === "flashrank") {
        process.stderr.write(
          '[wigolo] WIGOLO_RERANKER=flashrank is a legacy alias; treating as onnx. The reranker runs as a Python subprocess; install via "wigolo warmup --reranker".\n'
        );
        return "onnx";
      }
      return raw;
    })(),
    rerankerModel: envStr("WIGOLO_RERANKER_MODEL", "bge-reranker-v2-m3", settings, "rerankerModel") ?? "bge-reranker-v2-m3",
    rerankerMaxLength: envInt("WIGOLO_RERANKER_MAX_LENGTH", 512, settings, "rerankerMaxLength"),
    rerankerReadyTimeoutMs: envInt("WIGOLO_RERANKER_READY_TIMEOUT_MS", 6e4, settings, "rerankerReadyTimeoutMs"),
    rerankerRequestTimeoutMs: envInt("WIGOLO_RERANKER_REQUEST_TIMEOUT_MS", 3e4, settings, "rerankerRequestTimeoutMs"),
    rerankerIdleTimeoutMs: envInt("WIGOLO_RERANKER_IDLE_TIMEOUT_MS", 3e5, settings, "rerankerIdleTimeoutMs"),
    relevanceThreshold: (() => {
      const raw = envStr("WIGOLO_RELEVANCE_THRESHOLD", null, settings, "relevanceThreshold");
      if (raw === null || raw === "") return 0;
      const n = parseFloat(raw);
      return isNaN(n) ? 0 : n;
    })(),
    findSimilarColdStartThreshold: (() => {
      const raw = envStr("WIGOLO_FIND_SIMILAR_COLD_START_THRESHOLD", null, settings, "findSimilarColdStartThreshold");
      if (raw === null || raw === "") return 0.02;
      const n = parseFloat(raw);
      return Number.isFinite(n) ? n : 0.02;
    })(),
    bootstrapMaxAttempts: envInt("WIGOLO_BOOTSTRAP_MAX_ATTEMPTS", 3, settings, "bootstrapMaxAttempts"),
    bootstrapBackoffSeconds: envIntArray("WIGOLO_BOOTSTRAP_BACKOFF_SECONDS", [30, 3600, 86400], settings, "bootstrapBackoffSeconds"),
    healthProbeIntervalMs: envInt("WIGOLO_HEALTH_PROBE_INTERVAL_MS", 3e4, settings, "healthProbeIntervalMs"),
    daemonPort: envInt("WIGOLO_DAEMON_PORT", 3333, settings, "daemonPort"),
    daemonHost: (() => {
      const raw = envStr("WIGOLO_DAEMON_HOST", "127.0.0.1", settings, "daemonHost");
      return raw?.trim() || "127.0.0.1";
    })(),
    pluginsDir: (() => {
      const raw = envStr("WIGOLO_PLUGINS_DIR", null, settings, "pluginsDir");
      if (raw) {
        if (raw.startsWith("~")) return join(homedir(), raw.slice(1));
        return raw;
      }
      return join(dataDir, "plugins");
    })(),
    browserTypes: parseBrowserTypes(envStr("WIGOLO_BROWSER_TYPES", null, settings, "browserTypes")),
    shellHistoryPath: envStr("WIGOLO_SHELL_HISTORY_PATH", null, settings, "shellHistoryPath") ?? join(homedir(), ".wigolo", "shell-history"),
    multiQueryConcurrency: envInt("WIGOLO_MULTI_QUERY_CONCURRENCY", 5, settings, "multiQueryConcurrency"),
    multiQueryMax: envInt("WIGOLO_MULTI_QUERY_MAX", 10, settings, "multiQueryMax"),
    embeddingModel: envStr("WIGOLO_EMBEDDING_MODEL", "BAAI/bge-small-en-v1.5", settings, "embeddingModel") ?? "BAAI/bge-small-en-v1.5",
    embeddingIdleTimeoutMs: envInt("WIGOLO_EMBEDDING_IDLE_TIMEOUT", 18e5, settings, "embeddingIdleTimeoutMs"),
    embeddingMaxTextLength: envInt("WIGOLO_EMBEDDING_MAX_TEXT_LENGTH", 8e3, settings, "embeddingMaxTextLength"),
    llmProvider: envStr("WIGOLO_LLM_PROVIDER", null, settings, "llmProvider"),
    llmCacheTtlDays: envInt("WIGOLO_LLM_CACHE_TTL_DAYS", 7, settings, "llmCacheTtlDays"),
    llmMaxCallsPerRequest: envInt("WIGOLO_LLM_MAX_CALLS_PER_REQUEST", 1, settings, "llmMaxCallsPerRequest"),
    tlsTier: (() => {
      const raw = (envStr("WIGOLO_TLS_TIER", "off", settings, "tlsTier") ?? "off").toLowerCase();
      return raw === "auto" || raw === "on" ? raw : "off";
    })(),
    // The TLS-impersonation backend accepts a `<browser>_<version>` profile
    // string and forwards it into a Rust napi binding. Passing an unvalidated
    // value risks a panic / abort in native code if the env var is a typo
    // (`chrme_142`) or hostile input. Restrict to the documented wreq-js
    // browser families; on mismatch we warn (to stderr via the logger) and
    // fall back to the safe default.
    tlsBrowser: validateTlsBrowser(envStr("WIGOLO_TLS_BROWSER", null, settings, "tlsBrowser"), "chrome_142"),
    tlsSuccessThreshold: envInt("WIGOLO_TLS_SUCCESS_THRESHOLD", 3, settings, "tlsSuccessThreshold")
  };
  return cachedConfig;
}
function resetConfig() {
  cachedConfig = null;
  resetPersistedConfig();
}
export {
  getConfig,
  resetConfig,
  validateTlsBrowser
};
//# sourceMappingURL=config.js.map