// src/core-node-modules.ts
import fs from "fs";
import path from "path";
var isDirectory = (directory) => {
  try {
    return fs.statSync(directory).isDirectory();
  } catch (error) {
    return false;
  }
};
var hasAstroDependency = (nodeModulesDirectory) => {
  const astroBin = process.platform === "win32" ? "astro.cmd" : "astro";
  return fs.existsSync(path.join(nodeModulesDirectory, "astro", "package.json")) || fs.existsSync(path.join(nodeModulesDirectory, ".bin", astroBin));
};
var isSymbolicLink = (targetPath) => {
  try {
    return fs.lstatSync(targetPath).isSymbolicLink();
  } catch (error) {
    return false;
  }
};
var isSameDirectory = (a, b) => {
  try {
    return fs.realpathSync.native(a) === fs.realpathSync.native(b);
  } catch (error) {
    return false;
  }
};
var resolveInstalledCoreNodeModules = (currentDir) => {
  const candidates = [];
  const seen = /* @__PURE__ */ new Set();
  const addCandidate = (candidate) => {
    const resolvedCandidate = path.resolve(candidate);
    if (!seen.has(resolvedCandidate)) {
      candidates.push(resolvedCandidate);
      seen.add(resolvedCandidate);
    }
  };
  addCandidate(path.resolve(currentDir, "..", "node_modules"));
  let directory = path.resolve(currentDir);
  while (true) {
    if (path.basename(directory) === "node_modules") {
      addCandidate(directory);
    }
    addCandidate(path.join(directory, "node_modules"));
    const parentDirectory = path.dirname(directory);
    if (parentDirectory === directory) {
      break;
    }
    directory = parentDirectory;
  }
  return candidates.find((candidate) => isDirectory(candidate) && hasAstroDependency(candidate)) ?? candidates.find(isDirectory);
};
var linkCoreNodeModules = ({
  coreNodeModules,
  installedCoreNodeModules
}) => {
  if (!installedCoreNodeModules) return;
  if (isSymbolicLink(coreNodeModules)) {
    if (isSameDirectory(coreNodeModules, installedCoreNodeModules)) {
      return;
    }
    fs.unlinkSync(coreNodeModules);
  } else if (fs.existsSync(coreNodeModules)) {
    return;
  }
  fs.symlinkSync(installedCoreNodeModules, coreNodeModules, process.platform === "win32" ? "junction" : "dir");
};

export {
  resolveInstalledCoreNodeModules,
  linkCoreNodeModules
};
