// src/actions/package-lint-pnpm.ts
import {
  existsSync,
  readFileSync,
  writeFileSync
} from "node:fs";
import PATH from "node:path";
import chalk from "chalk";
import * as yaml from "yaml";
function emptyResult() {
  return {
    errors: [],
    fixable: [],
    warnings: []
  };
}
function pnpmWorkspacePath(cwd) {
  return PATH.resolve(cwd, "pnpm-workspace.yaml");
}
function readPnpmWorkspaceDocument(cwd) {
  const wsPath = pnpmWorkspacePath(cwd);
  if (!existsSync(wsPath)) return void 0;
  try {
    return yaml.parseDocument(readFileSync(wsPath, "utf8"));
  } catch {
    return void 0;
  }
}
function readPnpmWorkspaceGlobs(cwd) {
  const doc = readPnpmWorkspaceDocument(cwd);
  if (!doc) return void 0;
  const packages = doc.get("packages");
  if (!yaml.isSeq(packages)) return void 0;
  const globs = [];
  for (const item of packages.items) {
    const value = yaml.isScalar(item) ? item.value : item;
    if (typeof value === "string") globs.push(value);
  }
  return globs.length > 0 ? globs : void 0;
}
var PNPM_RELEASE_AGE_REQUIRED_EXCLUDES = ["@xylabs/*", "@xyo-network/*"];
function readSequenceStrings(node) {
  if (!yaml.isSeq(node)) return [];
  const out = [];
  for (const item of node.items) {
    const value = yaml.isScalar(item) ? item.value : item;
    if (typeof value === "string") out.push(value);
  }
  return out;
}
function checkPnpmReleaseAgeExcludes(cwd, pm) {
  const result = emptyResult();
  if (pm !== "pnpm") return result;
  const doc = readPnpmWorkspaceDocument(cwd);
  if (!doc) return result;
  const existing = readSequenceStrings(doc.get("minimumReleaseAgeExclude"));
  for (const required of PNPM_RELEASE_AGE_REQUIRED_EXCLUDES) {
    if (!existing.includes(required)) {
      result.fixable.push(`pnpm-workspace.yaml minimumReleaseAgeExclude is missing '${required}'`);
    }
  }
  return result;
}
function fixPnpmReleaseAgeExcludes(cwd) {
  const doc = readPnpmWorkspaceDocument(cwd);
  if (!doc) return;
  if (!yaml.isMap(doc.contents)) {
    console.log(chalk.yellow("  \u26A0 pnpm-workspace.yaml has no top-level map; skipping fix"));
    return;
  }
  let seq = doc.get("minimumReleaseAgeExclude");
  if (!yaml.isSeq(seq)) {
    seq = new yaml.YAMLSeq();
    doc.set("minimumReleaseAgeExclude", seq);
  }
  const seqNode = seq;
  const existing = new Set(readSequenceStrings(seqNode));
  let added = false;
  for (const required of PNPM_RELEASE_AGE_REQUIRED_EXCLUDES) {
    if (existing.has(required)) continue;
    seqNode.add(required);
    existing.add(required);
    added = true;
  }
  if (!added) return;
  writeFileSync(pnpmWorkspacePath(cwd), String(doc), "utf8");
  console.log(chalk.green("  \u2714 Fixed: added @xylabs/* and @xyo-network/* to minimumReleaseAgeExclude in pnpm-workspace.yaml"));
}
export {
  checkPnpmReleaseAgeExcludes,
  fixPnpmReleaseAgeExcludes,
  readPnpmWorkspaceDocument,
  readPnpmWorkspaceGlobs
};
//# sourceMappingURL=package-lint-pnpm.mjs.map
