export function normalizeCliArgs(argv) {
  const topLevelCommands = new Set([
    "run",
    "status",
    "destroy",
    "cleanup",
    "show",
    "logs",
    "artifacts",
    "watch",
    "known-failures",
    "db",
    "help",
    "--help",
    "-h",
    "--version",
    "-v",
  ]);
  const runTypeShortcuts = new Set(["int", "e2e", "dal", "load", "pw", "all"]);
  const valueFlags = new Set([
    "--dir",
    "--service",
    "--type",
    "--suite",
    "--file",
    "--workers",
    "--file-timeout-seconds",
    "--shard",
    "--input",
    "--output",
    "--status",
    "--issue-mode",
    "--output-mode",
    "--tail",
    "--log-tail",
  ]);
  const positionals = findPositionals(argv, valueFlags);
  const firstPositional = positionals[0] || null;
  const shouldPrefixRun =
    !firstPositional ||
    runTypeShortcuts.has(firstPositional.value) ||
    !topLevelCommands.has(firstPositional.value);

  if (shouldPrefixRun) {
    return ["run", ...argv];
  }

  if (topLevelCommands.has(firstPositional.value) && argv[0] !== firstPositional.value) {
    return reorderCommandArgs(argv, positionals);
  }

  return argv;
}

function findPositionals(args, flagsWithValues) {
  const positionals = [];
  for (let index = 0; index < args.length; index += 1) {
    const value = args[index];
    if (!value.startsWith("-")) {
      positionals.push({ index, value });
      continue;
    }
    if (flagsWithValues.has(value)) {
      index += 1;
    }
  }
  return positionals;
}

function reorderCommandArgs(args, positionals) {
  const commandTokens = [positionals[0]];
  if (positionals[0]?.value === "known-failures" && positionals[1]) {
    commandTokens.push(positionals[1]);
  }
  if (positionals[0]?.value === "db" && positionals[1] && positionals[2]) {
    commandTokens.push(positionals[1], positionals[2]);
  }
  const commandIndexes = new Set(commandTokens.map((token) => token.index));
  return [
    ...commandTokens.map((token) => token.value),
    ...args.filter((_value, index) => !commandIndexes.has(index)),
  ];
}
