'use strict';
/*
 * Locating a Chromium to render with, in ONE place: the render worker uses
 * it, the self-test asks it what it found, and the "install a render
 * browser" action drops one into DATA/browsers for machines that have no
 * Chrome at all (a debloated Windows may not even have Edge).
 *
 * Order: CHROME env var → a browser we installed ourselves → the system's.
 */
const fs = require('fs');
const path = require('path');

function installedByUs() {
  // DATA/browsers/** — @puppeteer/browsers lays out chrome/<build>/<dir>/chrome[.exe]
  const root = process.env.CLIPSHELF_BROWSERS;
  if (!root) return [];
  const out = [];
  const walk = (dir, depth) => {
    if (depth > 4) return;
    let entries = [];
    try { entries = fs.readdirSync(dir, { withFileTypes: true }); } catch (e) { return; }
    for (const e of entries) {
      const p = path.join(dir, e.name);
      if (e.isDirectory()) walk(p, depth + 1);
      else if (/^(chrome|chrome\.exe|chromium|chromium\.exe)$/i.test(e.name)) out.push(p);
    }
  };
  walk(root, 0);
  return out;
}

function systemCandidates() {
  if (process.platform === 'win32') {
    const pf = process.env['PROGRAMFILES'] || 'C:\\Program Files';
    const pf86 = process.env['PROGRAMFILES(X86)'] || 'C:\\Program Files (x86)';
    const lad = process.env.LOCALAPPDATA || '';
    return [
      pf + '\\Google\\Chrome\\Application\\chrome.exe',
      pf86 + '\\Google\\Chrome\\Application\\chrome.exe',
      lad && lad + '\\Google\\Chrome\\Application\\chrome.exe',
      pf86 + '\\Microsoft\\Edge\\Application\\msedge.exe',
      pf + '\\Microsoft\\Edge\\Application\\msedge.exe',
      lad && lad + '\\Microsoft\\Edge\\Application\\msedge.exe',
      pf + '\\BraveSoftware\\Brave-Browser\\Application\\brave.exe',
      pf86 + '\\BraveSoftware\\Brave-Browser\\Application\\brave.exe',
      lad && lad + '\\Vivaldi\\Application\\vivaldi.exe',
    ].filter(Boolean);
  }
  if (process.platform === 'darwin') {
    return [
      '/Applications/Google Chrome.app/Contents/MacOS/Google Chrome',
      '/Applications/Microsoft Edge.app/Contents/MacOS/Microsoft Edge',
      '/Applications/Chromium.app/Contents/MacOS/Chromium',
      '/Applications/Brave Browser.app/Contents/MacOS/Brave Browser',
    ];
  }
  const home = process.env.HOME || '';
  const cached = [];
  try {
    const base = path.join(home, '.cache', 'puppeteer', 'chrome');
    for (const d of fs.readdirSync(base)) {
      cached.push(path.join(base, d, 'chrome-linux64', 'chrome'));
    }
  } catch (e) { /* none */ }
  return [
    '/usr/bin/google-chrome', '/usr/bin/google-chrome-stable',
    '/usr/bin/chromium', '/usr/bin/chromium-browser', '/snap/bin/chromium',
    '/usr/bin/microsoft-edge', ...cached,
  ];
}

function candidates() {
  return [...installedByUs(), ...systemCandidates()];
}

function findChrome() {
  if (process.env.CHROME) {
    if (fs.existsSync(process.env.CHROME)) return process.env.CHROME;
    throw new Error(`CHROME is set to "${process.env.CHROME}" but that file does not exist`);
  }
  const cands = candidates();
  for (const c of cands) if (c && fs.existsSync(c)) return c;
  throw new Error('no Chrome/Edge found. Looked in:\n  ' + cands.join('\n  ') +
                  '\nInstall Chrome, or let the app download one for you (Settings).');
}

module.exports = { findChrome, candidates };

if (require.main === module) {
  try {
    console.log(findChrome());
  } catch (e) {
    console.error(e.message);
    process.exit(2);
  }
}
