// src/actions/lint-init.ts
import {
  existsSync as existsSync3,
  readFileSync as readFileSync3,
  unlinkSync,
  writeFileSync
} from "node:fs";
import PATH2 from "node:path";
import { createInterface } from "node:readline";
import chalk3 from "chalk";
import { globSync as globSync2 } from "glob";

// src/lib/crossSpawn.ts
import crossSpawn from "cross-spawn";
function spawnSync(command, args, options) {
  return crossSpawn.sync(command, args, options);
}

// src/lib/packageManagerRuntime.ts
import fs from "node:fs";
import chalk from "chalk";
var DISPLAY_NAMES = {
  bun: "Bun",
  npm: "npm",
  pnpm: "pnpm",
  yarn: "Yarn"
};
var MAC_INSTALL_COMMANDS = {
  bun: "brew install oven-sh/bun/bun",
  npm: "brew install node",
  pnpm: "brew install pnpm",
  yarn: "brew install yarn"
};
function currentPlatform() {
  if (process.platform === "darwin" || process.platform === "linux" || process.platform === "win32") {
    return process.platform;
  }
  return "unknown";
}
function askYesNo(question) {
  if (!process.stdin.isTTY || !process.stdout.isTTY) {
    return false;
  }
  process.stdout.write(question);
  const buffer = Buffer.alloc(1024);
  const bytesRead = fs.readSync(process.stdin.fd, buffer, 0, buffer.length, null);
  const answer = buffer.toString("utf8", 0, bytesRead).trim().toLowerCase();
  return answer === "y" || answer === "yes";
}
function isCommandInstalled(command) {
  const result = spawnSync(command, ["--version"], {
    encoding: "utf8",
    stdio: "ignore"
  });
  return !result.error && result.status === 0;
}
function isPackageManagerInstalled(pm) {
  return isCommandInstalled(pm);
}
function getPackageManagerInstallPlan(pm, platform = currentPlatform()) {
  const displayName = DISPLAY_NAMES[pm];
  if (platform === "darwin") {
    const command = MAC_INSTALL_COMMANDS[pm];
    return {
      command,
      manualInstructions: [
        `Install ${displayName} with: ${command}`
      ],
      packageManager: pm,
      platform,
      supported: true
    };
  }
  if (platform === "linux") {
    return {
      manualInstructions: [
        `Automatic installation for ${displayName} is not implemented on Linux yet.`,
        `Install ${displayName} manually and re-run the command.`
      ],
      packageManager: pm,
      platform,
      supported: false
    };
  }
  if (platform === "win32") {
    return {
      manualInstructions: [
        `Automatic installation for ${displayName} is not implemented on Windows yet.`,
        `Install ${displayName} manually and re-run the command.`
      ],
      packageManager: pm,
      platform,
      supported: false
    };
  }
  return {
    manualInstructions: [
      `Automatic installation for ${displayName} is not implemented on ${platform} yet.`,
      `Install ${displayName} manually and re-run the command.`
    ],
    packageManager: pm,
    platform,
    supported: false
  };
}
function printManualInstructions(plan, context) {
  console.error(chalk.yellow(`${DISPLAY_NAMES[plan.packageManager]} is required for "${context.operation}".`));
  for (const line of plan.manualInstructions) {
    console.error(chalk.gray(`  ${line}`));
  }
}
function installWithHomebrew(pm, cwd) {
  const command = MAC_INSTALL_COMMANDS[pm];
  const result = spawnSync("brew", command.replace("brew ", "").split(" "), {
    cwd,
    encoding: "utf8",
    stdio: "inherit"
  });
  return result.status === 0;
}
function ensurePackageManagerInstalled(pm, context) {
  if (isPackageManagerInstalled(pm)) return true;
  const plan = getPackageManagerInstallPlan(pm, context.platform ?? currentPlatform());
  const displayName = DISPLAY_NAMES[pm];
  console.error(chalk.yellow(`${context.operation} requires ${displayName}, but it is not installed.`));
  if (!plan.supported) {
    printManualInstructions(plan, context);
    return false;
  }
  if (!isCommandInstalled("brew")) {
    console.error(chalk.yellow("Homebrew is not installed, so automatic installation is unavailable."));
    console.error(chalk.gray("  Install Homebrew from https://brew.sh and then run:"));
    console.error(chalk.gray(`  ${plan.command}`));
    return false;
  }
  const confirmed = askYesNo(chalk.cyan(`Install ${displayName} with Homebrew now? [y/N] `));
  if (!confirmed) {
    console.error(chalk.gray(`Skipping install. Run "${plan.command}" manually and then retry.`));
    return false;
  }
  console.error(chalk.cyan(`Installing ${displayName} via Homebrew...
`));
  if (!installWithHomebrew(pm, context.cwd)) {
    console.error(chalk.red(`Homebrew failed to install ${displayName}.`));
    console.error(chalk.gray(`Run "${plan.command}" manually and then retry.`));
    return false;
  }
  if (!isPackageManagerInstalled(pm)) {
    console.error(chalk.red(`${displayName} still does not appear to be installed after Homebrew completed.`));
    console.error(chalk.gray(`Run "${plan.command}" manually and then retry.`));
    return false;
  }
  console.error(chalk.green(`${displayName} installed successfully.`));
  return true;
}
function failureResult() {
  return {
    output: ["", ""],
    pid: 0,
    signal: null,
    status: 1,
    stderr: "",
    stdout: ""
  };
}
function spawnPackageManagerSync(pm, args, options) {
  if (!ensurePackageManagerInstalled(pm, options.context)) {
    return failureResult();
  }
  return spawnSync(pm, args, { encoding: "utf8", ...options });
}

// src/pm/workspaces.ts
import { existsSync, readFileSync } from "node:fs";
import PATH from "node:path";
import { globSync } from "glob";
function readJsonFile(path) {
  if (!existsSync(path)) return void 0;
  try {
    return JSON.parse(readFileSync(path, "utf8"));
  } catch {
    return void 0;
  }
}
function readRootPackageJson(cwd = process.cwd()) {
  return readJsonFile(PATH.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/toolchainVersion.ts
import { readFileSync as readFileSync2 } from "node:fs";
import { createRequire } from "node:module";
var require2 = createRequire(import.meta.url);
function bundledToolchainVersion() {
  const pkgPath = require2.resolve("@xylabs/toolchain/package.json");
  const pkg = JSON.parse(readFileSync2(pkgPath, "utf8"));
  if (!pkg.version) throw new Error("Could not read @xylabs/toolchain version");
  return pkg.version;
}
function bundledToolchainRange() {
  return `^${bundledToolchainVersion()}`;
}

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

// src/lib/runInstall.ts
import chalk2 from "chalk";
function runInstall(cwd) {
  const pm = detectPackageManager();
  console.log(chalk2.gray(`Running ${pm} install...`));
  const result = spawnPackageManagerSync(pm, ["install"], {
    context: { cwd, operation: `Run ${pm} install` },
    cwd,
    encoding: "utf8",
    stdio: "inherit"
  });
  if (result.status !== 0) {
    console.warn(chalk2.yellow(`${pm} install failed`));
    return false;
  }
  console.log(chalk2.green("Dependencies installed"));
  return true;
}

// src/actions/lint-init.ts
function askConfirmation(question) {
  const rl = createInterface({ input: process.stdin, output: process.stdout });
  return new Promise((resolve) => {
    rl.question(question, (answer) => {
      rl.close();
      resolve(answer.toLowerCase() === "y" || answer.toLowerCase() === "yes");
    });
  });
}
var DISALLOWED_IMPORTS_XYLABS = [
  "@xylabs/api",
  "@xylabs/array",
  "@xylabs/arraybuffer",
  "@xylabs/assert",
  "@xylabs/base",
  "@xylabs/bignumber",
  "@xylabs/buffer",
  "@xylabs/creatable",
  "@xylabs/decimal-precision",
  "@xylabs/delay",
  "@xylabs/enum",
  "@xylabs/error",
  "@xylabs/eth-address",
  "@xylabs/events",
  "@xylabs/exists",
  "@xylabs/fetch",
  "@xylabs/forget",
  "@xylabs/function-name",
  "@xylabs/hex",
  "@xylabs/logger",
  "@xylabs/object",
  "@xylabs/platform",
  "@xylabs/profile",
  "@xylabs/promise",
  "@xylabs/retry",
  "@xylabs/set",
  "@xylabs/static-implements",
  "@xylabs/storage",
  "@xylabs/telemetry",
  "@xylabs/telemetry-exporter",
  "@xylabs/timer",
  "@xylabs/typeof",
  "@xylabs/url",
  "@xylabs/zod"
];
var DISALLOWED_IMPORTS_XYO = [
  "@xyo-network/account",
  "@xyo-network/account-model",
  "@xyo-network/address-payload-plugin",
  "@xyo-network/api",
  "@xyo-network/api-location-diviner",
  "@xyo-network/api-models",
  "@xyo-network/archivist",
  "@xyo-network/archivist-abstract",
  "@xyo-network/archivist-memory",
  "@xyo-network/archivist-model",
  "@xyo-network/archivist-wrapper",
  "@xyo-network/boundwitness",
  "@xyo-network/boundwitness-builder",
  "@xyo-network/boundwitness-loader",
  "@xyo-network/boundwitness-model",
  "@xyo-network/boundwitness-validator",
  "@xyo-network/boundwitness-wrapper",
  "@xyo-network/bridge",
  "@xyo-network/bridge-abstract",
  "@xyo-network/bridge-model",
  "@xyo-network/bridge-wrapper",
  "@xyo-network/config-payload-plugin",
  "@xyo-network/core",
  "@xyo-network/core-payload-plugins",
  "@xyo-network/crypto",
  "@xyo-network/data",
  "@xyo-network/diviner",
  "@xyo-network/diviner-abstract",
  "@xyo-network/diviner-model",
  "@xyo-network/diviner-wrapper",
  "@xyo-network/dns",
  "@xyo-network/domain-payload-plugin",
  "@xyo-network/elliptic",
  "@xyo-network/hash",
  "@xyo-network/huri",
  "@xyo-network/id-payload-plugin",
  "@xyo-network/key-model",
  "@xyo-network/manifest",
  "@xyo-network/manifest-model",
  "@xyo-network/manifest-wrapper",
  "@xyo-network/metamask-connector",
  "@xyo-network/module",
  "@xyo-network/module-abstract",
  "@xyo-network/module-event-emitter",
  "@xyo-network/module-factory-locator",
  "@xyo-network/module-model",
  "@xyo-network/module-resolver",
  "@xyo-network/module-wrapper",
  "@xyo-network/modules",
  "@xyo-network/network",
  "@xyo-network/node",
  "@xyo-network/node-abstract",
  "@xyo-network/node-memory",
  "@xyo-network/node-model",
  "@xyo-network/node-wrapper",
  "@xyo-network/payload",
  "@xyo-network/payload-builder",
  "@xyo-network/payload-model",
  "@xyo-network/payload-plugin",
  "@xyo-network/payload-validator",
  "@xyo-network/payload-wrapper",
  "@xyo-network/payloadset-plugin",
  "@xyo-network/previous-hash-store",
  "@xyo-network/protocol",
  "@xyo-network/quadkey",
  "@xyo-network/query-payload-plugin",
  "@xyo-network/schema-cache",
  "@xyo-network/schema-name-validator",
  "@xyo-network/schema-payload-plugin",
  "@xyo-network/sdk-protocol-js",
  "@xyo-network/sdk-utils",
  "@xyo-network/sentinel",
  "@xyo-network/sentinel-abstract",
  "@xyo-network/sentinel-memory",
  "@xyo-network/sentinel-model",
  "@xyo-network/sentinel-wrapper",
  "@xyo-network/value-payload-plugin",
  "@xyo-network/wallet",
  "@xyo-network/wallet-model",
  "@xyo-network/wasm",
  "@xyo-network/witness",
  "@xyo-network/witness-abstract",
  "@xyo-network/witness-model",
  "@xyo-network/witness-wrapper"
];
var XYLABS_SDK_IMPORT_MESSAGE = "Use '@xylabs/sdk-js' instead.";
var XYO_SDK_IMPORT_MESSAGE = "Use '@xyo-network/sdk-js' instead.";
function getRequiredDevDependencies(react) {
  const configPkg = react ? "@xylabs/eslint-config-react-flat" : "@xylabs/eslint-config-flat";
  return {
    [configPkg]: bundledToolchainRange(),
    eslint: "^10.0.0"
  };
}
function formatDisallowedArray(name, imports, message) {
  const items = imports.map((i) => `  { name: '${i}', message: "${message}" },`).join("\n");
  return `const ${name} = [
${items}
]`;
}
function generateEslintConfig({
  react,
  useXyLabsBarrel,
  useXyoBarrel
}) {
  const configPkg = react ? "@xylabs/eslint-config-react-flat" : "@xylabs/eslint-config-flat";
  const lines = [
    "import type { Linter } from 'eslint'",
    "",
    `import { config as xylabsConfig } from '${configPkg}'`,
    ""
  ];
  if (useXyLabsBarrel) {
    lines.push(formatDisallowedArray("disallowedImportsXyLabs", DISALLOWED_IMPORTS_XYLABS, XYLABS_SDK_IMPORT_MESSAGE), "");
  }
  if (useXyoBarrel) {
    lines.push(formatDisallowedArray("disallowedImportsXyo", DISALLOWED_IMPORTS_XYO, XYO_SDK_IMPORT_MESSAGE), "");
  }
  lines.push("const config: Linter.Config[] = [", "  { ignores: ['.yarn/**', 'build', '**/build/**', '**/dist/**', 'dist', 'node_modules/**', '**/node_modules/**', '**/*.md/**', '.claude/worktrees/*'] },", "  ...xylabsConfig,");
  if (useXyLabsBarrel || useXyoBarrel) {
    lines.push("  {", "    rules:", "    {", "      'no-restricted-imports': [", "        'warn',", "        {");
    if (useXyLabsBarrel && useXyoBarrel) {
      lines.push("          paths: [", "            ...disallowedImportsXyLabs,", "            ...disallowedImportsXyo,", "          ],");
    } else if (useXyLabsBarrel) {
      lines.push("          paths: [", "            ...disallowedImportsXyLabs,", "          ],");
    } else {
      lines.push("          paths: [", "            ...disallowedImportsXyo,", "          ],");
    }
    lines.push("        },", "      ],", "    },", "  },");
  }
  lines.push("]", "", "export default config", "");
  return lines.join("\n");
}
function addDevDependencies(packageJsonPath, requiredDeps, verbose) {
  const content = readFileSync3(packageJsonPath, "utf8");
  const pkg = JSON.parse(content);
  const devDeps = pkg.devDependencies ?? {};
  let changed = false;
  for (const [name, version] of Object.entries(requiredDeps)) {
    if (!devDeps[name]) {
      devDeps[name] = version;
      changed = true;
      if (verbose) console.log(chalk3.gray(`  Added ${name}@${version} to devDependencies`));
    } else if (verbose) {
      console.log(chalk3.gray(`  ${name} already in devDependencies`));
    }
  }
  if (changed) {
    const sorted = Object.fromEntries(Object.entries(devDeps).toSorted(([a], [b]) => a.localeCompare(b)));
    pkg.devDependencies = sorted;
    writeFileSync(packageJsonPath, `${JSON.stringify(pkg, null, 2)}
`, "utf8");
    console.log(chalk3.green("Updated package.json devDependencies"));
  } else {
    console.log(chalk3.gray("package.json devDependencies already up to date"));
  }
  return changed;
}
function hasReactDependency(packageJsonPath) {
  try {
    const content = readFileSync3(packageJsonPath, "utf8");
    const pkg = JSON.parse(content);
    const deps = pkg.dependencies;
    const devDeps = pkg.devDependencies;
    const peerDeps = pkg.peerDependencies;
    return deps?.react != null || devDeps?.react != null || peerDeps?.react != null;
  } catch {
    return false;
  }
}
function detectReactInMonorepo(cwd, verbose) {
  const rootPkgPath = PATH2.resolve(cwd, "package.json");
  if (hasReactDependency(rootPkgPath)) {
    if (verbose) console.log(chalk3.gray("  React detected in package.json"));
    return true;
  }
  const packageJsonPaths = globSync2("packages/**/package.json", {
    cwd,
    ignore: ["**/node_modules/**"]
  });
  for (const relPath of packageJsonPaths) {
    const fullPath = PATH2.resolve(cwd, relPath);
    if (hasReactDependency(fullPath)) {
      if (verbose) console.log(chalk3.gray(`  React detected in ${relPath}`));
      return true;
    }
  }
  return false;
}
function findExistingConfig(configPath, legacyConfigPath) {
  if (existsSync3(configPath)) return configPath;
  if (existsSync3(legacyConfigPath)) return legacyConfigPath;
  return void 0;
}
function removeLegacyConfig(legacyConfigPath) {
  if (existsSync3(legacyConfigPath)) {
    unlinkSync(legacyConfigPath);
    console.log(chalk3.gray("Removed legacy eslint.config.mjs"));
  }
}
function updateDependencies(packageJsonPath, react, cwd, verbose) {
  if (!existsSync3(packageJsonPath)) {
    console.log(chalk3.yellow("No package.json found \u2014 skipping dependency updates"));
    return;
  }
  const changed = addDevDependencies(packageJsonPath, getRequiredDevDependencies(react), verbose);
  if (changed) {
    runInstall(cwd);
  }
}
async function lintInit({ verbose } = {}) {
  const cwd = INIT_CWD();
  const configPath = PATH2.resolve(cwd, "eslint.config.ts");
  const legacyConfigPath = PATH2.resolve(cwd, "eslint.config.mjs");
  const existingPath = findExistingConfig(configPath, legacyConfigPath);
  if (existingPath) {
    const filename = PATH2.basename(existingPath);
    const confirmed = await askConfirmation(
      chalk3.yellow(`${filename} already exists. Replace it with eslint.config.ts? (y/N) `)
    );
    if (!confirmed) {
      console.log(chalk3.gray(`Skipped \u2014 existing ${filename} preserved`));
      return 0;
    }
  }
  const react = detectReactInMonorepo(cwd, verbose);
  if (react) {
    console.log(chalk3.cyan("Detected React packages \u2014 using @xylabs/eslint-config-react-flat"));
  } else if (verbose) {
    console.log(chalk3.gray("  No React packages detected \u2014 using @xylabs/eslint-config-flat"));
  }
  const useXyLabsBarrel = await askConfirmation(
    chalk3.cyan("Disallow @xylabs/sdk-js barrel imports? (y/N) ")
  );
  const useXyoBarrel = await askConfirmation(
    chalk3.cyan("Disallow @xyo-network/sdk-js barrel imports? (y/N) ")
  );
  const config = generateEslintConfig({
    react,
    useXyLabsBarrel,
    useXyoBarrel
  });
  writeFileSync(configPath, config, "utf8");
  console.log(chalk3.green("Generated eslint.config.ts"));
  removeLegacyConfig(legacyConfigPath);
  updateDependencies(PATH2.resolve(cwd, "package.json"), react, cwd, verbose);
  return 0;
}
export {
  detectReactInMonorepo,
  lintInit
};
//# sourceMappingURL=lint-init.mjs.map
