'use strict';

const fs = require('fs');
const upath = require('./upath.js');
const index = require('./index.js');
const cjs = require('./cjs.js');
require('tty');

const prepare = index.defineNuxtCommand({
  meta: {
    name: "prepare",
    usage: "npx nuxi prepare",
    description: "Prepare nuxt for development/build"
  },
  async invoke(args) {
    process.env.NODE_ENV = process.env.NODE_ENV || "production";
    const rootDir = upath.upath.resolve(args._[0] || ".");
    const { loadNuxt } = cjs.requireModule("@nuxt/kit", rootDir);
    const nuxt = await loadNuxt({ rootDir });
    const adHocModules = nuxt.options._majorVersion === 3 ? ["@nuxt/kit", "@nuxt/nitro"] : ["@nuxt/kit"];
    const modulePaths = cjs.getModulePaths(nuxt.options.modulesDir);
    const references = [
      "nuxt3",
      ...adHocModules,
      ...nuxt.options.buildModules,
      ...nuxt.options.modules,
      ...nuxt.options._modules
    ].filter((f) => typeof f === "string").map((id) => {
      var _a;
      return { types: ((_a = cjs.getNearestPackage(id, modulePaths)) == null ? void 0 : _a.name) || id };
    });
    const declarations = [];
    await nuxt.callHook("builder:generateApp");
    await nuxt.callHook("prepare:types", { references, declarations });
    const declarationPath = upath.upath.resolve(`${rootDir}/nuxt.d.ts`);
    const declaration = [
      "// This file is auto generated by `nuxt prepare`",
      "// Please do not manually modify this file.",
      "",
      ...references.map((ref) => {
        if ("path" in ref) {
          ref.path = upath.upath.relative(rootDir, ref.path);
        }
        return `/// <reference ${renderAttrs(ref)} />`;
      }),
      ...declarations,
      "export {}",
      ""
    ].join("\n");
    await fs.promises.writeFile(declarationPath, declaration);
    index.success("Generated", index.cyan(upath.upath.relative(process.cwd(), declarationPath)));
  }
});
function renderAttrs(obj) {
  return Object.entries(obj).map((e) => renderAttr(e[0], e[1])).join(" ");
}
function renderAttr(key, value) {
  return value ? `${key}="${value}"` : "";
}

exports['default'] = prepare;
