// src/actions/packman/swapTsScriptsDependency.ts
import {
  existsSync,
  readFileSync,
  writeFileSync
} from "fs";
import PATH from "path";
import chalk from "chalk";
var managedPackages = [
  "@xylabs/toolchain",
  "@xylabs/ts-scripts-pnpm",
  "@xylabs/ts-scripts-yarn3"
];
function targetToolchainPackage(target) {
  switch (target) {
    case "pnpm": {
      return "@xylabs/ts-scripts-pnpm";
    }
    case "yarn": {
      return "@xylabs/ts-scripts-yarn3";
    }
    default: {
      return "@xylabs/toolchain";
    }
  }
}
function swapInPackageJson(pkgPath, target) {
  if (!existsSync(pkgPath)) return false;
  const raw = readFileSync(pkgPath, "utf8");
  const pkg = JSON.parse(raw);
  const targetPackage = targetToolchainPackage(target);
  let changed = false;
  for (const depField of ["dependencies", "devDependencies"]) {
    const deps = pkg[depField];
    if (!deps) continue;
    const existingVersion = managedPackages.map((name) => deps[name]).find(Boolean);
    if (!existingVersion) continue;
    for (const name of managedPackages) {
      if (deps[name]) {
        delete deps[name];
        changed = true;
      }
    }
    deps[targetPackage] = existingVersion;
  }
  if (changed) {
    writeFileSync(pkgPath, JSON.stringify(pkg, null, 2) + "\n", "utf8");
  }
  return changed;
}
function swapTsScriptsDependency(cwd, workspacePackageJsonPaths, target) {
  let count = 0;
  if (swapInPackageJson(PATH.join(cwd, "package.json"), target)) {
    count++;
  }
  for (const pkgPath of workspacePackageJsonPaths) {
    const fullPath = PATH.resolve(cwd, pkgPath, "package.json");
    if (swapInPackageJson(fullPath, target)) {
      count++;
    }
  }
  if (count > 0) {
    console.log(chalk.green(`  Set toolchain dependency to ${targetToolchainPackage(target)} in ${count} package(s)`));
  }
}
export {
  swapTsScriptsDependency
};
//# sourceMappingURL=swapTsScriptsDependency.mjs.map