// src/actions/package-lint-pnpm.ts
import {
  existsSync,
  readFileSync,
  writeFileSync
} from "node:fs";
import PATH from "node:path";
import chalk from "chalk";
import * as yaml2 from "yaml";

// src/lib/pnpmConfig/readMinReleaseAge.ts
import * as yaml from "yaml";
var DEFAULT_MINIMUM_RELEASE_AGE_MINUTES = 1440;

// src/actions/package-lint-pnpm.ts
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 yaml2.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 (!yaml2.isSeq(packages)) return void 0;
  const globs = [];
  for (const item of packages.items) {
    const value = yaml2.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 (!yaml2.isSeq(node)) return [];
  const out = [];
  for (const item of node.items) {
    const value = yaml2.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 isRecord(value) {
  return typeof value === "object" && value !== null && !Array.isArray(value);
}
function isConfiguredValue(value) {
  if (value === void 0 || value === null) return false;
  if (isRecord(value)) return Object.keys(value).length > 0;
  if (Array.isArray(value)) return value.length > 0;
  return value !== "";
}
function configuredYamlKeys(node) {
  if (!yaml2.isMap(node)) return [];
  const keys = [];
  for (const item of node.items) {
    const key = yaml2.isScalar(item.key) ? item.key.value : item.key;
    if (typeof key === "string" || typeof key === "number") keys.push(String(key));
  }
  return keys;
}
function isConfiguredYamlNode(node) {
  if (node === void 0 || node === null) return false;
  if (yaml2.isMap(node) || yaml2.isSeq(node)) return node.items.length > 0;
  if (yaml2.isScalar(node)) return node.value !== void 0 && node.value !== null && node.value !== "";
  return true;
}
function formatOverrideWarning(location, keys) {
  if (keys.length === 0) return `${location} defines dependency overrides`;
  const shown = keys.slice(0, 5).join(", ");
  const suffix = keys.length > 5 ? `, and ${keys.length - 5} more` : "";
  return `${location} defines ${keys.length} dependency override${keys.length === 1 ? "" : "s"}: ${shown}${suffix}`;
}
function checkPnpmDependencyOverrides(cwd, pm, rootPkg) {
  const result = emptyResult();
  if (pm !== "pnpm") return result;
  const pnpmConfig = isRecord(rootPkg.pnpm) ? rootPkg.pnpm : void 0;
  const packageJsonOverrides = pnpmConfig?.overrides;
  if (isConfiguredValue(packageJsonOverrides)) {
    result.warnings.push(formatOverrideWarning(
      "Root package.json pnpm.overrides field",
      isRecord(packageJsonOverrides) ? Object.keys(packageJsonOverrides) : []
    ));
  }
  const doc = readPnpmWorkspaceDocument(cwd);
  const workspaceOverrides = doc?.get("overrides");
  if (isConfiguredYamlNode(workspaceOverrides)) {
    result.warnings.push(formatOverrideWarning(
      "pnpm-workspace.yaml overrides field",
      configuredYamlKeys(workspaceOverrides)
    ));
  }
  return result;
}
function isMinimumReleaseAgeSatisfied(value) {
  return value !== void 0 && value !== null;
}
function checkPnpmMinimumReleaseAge(cwd, pm) {
  const result = emptyResult();
  if (pm !== "pnpm") return result;
  const doc = readPnpmWorkspaceDocument(cwd);
  if (!doc) return result;
  if (!isMinimumReleaseAgeSatisfied(doc.get("minimumReleaseAge"))) {
    result.fixable.push(`pnpm-workspace.yaml is missing minimumReleaseAge (recommended: ${DEFAULT_MINIMUM_RELEASE_AGE_MINUTES})`);
  }
  return result;
}
function setWorkspaceScalar(cwd, key, value, isSatisfied, successMessage) {
  const doc = readPnpmWorkspaceDocument(cwd);
  if (!doc) return;
  if (!yaml2.isMap(doc.contents)) {
    console.log(chalk.yellow("  \u26A0 pnpm-workspace.yaml has no top-level map; skipping fix"));
    return;
  }
  if (isSatisfied(doc.get(key))) return;
  doc.set(key, value);
  writeFileSync(pnpmWorkspacePath(cwd), String(doc), "utf8");
  console.log(chalk.green(successMessage));
}
function fixPnpmMinimumReleaseAge(cwd) {
  setWorkspaceScalar(
    cwd,
    "minimumReleaseAge",
    DEFAULT_MINIMUM_RELEASE_AGE_MINUTES,
    isMinimumReleaseAgeSatisfied,
    `  \u2714 Fixed: set minimumReleaseAge: ${DEFAULT_MINIMUM_RELEASE_AGE_MINUTES} in pnpm-workspace.yaml`
  );
}
function fixPnpmReleaseAgeExcludes(cwd) {
  const doc = readPnpmWorkspaceDocument(cwd);
  if (!doc) return;
  if (!yaml2.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 (!yaml2.isSeq(seq)) {
    seq = new yaml2.YAMLSeq();
    doc.set("minimumReleaseAgeExclude", seq);
  }
  const seqNode = seq;
  const existing = new Set(readSequenceStrings(seqNode));
  let isAdded = false;
  for (const required of PNPM_RELEASE_AGE_REQUIRED_EXCLUDES) {
    if (existing.has(required)) continue;
    seqNode.add(required);
    existing.add(required);
    isAdded = true;
  }
  if (!isAdded) 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 {
  checkPnpmDependencyOverrides,
  checkPnpmMinimumReleaseAge,
  checkPnpmReleaseAgeExcludes,
  fixPnpmMinimumReleaseAge,
  fixPnpmReleaseAgeExcludes,
  readPnpmWorkspaceDocument,
  readPnpmWorkspaceGlobs
};
//# sourceMappingURL=package-lint-pnpm.mjs.map
