#!/usr/bin/env node
import { findDirectChromiumLaunches } from "./src/playwright-launch-guard.mjs";

const args = parseArgs(process.argv.slice(2));
if (args.help) {
  process.stdout.write(`${JSON.stringify(helpPayload(), null, 2)}\n`);
  process.exit(0);
}

const report = findDirectChromiumLaunches({
  repoRoot: args.repoRoot,
  roots: args.roots.length > 0 ? args.roots : undefined
});
process.stdout.write(`${JSON.stringify(report, null, 2)}\n`);
process.exitCode = report.status === "pass" ? 0 : 2;

function parseArgs(argv) {
  const out = { help: false, repoRoot: process.cwd(), roots: [] };
  for (let index = 0; index < argv.length; index += 1) {
    const arg = argv[index];
    const readValue = (name) => {
      const inline = arg.match(new RegExp(`^${name}=(.+)$`, "u"));
      if (inline) return inline[1];
      const value = argv[index + 1];
      if (!value || value.startsWith("--")) throw new Error(`${name} requires a value`);
      index += 1;
      return value;
    };
    if (arg === "--help" || arg === "-h") out.help = true;
    else if (arg === "--root" || arg.startsWith("--root=")) out.repoRoot = readValue("--root");
    else if (arg === "--path" || arg.startsWith("--path=")) out.roots.push(...readValue("--path").split(",").filter(Boolean));
    else throw new Error(`unknown playwright-launch-guard argument: ${arg}`);
  }
  return out;
}

function helpPayload() {
  return {
    ok: true,
    command: "playwright-launch-guard",
    usage: [
      "node scripts/playwright-launch-guard.mjs",
      "node scripts/playwright-launch-guard.mjs --path scripts,tools,web"
    ],
    summary: "Fails when repo scripts bypass scripts/src/browser-launcher.mjs with direct chromium launch calls."
  };
}
