#!/usr/bin/env node
/**
 * Auto-download the browser engine for Al Moasis's browser tools
 * (browser_open, web scraping, Google-Maps lead extraction) and the
 * Playwright MCP. Runs once on `npm i -g almoasis` / `npx almoasis`.
 *
 * NON-FATAL by design: if the download fails (offline, proxy, CI), we log a
 * clear recovery command and exit 0 so the install itself never breaks. The
 * user can always run `npx playwright install chromium` later. Skipping the
 * browser does NOT stop chat / WhatsApp / Telegram / file tools from working.
 *
 * We install BOTH `chromium` (full, for browser_open) and
 * `chromium-headless-shell` (lighter, used by some headless paths). Playwright
 * downloads the exact revision THIS package's playwright version expects, so
 * there's never the version-mismatch that breaks a hand-bundled browser.
 */
import { execSync } from 'node:child_process';
import { createRequire } from 'node:module';
import { dirname, join } from 'node:path';
import { existsSync } from 'node:fs';

// Honor an explicit opt-out (CI, slim installs).
if (process.env.ALMOASIS_SKIP_BROWSER_INSTALL === '1' || process.env.PLAYWRIGHT_SKIP_BROWSER_DOWNLOAD === '1') {
  console.log('[almoasis] Skipping Chromium download (opt-out env set).');
  process.exit(0);
}

try {
  const require = createRequire(import.meta.url);
  // Resolve the CLI via the package ROOT (package.json is always resolvable),
  // then join cli.js. Using require.resolve('playwright/cli.js') directly fails
  // because the package's "exports" map doesn't expose that subpath.
  let cli = null;
  for (const pkg of ['playwright', 'playwright-core']) {
    try {
      const root = dirname(require.resolve(`${pkg}/package.json`));
      const candidate = join(root, 'cli.js');
      if (existsSync(candidate)) { cli = candidate; break; }
    } catch { /* try next */ }
  }
  console.log('[almoasis] ⬇️  Downloading Chromium for browser tools (one-time, ~120MB)…');
  if (cli) {
    execSync(`node "${cli}" install chromium chromium-headless-shell`, { stdio: 'inherit' });
  } else {
    // Fallback: the `playwright` bin is on PATH during npm lifecycle scripts.
    execSync('playwright install chromium chromium-headless-shell', { stdio: 'inherit' });
  }
  console.log('[almoasis] ✅ Chromium ready — browser scraping & web automation enabled.');
} catch (err) {
  console.error('[almoasis] ⚠️  Chromium auto-install was skipped — browser scraping will be');
  console.error('[almoasis]     unavailable until you run:  npx playwright install chromium');
  console.error('[almoasis]     (chat, WhatsApp, Telegram, files all still work normally.)');
  console.error('[almoasis]     reason: ' + (err && err.message ? err.message : String(err)));
  // Exit 0 — an optional browser download must never fail the whole install.
  process.exit(0);
}
