// src/lib/updo/applyUpdates.ts
import { readFileSync, writeFileSync } from "node:fs";
import PATH from "node:path";
import chalk from "chalk";
import semver from "semver";
function isSimpleRange(range) {
  const trimmed = range.trim();
  if (trimmed.startsWith("^") || trimmed.startsWith("~")) return true;
  return semver.valid(trimmed) !== null;
}
function shouldApplyToBag(bag, updateMap) {
  if (!bag) return false;
  let isChanged = false;
  for (const name of Object.keys(bag)) {
    const update = updateMap.get(name);
    if (!update) continue;
    if (bag[name] !== update.targetRange) {
      bag[name] = update.targetRange;
      isChanged = true;
    }
  }
  return isChanged;
}
function shouldApplyToPeerBag(pkg, updateMap) {
  const peer = pkg.peerDependencies;
  if (peer === void 0) return false;
  let isChanged = false;
  for (const name of Object.keys(peer)) {
    const update = updateMap.get(name);
    if (!update) continue;
    if (pkg.dependencies?.[name] !== void 0) continue;
    if (pkg.devDependencies?.[name] !== void 0) continue;
    if (!isSimpleRange(peer[name])) continue;
    if (peer[name] !== update.targetRange) {
      peer[name] = update.targetRange;
      isChanged = true;
    }
  }
  return isChanged;
}
function shouldApplyToWorkspace(pkgPath, updateMap) {
  let content;
  try {
    content = readFileSync(pkgPath, "utf8");
  } catch {
    return false;
  }
  const pkg = JSON.parse(content);
  const isDepsChanged = shouldApplyToBag(pkg.dependencies, updateMap);
  const isDevDepsChanged = shouldApplyToBag(pkg.devDependencies, updateMap);
  const isPeerChanged = shouldApplyToPeerBag(pkg, updateMap);
  const isChanged = isDepsChanged || isDevDepsChanged || isPeerChanged;
  if (isChanged) {
    writeFileSync(pkgPath, `${JSON.stringify(pkg, null, 2)}
`);
  }
  return isChanged;
}
function applyUpdates(cwd, workspaces, updates) {
  const updateMap = new Map(updates.map((u) => [u.name, u]));
  let modified = 0;
  for (const ws of workspaces) {
    const pkgPath = PATH.resolve(cwd, ws.location, "package.json");
    if (shouldApplyToWorkspace(pkgPath, updateMap)) {
      modified++;
      console.log(chalk.gray(`  Updated ${ws.name}`));
    }
  }
  return modified;
}
export {
  applyUpdates
};
//# sourceMappingURL=applyUpdates.mjs.map
