// 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 applyToBag(bag, updateMap) {
  if (!bag) return false;
  let changed = 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;
      changed = true;
    }
  }
  return changed;
}
function applyToPeerBag(pkg, updateMap) {
  const peer = pkg.peerDependencies;
  if (!peer) return false;
  let changed = 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;
      changed = true;
    }
  }
  return changed;
}
function applyToWorkspace(pkgPath, updateMap) {
  let content;
  try {
    content = readFileSync(pkgPath, "utf8");
  } catch {
    return false;
  }
  const pkg = JSON.parse(content);
  const depsChanged = applyToBag(pkg.dependencies, updateMap);
  const devDepsChanged = applyToBag(pkg.devDependencies, updateMap);
  const peerChanged = applyToPeerBag(pkg, updateMap);
  const changed = depsChanged || devDepsChanged || peerChanged;
  if (changed) {
    writeFileSync(pkgPath, `${JSON.stringify(pkg, null, 2)}
`);
  }
  return changed;
}
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 (applyToWorkspace(pkgPath, updateMap)) {
      modified++;
      console.log(chalk.gray(`  Updated ${ws.name}`));
    }
  }
  return modified;
}
export {
  applyUpdates
};
//# sourceMappingURL=applyUpdates.mjs.map
