const LOW_CPU_RESOURCE_PROFILE = "low_cpu";

const BLOCKED_RESOURCE_TYPES = new Set(["font", "media"]);
const BLOCKED_URL_PATTERN = /(?:doubleclick|googletagmanager|google-analytics|cnzz|umeng|alicdn\.com\/.*(?:beacon|log|trace)|log\.mmstat|gm.mmstat|arms-retcode|retcode|aplus|acjs|adservice|marketing)/i;

export function resolveSearchResourceProfile(env = process.env) {
  const value = String(env.SEARCH_RESOURCE_PROFILE ?? "").trim().toLowerCase();
  return value === LOW_CPU_RESOURCE_PROFILE ? LOW_CPU_RESOURCE_PROFILE : "debug";
}

export function isLowCpuSearchRuntime(env = process.env) {
  return resolveSearchResourceProfile(env) === LOW_CPU_RESOURCE_PROFILE;
}

export function buildSearchBrowserArgs(env = process.env) {
  const args = ["--disable-blink-features=AutomationControlled"];

  if (isLowCpuSearchRuntime(env)) {
    args.push(
      "--disable-background-networking",
      "--disable-default-apps",
      "--disable-extensions",
      "--disable-sync",
      "--mute-audio",
      "--autoplay-policy=user-gesture-required",
    );
  }

  return args;
}

export async function installLowCpuRouteFilters(context, env = process.env) {
  if (!isLowCpuSearchRuntime(env)) {
    return;
  }

  await context.route("**/*", async (route) => {
    const request = route.request();
    if (BLOCKED_RESOURCE_TYPES.has(request.resourceType()) || BLOCKED_URL_PATTERN.test(request.url())) {
      await route.abort().catch(() => {});
      return;
    }

    await route.continue().catch(() => {});
  });
}

