import { execSync } from 'node:child_process';
import { c as consola } from '../shared/nuxi.114b1a98.mjs';
import 'node:util';
import 'node:path';
import 'node:process';
import 'tty';
import { promises, statSync } from 'node:fs';
import { r as resolvePath } from '../shared/nuxi.f03591c1.mjs';
import { i as isAbsolute, r as resolve, j as join } from '../shared/nuxi.ffb4843d.mjs';
import { g as getPackageManager, p as packageManagerLocks } from '../shared/nuxi.b31b4c56.mjs';
import { r as rmRecursive, t as touchFile } from '../shared/nuxi.04a0178b.mjs';
import { c as cleanupNuxtDirs, n as nuxtVersionToGitIdentifier } from '../shared/nuxi.18aa8f90.mjs';
import { d as defineNuxtCommand } from '../shared/nuxi.c68ce99d.mjs';
import 'node:module';
import 'node:url';
import 'node:assert';
import 'node:v8';

const defaultFindOptions = {
  startingFrom: ".",
  rootPattern: /^node_modules$/,
  reverse: false,
  test: (filePath) => {
    try {
      if (statSync(filePath).isFile()) {
        return true;
      }
    } catch {
    }
  }
};
async function findFile(filename, _options = {}) {
  const options = { ...defaultFindOptions, ..._options };
  const basePath = resolve(options.startingFrom);
  const leadingSlash = basePath[0] === "/";
  const segments = basePath.split("/").filter(Boolean);
  if (leadingSlash) {
    segments[0] = "/" + segments[0];
  }
  let root = segments.findIndex((r) => r.match(options.rootPattern));
  if (root === -1) {
    root = 0;
  }
  if (!options.reverse) {
    for (let index = segments.length; index > root; index--) {
      const filePath = join(...segments.slice(0, index), filename);
      if (await options.test(filePath)) {
        return filePath;
      }
    }
  } else {
    for (let index = root + 1; index <= segments.length; index++) {
      const filePath = join(...segments.slice(0, index), filename);
      if (await options.test(filePath)) {
        return filePath;
      }
    }
  }
  throw new Error(
    `Cannot find matching ${filename} in ${options.startingFrom} or parent directories`
  );
}
function findNearestFile(filename, _options = {}) {
  return findFile(filename, _options);
}
const FileCache = /* @__PURE__ */ new Map();
async function readPackageJSON(id, options = {}) {
  const resolvedPath = await resolvePackageJSON(id, options);
  const cache = options.cache && typeof options.cache !== "boolean" ? options.cache : FileCache;
  if (options.cache && cache.has(resolvedPath)) {
    return cache.get(resolvedPath);
  }
  const blob = await promises.readFile(resolvedPath, "utf8");
  const parsed = JSON.parse(blob);
  cache.set(resolvedPath, parsed);
  return parsed;
}
async function resolvePackageJSON(id = process.cwd(), options = {}) {
  const resolvedPath = isAbsolute(id) ? id : await resolvePath(id, options);
  return findNearestFile("package.json", {
    startingFrom: resolvedPath,
    ...options
  });
}

async function getNuxtVersion(path) {
  try {
    const pkg = await readPackageJSON("nuxt", { url: path });
    if (!pkg.version) {
      consola.warn("Cannot find any installed nuxt versions in ", path);
    }
    return pkg.version || null;
  } catch {
    return null;
  }
}
const upgrade = defineNuxtCommand({
  meta: {
    name: "upgrade",
    usage: "npx nuxi upgrade [--force|-f]",
    description: "Upgrade nuxt"
  },
  async invoke(args) {
    const rootDir = resolve(args._[0] || ".");
    const packageManager = getPackageManager(rootDir);
    if (!packageManager) {
      console.error("Cannot detect Package Manager in", rootDir);
      process.exit(1);
    }
    const packageManagerVersion = execSync(`${packageManager} --version`).toString("utf8").trim();
    consola.info("Package Manager:", packageManager, packageManagerVersion);
    const currentVersion = await getNuxtVersion(rootDir) || "[unknown]";
    consola.info("Current nuxt version:", currentVersion);
    if (args.force || args.f) {
      consola.info("Removing lock-file and node_modules...");
      const pmLockFile = resolve(rootDir, packageManagerLocks[packageManager]);
      await rmRecursive([pmLockFile, resolve(rootDir, "node_modules")]);
      await touchFile(pmLockFile);
    }
    consola.info("Installing latest Nuxt 3 release...");
    execSync(`${packageManager} ${packageManager === "yarn" ? "add" : "install"} -D nuxt`, { stdio: "inherit", cwd: rootDir });
    await cleanupNuxtDirs(rootDir);
    const upgradedVersion = await getNuxtVersion(rootDir) || "[unknown]";
    consola.info("Upgraded nuxt version:", upgradedVersion);
    if (upgradedVersion === currentVersion) {
      consola.success("You're already using the latest version of nuxt.");
    } else {
      consola.success("Successfully upgraded nuxt from", currentVersion, "to", upgradedVersion);
      const commitA = nuxtVersionToGitIdentifier(currentVersion);
      const commitB = nuxtVersionToGitIdentifier(upgradedVersion);
      if (commitA && commitB) {
        consola.info("Changelog:", `https://github.com/nuxt/nuxt/compare/${commitA}...${commitB}`);
      }
    }
  }
});

export { upgrade as default };
