import * as plugins from './smartpuppeteer.plugins.js';

export interface IEnvAwareOptions {
  forceNoSandbox?: boolean;
  usePipe?: boolean;
}

export const getEnvAwareBrowserInstance = async (
  optionsArg: IEnvAwareOptions = {}
): Promise<plugins.puppeteer.Browser> => {
  const options: IEnvAwareOptions = {
    forceNoSandbox: false,
    ...optionsArg,
  };

  let chromeArgs: string[] = [];
  if (
    process.env.CI ||
    options.forceNoSandbox ||
    plugins.os.userInfo().username === 'root'
  ) {
    chromeArgs = chromeArgs.concat(['--no-sandbox', '--disable-setuid-sandbox']);
    console.warn('********************************************************');
    console.warn('WARNING: Launching browser without sandbox. This can be insecure!');
    console.warn('********************************************************');
  }

  // Automatically choose an executable if available: prefer google-chrome, then chromium, then chromium-browser.
  const execPath =
    plugins.smartshell.which.sync('google-chrome') ||
    plugins.smartshell.which.sync('chromium') ||
    plugins.smartshell.which.sync('chromium-browser');

  const executablePathOptions = execPath ? { executablePath: execPath } : {};

  console.log('Launching puppeteer browser with arguments:');
  console.log(chromeArgs);
  if (execPath) {
    console.log(`Using executable: ${execPath}`);
  } else {
    console.log('No specific browser executable found; falling back to Puppeteer default.');
  }

  const headlessBrowser = await plugins.puppeteer.launch({
    args: chromeArgs,
    pipe: options.usePipe !== undefined ? options.usePipe : true,
    headless: true,
    ...executablePathOptions,
  });

  return headlessBrowser;
};