const os = require('os');
const path = require('path');
const { computeExecutablePath, Browser } = require('@puppeteer/browsers');
const puppeteer = require('puppeteer');

// Resolve the Chrome that Puppeteer downloaded so tests run without a
// system-installed browser, both locally and in CI containers.
// Puppeteer v25 made executablePath() async, which a sync karma.conf cannot
// await — so we compute the path synchronously via @puppeteer/browsers instead.
const buildId = puppeteer.PUPPETEER_REVISIONS.chrome;
const cacheDir = process.env.PUPPETEER_CACHE_DIR || path.join(os.homedir(), '.cache', 'puppeteer');
process.env.CHROME_BIN = computeExecutablePath({ browser: Browser.CHROME, buildId, cacheDir });

module.exports = function (config) {
  config.set({
    basePath: '',
    frameworks: ['jasmine'],
    plugins: [
      require('karma-jasmine'),
      require('karma-chrome-launcher'),
      require('karma-jasmine-html-reporter'),
      require('karma-coverage'),
    ],
    jasmineHtmlReporter: {
      suppressAll: true,
    },
    coverageReporter: {
      dir: path.join(__dirname, 'coverage', 'playground-frontend'),
      subdir: '.',
      reporters: [{ type: 'html' }, { type: 'text-summary' }],
    },
    reporters: ['progress', 'kjhtml'],
    browsers: ['ChromeHeadlessNoSandbox'],
    customLaunchers: {
      ChromeHeadlessNoSandbox: {
        base: 'ChromeHeadless',
        // CI containers run as root with no sandbox; /dev/shm is often too small.
        flags: ['--no-sandbox', '--headless', '--disable-gpu', '--disable-dev-shm-usage'],
      },
    },
    restartOnFileChange: true,
  });
};
