import { defineConfig, devices } from "@playwright/test";
import { existsSync, readdirSync, realpathSync, statSync } from "node:fs";
function findNixChromiumHeadlessShell(): string | undefined {
  const browsersPath = process.env.PLAYWRIGHT_BROWSERS_PATH;
  if (!browsersPath || !existsSync(browsersPath)) return undefined;
  const findExecutable = (root: string): string | undefined => {
    for (const entry of readdirSync(root)) {
      const candidate = `${root}/${entry}`;
      const stat = statSync(candidate);
      if (stat.isFile() && entry === "chrome-headless-shell") return candidate;
      if (stat.isDirectory()) {
        const found = findExecutable(candidate);
        if (found) return found;
      }
    }
    return undefined;
  };
  for (const entry of readdirSync(browsersPath)) {
    if (entry.startsWith("chromium_headless_shell-")) {
      const found = findExecutable(realpathSync(`${browsersPath}/${entry}`));
      if (found) return found;
    }
  }
  return undefined;
}
const chromiumExecutablePath = findNixChromiumHeadlessShell();
export default defineConfig({
  testDir: "./tests",
  timeout: 30_000,
  expect: { timeout: 5_000 },
  use: {
    baseURL: "http://127.0.0.1:60000", // avoid ports likely to be in use
    trace: "on-first-retry",
  },
  projects: [
    {
      name: "chromium",
      use: {
        ...devices["Desktop Chrome"],
        launchOptions: chromiumExecutablePath ? { executablePath: chromiumExecutablePath } : undefined,
      },
    },
  ],
  webServer: {
    command:
      "rm -f data/polymodel-e2e.db && DATABASE_URL=sqlite:./data/polymodel-e2e.db POLYMODEL_SAMPLE_DATA=auto just serve --port 60000",
    cwd: "..",
    url: "http://127.0.0.1:60000",
    reuseExistingServer: false,
    timeout: 600_000,
  },
});
