// src/actions/packman/clean.ts
import {
  existsSync as existsSync3,
  rmSync,
  writeFileSync
} from "fs";
import PATH3 from "path";
import chalk2 from "chalk";

// src/actions/packman/convert.ts
import {
  existsSync as existsSync2,
  readdirSync,
  statSync
} from "fs";
import PATH2 from "path";
import chalk from "chalk";

// src/pm/workspaces.ts
import { existsSync, readFileSync } from "fs";
import PATH from "path";
import { globSync } from "glob";
function readJsonFile(path) {
  if (!existsSync(path)) return void 0;
  try {
    return JSON.parse(readFileSync(path, "utf8"));
  } catch {
    return void 0;
  }
}
function readRootPackageJson(cwd = process.cwd()) {
  return readJsonFile(PATH.resolve(cwd, "package.json"));
}
function readWorkspacePatternsFromPackageJson(cwd = process.cwd()) {
  const pkg = readRootPackageJson(cwd);
  if (!pkg?.workspaces) return [];
  if (Array.isArray(pkg.workspaces)) return [...pkg.workspaces];
  return pkg.workspaces.packages ? [...pkg.workspaces.packages] : [];
}
function readPnpmWorkspacePatterns(cwd = process.cwd()) {
  const wsPath = PATH.resolve(cwd, "pnpm-workspace.yaml");
  if (!existsSync(wsPath)) return [];
  const content = readFileSync(wsPath, "utf8");
  const patterns = [];
  let inPackages = false;
  for (const line of content.split("\n")) {
    if (/^packages\s*:/.test(line.trim())) {
      inPackages = true;
      continue;
    }
    if (inPackages) {
      const match = /^\s+-\s+['"]?([^'"]+)['"]?\s*$/.exec(line);
      if (match) {
        patterns.push(match[1]);
      } else if (line.trim() !== "" && !/^\s/.test(line)) {
        break;
      }
    }
  }
  return patterns;
}
function readWorkspacePatterns(cwd = process.cwd()) {
  const fromPackageJson = readWorkspacePatternsFromPackageJson(cwd);
  return fromPackageJson.length > 0 ? fromPackageJson : readPnpmWorkspacePatterns(cwd);
}
function detectPackageManagerFromPackageJson(cwd = process.cwd()) {
  const packageManager = readRootPackageJson(cwd)?.packageManager;
  if (!packageManager) return void 0;
  return packageManager.split("@")[0];
}

// src/actions/packman/convert.ts
function detectCurrentPM(cwd) {
  const packageManager = detectPackageManagerFromPackageJson(cwd);
  if (packageManager === "bun" || packageManager === "npm" || packageManager === "pnpm" || packageManager === "yarn") {
    return packageManager;
  }
  if (existsSync2(PATH2.join(cwd, "pnpm-lock.yaml")) || existsSync2(PATH2.join(cwd, "pnpm-workspace.yaml"))) {
    return "pnpm";
  }
  if (existsSync2(PATH2.join(cwd, "bun.lock")) || existsSync2(PATH2.join(cwd, "bun.lockb"))) {
    return "bun";
  }
  if (existsSync2(PATH2.join(cwd, "yarn.lock")) || existsSync2(PATH2.join(cwd, ".yarnrc.yml"))) {
    return "yarn";
  }
  if (existsSync2(PATH2.join(cwd, "package-lock.json")) || existsSync2(PATH2.join(cwd, "npm-shrinkwrap.json"))) {
    return "npm";
  }
  return "unknown";
}
function findWorkspacePackagePaths(cwd) {
  const patterns = readWorkspacePatterns(cwd);
  const dirs = [];
  for (const pattern of patterns) {
    const resolved = resolveWorkspaceGlob(cwd, pattern);
    dirs.push(...resolved);
  }
  return dirs;
}
function resolveWorkspaceGlob(cwd, pattern) {
  const parts = pattern.split("/");
  return walkGlob(cwd, parts, "");
}
function walkGlob(basePath, parts, currentPath) {
  if (parts.length === 0) {
    const fullPath = PATH2.join(basePath, currentPath);
    if (existsSync2(PATH2.join(fullPath, "package.json"))) {
      return [currentPath];
    }
    return [];
  }
  const [part, ...rest] = parts;
  const dirPath = PATH2.join(basePath, currentPath);
  if (!existsSync2(dirPath) || !statSync(dirPath).isDirectory()) {
    return [];
  }
  if (part === "*" || part === "**") {
    const entries = readdirSync(dirPath, { withFileTypes: true }).filter((e) => e.isDirectory() && !e.name.startsWith(".") && e.name !== "node_modules" && e.name !== "dist");
    const results = [];
    if (part === "**") {
      results.push(...walkGlob(basePath, rest, currentPath));
    }
    for (const entry of entries) {
      const subPath2 = currentPath ? `${currentPath}/${entry.name}` : entry.name;
      if (part === "**") {
        results.push(
          ...walkGlob(basePath, rest, subPath2),
          ...walkGlob(basePath, parts, subPath2)
        );
      } else {
        results.push(...walkGlob(basePath, rest, subPath2));
      }
    }
    return results;
  }
  const subPath = currentPath ? `${currentPath}/${part}` : part;
  return walkGlob(basePath, rest, subPath);
}

// src/actions/packman/clean.ts
function removeNodeModules(dir, verbose) {
  const nmPath = PATH3.join(dir, "node_modules");
  if (existsSync3(nmPath)) {
    if (verbose) console.log(chalk2.gray(`Removing ${nmPath}`));
    rmSync(nmPath, { force: true, recursive: true });
    return true;
  }
  return false;
}
function cleanLockFiles(cwd, pm) {
  switch (pm) {
    case "yarn": {
      const lockPath = PATH3.join(cwd, "yarn.lock");
      if (existsSync3(lockPath)) {
        writeFileSync(lockPath, "");
        console.log(chalk2.green("Truncated yarn.lock"));
      }
      break;
    }
    case "npm": {
      const lockPath = PATH3.join(cwd, "package-lock.json");
      if (existsSync3(lockPath)) {
        rmSync(lockPath);
        console.log(chalk2.green("Deleted package-lock.json"));
      }
      break;
    }
    case "bun": {
      for (const lockfile of ["bun.lock", "bun.lockb"]) {
        const lockPath = PATH3.join(cwd, lockfile);
        if (existsSync3(lockPath)) {
          rmSync(lockPath);
          console.log(chalk2.green(`Deleted ${lockfile}`));
        }
      }
      break;
    }
    case "pnpm": {
      const lockPath = PATH3.join(cwd, "pnpm-lock.yaml");
      if (existsSync3(lockPath)) {
        rmSync(lockPath);
        console.log(chalk2.green("Deleted pnpm-lock.yaml"));
      }
      break;
    }
  }
}
function packmanClean({ verbose }) {
  const cwd = process.cwd();
  const pm = detectCurrentPM(cwd);
  if (pm === "unknown") {
    console.error(chalk2.red("Could not detect current package manager. No packageManager field or known lockfile found."));
    return 1;
  }
  console.log(chalk2.blue(`Detected package manager: ${pm}`));
  let removedCount = 0;
  if (removeNodeModules(cwd, verbose)) removedCount++;
  const workspacePaths = findWorkspacePackagePaths(cwd);
  for (const wsPath of workspacePaths) {
    if (removeNodeModules(PATH3.join(cwd, wsPath), verbose)) removedCount++;
  }
  console.log(chalk2.green(`Removed ${removedCount} node_modules folder${removedCount === 1 ? "" : "s"}`));
  cleanLockFiles(cwd, pm);
  console.log(chalk2.green("Ready for a clean install"));
  return 0;
}
export {
  packmanClean
};
//# sourceMappingURL=clean.mjs.map