const { execFileSync } = require("node:child_process");

const webkitHostLibraries = [
  "libgtk-4.so.1",
  "libgraphene-1.0.so.0",
  "libxslt.so.1",
  "libevent-2.1.so.7",
  "libopus.so.0",
  "libgstallocators-1.0.so.0",
  "libgstapp-1.0.so.0",
  "libgstpbutils-1.0.so.0",
  "libgstaudio-1.0.so.0",
  "libgsttag-1.0.so.0",
  "libgstvideo-1.0.so.0",
  "libgstgl-1.0.so.0",
  "libgstcodecparsers-1.0.so.0",
  "libgstfft-1.0.so.0",
  "libflite.so.1",
  "libwebpdemux.so.2",
  "libavif.so.16",
  "libharfbuzz-icu.so.0",
  "libwebpmux.so.3",
  "libwayland-server.so.0",
  "libmanette-0.2.so.0",
  "libenchant-2.so.2",
  "libhyphen.so.0",
  "libsecret-1.so.0",
  "libwoff2dec.so.1.0.2",
  "libx264.so",
];

function hasWebKitHostDependencies() {
  if (process.platform !== "linux") {
    return true;
  }

  let output = "";
  try {
    output = execFileSync("ldconfig", ["-p"], { encoding: "utf8" });
  } catch {
    return false;
  }

  return webkitHostLibraries.every((library) => output.includes(library));
}

function shouldIncludeWebKit() {
  if (process.env.PLAYWRIGHT_FORCE_WEBKIT === "1") {
    return true;
  }
  if (process.env.PLAYWRIGHT_SKIP_WEBKIT === "1") {
    return false;
  }
  return hasWebKitHostDependencies();
}

module.exports = {
  hasWebKitHostDependencies,
  shouldIncludeWebKit,
};
