import { existsSync } from 'node:fs';
import { execSync } from 'node:child_process';

const VALID_PACKAGE_MANAGERS = /* @__PURE__ */ new Set(["npm", "pnpm", "yarn"]);
function createPackageManagerRunner(type, { root = process.cwd() } = {}) {
  return {
    type,
    commands: {
      run(command, ...args) {
        return type === "npm" ? `npm run ${command}${stringifyArgs(args)}` : `${type} ${command}${stringifyArgs(args)}`;
      },
      install(...args) {
        return `${type} install${stringifyArgs(args)}`;
      }
    },
    async install() {
      try {
        execSync(`corepack use ${type}@latest`, {
          cwd: root,
          stdio: "inherit"
        });
      } catch {
      }
      execSync(`${type} install`, { cwd: root, stdio: "inherit" });
    },
    async run(command, args) {
      execSync(`${type} ${command} ${args.join(" ")}`, {
        cwd: root,
        stdio: "inherit"
      });
    }
  };
}
function stringifyArgs(args) {
  return args.length === 0 ? "" : ` ${args.join(" ")}`;
}
async function getPackageManager(explicitPackageManager) {
  if (explicitPackageManager) {
    const normalizedPackageManager = explicitPackageManager.toLowerCase();
    return VALID_PACKAGE_MANAGERS.has(normalizedPackageManager) ? normalizedPackageManager : void 0;
  }
  const npmUserAgent = process.env["npm_config_user_agent"];
  if (npmUserAgent?.includes("pnpm") || existsSync("pnpm-lock.yaml")) {
    return "pnpm";
  } else if (npmUserAgent?.includes("yarn") || existsSync("yarn.lock")) {
    return "yarn";
  } else if (npmUserAgent?.includes("npm") || existsSync("package-lock.json")) {
    return "npm";
  }
}

export { createPackageManagerRunner, getPackageManager };
