/**
 * Deploy-time pre-download of the CloakBrowser stealth Chromium binary.
 *
 * Runs as dp-worker's `postinstall`, so by the time a worker is started in
 * cloakbrowser mode the ~200MB patched Chromium is already cached on the host
 * (`~/.cloakbrowser/`, override `CLOAKBROWSER_CACHE_DIR`). The cache is shared
 * across every worker process on the host, so this downloads at most once per
 * host — tasks never block on a download.
 *
 * Best-effort by design:
 *   - Set DIPCLAW_SKIP_CLOAK_DOWNLOAD=1 to skip (CI, dev, or chrome-only hosts).
 *   - Any failure is logged and swallowed — it must never fail `npm install`,
 *     since the runtime `ensureBinary()` guard in cloakbrowser-backend.ts will
 *     fetch the binary on first cloakbrowser launch as a fallback.
 */

if (process.env.DIPCLAW_SKIP_CLOAK_DOWNLOAD) {
  console.log(
    "[install-cloakbrowser] DIPCLAW_SKIP_CLOAK_DOWNLOAD set — skipping binary pre-download."
  );
  process.exit(0);
}

try {
  const { ensureBinary, binaryInfo } = await import("cloakbrowser");
  const before = binaryInfo();
  if (before.installed) {
    console.log(
      `[install-cloakbrowser] stealth Chromium already cached (${before.version}) at ${before.binaryPath}`
    );
    process.exit(0);
  }
  console.log(
    "[install-cloakbrowser] downloading CloakBrowser stealth Chromium (~200MB, once per host)…"
  );
  const binaryPath = await ensureBinary();
  console.log(`[install-cloakbrowser] ready: ${binaryPath}`);
} catch (err) {
  const message = err && err.message ? err.message : String(err);
  console.warn(
    `[install-cloakbrowser] pre-download skipped (${message}). ` +
      "Will download on first cloakbrowser launch instead."
  );
  // Never fail the install.
  process.exit(0);
}
