// src/lib/claudeMdTemplate.ts
import {
  readdirSync,
  readFileSync,
  statSync
} from "node:fs";
import { createRequire } from "node:module";
import PATH from "node:path";
var require2 = createRequire(import.meta.url);
var packageRoot = PATH.dirname(require2.resolve("@xylabs/toolchain/package.json"));
var templatesDir = PATH.resolve(packageRoot, "templates", "claude");
function applyPackageManager(content, pm) {
  const xyCommand = pm === "npm" ? "npm exec -- xy" : pm === "bun" ? "bun run xy" : `${pm} xy`;
  const addCommand = pm === "npm" ? "npm install" : pm === "bun" ? "bun add" : `${pm} add`;
  return content.replaceAll("yarn xy", xyCommand).replaceAll("pnpm xy", xyCommand).replaceAll("yarn add", addCommand).replaceAll("pnpm add", addCommand);
}
var XYLABS_RULES_PREFIX = "xylabs-";
var XYLABS_COMMANDS_PREFIX = "xy-";
var XYLABS_SKILLS_PREFIX = "xylabs-";
var claudeMdRuleTemplates = () => {
  const rulesDir = PATH.resolve(templatesDir, "rules");
  const files = readdirSync(rulesDir).filter((f) => f.startsWith(XYLABS_RULES_PREFIX) && f.endsWith(".md"));
  const result = {};
  for (const file of files) {
    result[file] = readFileSync(PATH.resolve(rulesDir, file), "utf8");
  }
  return result;
};
var claudeCommandTemplates = () => {
  const commandsDir = PATH.resolve(templatesDir, "commands");
  const files = readdirSync(commandsDir).filter((f) => f.startsWith(XYLABS_COMMANDS_PREFIX) && f.endsWith(".md"));
  const result = {};
  for (const file of files) {
    result[file] = readFileSync(PATH.resolve(commandsDir, file), "utf8");
  }
  return result;
};
var claudeSkillTemplates = () => {
  const skillsDir = PATH.resolve(templatesDir, "skills");
  const dirs = readdirSync(skillsDir).filter(
    (f) => f.startsWith(XYLABS_SKILLS_PREFIX) && statSync(PATH.resolve(skillsDir, f)).isDirectory()
  );
  const result = {};
  for (const dir of dirs) {
    const dirPath = PATH.resolve(skillsDir, dir);
    const files = readdirSync(dirPath, { recursive: true, encoding: "utf8" });
    result[dir] = {};
    for (const file of files) {
      if (statSync(PATH.resolve(dirPath, file)).isFile()) {
        result[dir][file] = readFileSync(PATH.resolve(dirPath, file), "utf8");
      }
    }
  }
  return result;
};

// src/pm/workspaces.ts
import { existsSync, readFileSync as readFileSync2 } from "node:fs";
import PATH2 from "node:path";
import { globSync } from "glob";
function readJsonFile(path) {
  if (!existsSync(path)) return void 0;
  try {
    return JSON.parse(readFileSync2(path, "utf8"));
  } catch {
    return void 0;
  }
}
function readRootPackageJson(cwd = process.cwd()) {
  return readJsonFile(PATH2.resolve(cwd, "package.json"));
}
function detectPackageManagerFromPackageJson(cwd = process.cwd()) {
  const packageManager = readRootPackageJson(cwd)?.packageManager;
  if (!packageManager) return void 0;
  return packageManager.split("@")[0];
}

// src/pm/detectPackageManager.ts
import { existsSync as existsSync2 } from "node:fs";
var knownPackageManagers = /* @__PURE__ */ new Set(["bun", "npm", "pnpm", "yarn"]);
function detectPackageManager() {
  const packageManager = detectPackageManagerFromPackageJson();
  if (packageManager && knownPackageManagers.has(packageManager)) {
    return packageManager;
  }
  if (existsSync2("pnpm-lock.yaml") || existsSync2("pnpm-workspace.yaml")) return "pnpm";
  if (existsSync2("bun.lock") || existsSync2("bun.lockb")) return "bun";
  if (existsSync2("yarn.lock") || existsSync2(".yarnrc.yml")) return "yarn";
  if (existsSync2("package-lock.json") || existsSync2("npm-shrinkwrap.json")) return "npm";
  return "yarn";
}

// src/lib/initCwd.ts
function INIT_CWD() {
  return process.env.INIT_CWD ?? process.cwd();
}

// src/lib/reporting/runWithEnvelope.ts
import { performance as performance2 } from "node:perf_hooks";

// src/lib/reporting/xyReporter.ts
import { performance } from "node:perf_hooks";
var jsonMode = false;
var originalStdoutWrite;
var envelopeEmitted = false;
var currentCommand = "unknown";
var startTime = 0;
function isJsonMode() {
  return jsonMode;
}
function setCurrentCommand(name) {
  currentCommand = name;
  startTime = performance.now();
  envelopeEmitted = false;
}
function emitJson(envelope) {
  if (envelopeEmitted) return;
  envelopeEmitted = true;
  const json = JSON.stringify(envelope) + "\n";
  if (originalStdoutWrite) {
    originalStdoutWrite(json);
  } else {
    process.stdout.write(json);
  }
}

// src/lib/reporting/runWithEnvelope.ts
async function runWithEnvelope(command, action) {
  setCurrentCommand(command);
  const start = performance2.now();
  let exitCode;
  let envelope;
  try {
    const ret = await action();
    if (typeof ret === "number") {
      exitCode = ret;
    } else {
      exitCode = ret.exitCode;
      envelope = ret.envelope;
    }
  } catch (ex) {
    exitCode = 1;
    const message = ex instanceof Error ? ex.message : String(ex);
    envelope = {
      errorCount: 1,
      errors: [{ message }]
    };
    if (!isJsonMode()) {
      console.error(message);
    }
  }
  if (isJsonMode()) {
    emitJson({
      command,
      data: envelope?.data,
      durationMs: Math.round(performance2.now() - start),
      errorCount: envelope?.errorCount ?? (exitCode === 0 ? 0 : 1),
      errors: envelope?.errors,
      exitCode,
      schemaVersion: 1,
      success: exitCode === 0,
      warningCount: envelope?.warningCount ?? 0,
      warnings: envelope?.warnings
    });
  }
  return exitCode;
}
async function withEnvelope(command, action) {
  process.exitCode = await runWithEnvelope(command, action);
}

// src/actions/claude-check.ts
import {
  existsSync as existsSync3,
  readdirSync as readdirSync2,
  readFileSync as readFileSync3,
  statSync as statSync2
} from "node:fs";
import PATH3 from "node:path";
import chalk from "chalk";
var checkCommands = (commandsDir) => {
  const pm = detectPackageManager();
  const rawTemplates = claudeCommandTemplates();
  const templates = {};
  for (const [name, content] of Object.entries(rawTemplates)) {
    templates[name] = applyPackageManager(content, pm);
  }
  const missing = [];
  const outdated = [];
  for (const [filename, content] of Object.entries(templates)) {
    const targetPath = PATH3.resolve(commandsDir, filename);
    if (!existsSync3(targetPath)) {
      missing.push(filename);
    } else if (readFileSync3(targetPath, "utf8") !== content) {
      outdated.push(filename);
    }
  }
  const templateNames = new Set(Object.keys(templates));
  const stale = existsSync3(commandsDir) ? readdirSync2(commandsDir).filter((f) => f.startsWith(XYLABS_COMMANDS_PREFIX) && f.endsWith(".md") && !templateNames.has(f)) : [];
  return {
    missing,
    outdated,
    stale
  };
};
var checkRules = (rulesDir) => {
  const pm = detectPackageManager();
  const rawTemplates = claudeMdRuleTemplates();
  const templates = {};
  for (const [name, content] of Object.entries(rawTemplates)) {
    templates[name] = applyPackageManager(content, pm);
  }
  const missing = [];
  const outdated = [];
  for (const [filename, content] of Object.entries(templates)) {
    const targetPath = PATH3.resolve(rulesDir, filename);
    if (!existsSync3(targetPath)) {
      missing.push(filename);
    } else if (readFileSync3(targetPath, "utf8") !== content) {
      outdated.push(filename);
    }
  }
  const templateNames = new Set(Object.keys(templates));
  const stale = existsSync3(rulesDir) ? readdirSync2(rulesDir).filter((f) => f.startsWith(XYLABS_RULES_PREFIX) && f.endsWith(".md") && !templateNames.has(f)) : [];
  return {
    missing,
    outdated,
    stale
  };
};
var checkSkills = (skillsDir) => {
  const pm = detectPackageManager();
  const rawTemplates = claudeSkillTemplates();
  const missing = [];
  const outdated = [];
  for (const [skillName, files] of Object.entries(rawTemplates)) {
    const skillDir = PATH3.resolve(skillsDir, skillName);
    if (!existsSync3(skillDir)) {
      missing.push(skillName);
      continue;
    }
    for (const [filename, rawContent] of Object.entries(files)) {
      const content = applyPackageManager(rawContent, pm);
      const targetPath = PATH3.resolve(skillDir, filename);
      if (!existsSync3(targetPath)) {
        missing.push(`${skillName}/${filename}`);
      } else if (readFileSync3(targetPath, "utf8") !== content) {
        outdated.push(`${skillName}/${filename}`);
      }
    }
  }
  const templateNames = new Set(Object.keys(rawTemplates));
  const stale = existsSync3(skillsDir) ? readdirSync2(skillsDir).filter(
    (f) => f.startsWith(XYLABS_SKILLS_PREFIX) && statSync2(PATH3.resolve(skillsDir, f)).isDirectory() && !templateNames.has(f)
  ) : [];
  return {
    missing,
    outdated,
    stale
  };
};
var logSection = (label, result) => {
  const issues = [...result.missing, ...result.outdated, ...result.stale];
  if (issues.length === 0) {
    console.log(chalk.green(`  \u2714 ${label}`));
    return true;
  }
  console.log(chalk.red(`  \u2718 ${label}`));
  for (const file of result.missing) {
    console.log(chalk.yellow(`      missing: ${file}`));
  }
  for (const file of result.outdated) {
    console.log(chalk.yellow(`      outdated: ${file}`));
  }
  for (const file of result.stale) {
    console.log(chalk.yellow(`      stale: ${file}`));
  }
  return false;
};
function claudeCheck() {
  const cwd = INIT_CWD();
  const claudeDir = PATH3.resolve(cwd, ".claude");
  console.log(chalk.bold("Claude configuration check:"));
  console.log();
  const commandsResult = checkCommands(PATH3.resolve(claudeDir, "commands"));
  const rulesResult = checkRules(PATH3.resolve(claudeDir, "rules"));
  const skillsResult = checkSkills(PATH3.resolve(claudeDir, "skills"));
  const commandsOk = logSection("commands", commandsResult);
  const rulesOk = logSection("rules", rulesResult);
  const skillsOk = logSection("skills", skillsResult);
  console.log();
  if (commandsOk && rulesOk && skillsOk) {
    console.log(chalk.green("All Claude configuration is up to date."));
  } else {
    console.log(chalk.yellow("Run `xy claude init` to sync all configuration."));
  }
  return 0;
}

// src/xy/common/claude/checkCommand.ts
var checkCommand = {
  command: "check",
  describe: "Check if Claude configuration is up to date with templates",
  handler: async (argv) => {
    if (argv.verbose) console.log("Claude Check");
    await withEnvelope("claude check", () => claudeCheck());
  }
};
export {
  checkCommand
};
//# sourceMappingURL=checkCommand.mjs.map
