'use strict';
const { spawnSync } = require('child_process');
const fs = require('fs');
const path = require('path');

process.env.PLAYWRIGHT_BROWSERS_PATH = process.env.PLAYWRIGHT_BROWSERS_PATH ||
  path.resolve(__dirname, '..', 'browsers');

// Find Playwright CLI (avoid 'exports' restriction in playwright 1.59+)
const candidates = [
  path.resolve(__dirname, 'node_modules', 'playwright', 'cli.js'),
  path.resolve(__dirname, 'node_modules', 'playwright-core', 'cli.js'),
];
let cli = null;
for (const p of candidates) {
  if (fs.existsSync(p)) { cli = p; break; }
}
if (!cli) {
  console.error('[Chromium] Playwright CLI not found. Tried:');
  for (const p of candidates) console.error('  -', p);
  process.exit(1);
}
console.log('[Chromium] Using CLI:', cli);

// Mirror strategy: try default (Azure CDN) first, retry with mirror on failure
function tryInstall(host) {
  const env = Object.assign({}, process.env);
  if (host) env.PLAYWRIGHT_DOWNLOAD_HOST = host;
  console.log('[Chromium] Download host:', host || '(default Azure CDN)');
  const r = spawnSync(process.execPath, [cli, 'install', 'chromium'], { stdio: 'inherit', env });
  return r.status || 0;
}

const userHost = process.env.PLAYWRIGHT_DOWNLOAD_HOST;
const cnMode = process.env.AICS_CN_MIRROR === '1' || process.env.AICS_CN_MIRROR === 'on';

let code;
if (userHost) {
  code = tryInstall(userHost);
} else if (cnMode) {
  // User explicitly requested CN mirror
  code = tryInstall('https://cdn.npmmirror.com/binaries/playwright');
  if (code !== 0) {
    console.log('[Chromium] CN mirror failed, retrying with default...');
    code = tryInstall(null);
  }
} else {
  // Default: try Azure CDN; if fails, suggest CN mirror
  code = tryInstall(null);
  if (code !== 0) {
    console.log('[Chromium] Default download failed.');
    console.log('[Chromium] If you are in China, retry with: set AICS_CN_MIRROR=1');
  }
}
process.exit(code);
