import process from 'node:process';
import { defineCommand } from 'citty';
import { resolve, relative } from 'pathe';
import { s as showVersions } from '../shared/cli.DGQJ5P32.mjs';
import { o as overrideEnv } from '../shared/cli.0t4uqXVO.mjs';
import { a as clearBuildDir } from '../shared/cli.CoNbGSsT.mjs';
import { l as loadKit } from '../shared/cli.DlcAx0De.mjs';
import { c as cwdArgs, l as logLevelArgs, d as dotEnvArgs, e as envNameArgs, b as legacyRootDirArgs, a as logger } from '../shared/cli.TH4BiEd5.mjs';
import 'consola/utils';
import 'pkg-types';
import 'node:fs';
import 'jiti';
import 'node:path';
import 'std-env';
import 'consola';
import 'node:url';

const buildCommand = defineCommand({
  meta: {
    name: "build",
    description: "Build Nuxt for production deployment"
  },
  args: {
    ...cwdArgs,
    ...logLevelArgs,
    prerender: {
      type: "boolean",
      description: "Build Nuxt and prerender static routes"
    },
    preset: {
      type: "string",
      description: "Nitro server preset"
    },
    ...dotEnvArgs,
    ...envNameArgs,
    ...legacyRootDirArgs
  },
  async run(ctx) {
    overrideEnv("production");
    const cwd = resolve(ctx.args.cwd || ctx.args.rootDir);
    await showVersions(cwd);
    const kit = await loadKit(cwd);
    const nuxt = await kit.loadNuxt({
      cwd,
      dotenv: {
        cwd,
        fileName: ctx.args.dotenv
      },
      envName: ctx.args.envName,
      // c12 will fall back to NODE_ENV
      overrides: {
        logLevel: ctx.args.logLevel,
        // TODO: remove in 3.8
        _generate: ctx.args.prerender,
        nitro: {
          static: ctx.args.prerender,
          preset: ctx.args.preset || process.env.NITRO_PRESET || process.env.SERVER_PRESET
        },
        ...ctx.data?.overrides
      }
    });
    let nitro;
    try {
      nitro = kit.useNitro?.();
      logger.info(`Building for Nitro preset: \`${nitro.options.preset}\``);
    } catch {
    }
    await clearBuildDir(nuxt.options.buildDir);
    await kit.writeTypes(nuxt);
    nuxt.hook("build:error", (err) => {
      logger.error("Nuxt Build Error:", err);
      process.exit(1);
    });
    await kit.buildNuxt(nuxt);
    if (ctx.args.prerender) {
      if (!nuxt.options.ssr) {
        logger.warn(
          "HTML content not prerendered because `ssr: false` was set. You can read more in `https://nuxt.com/docs/getting-started/deployment#static-hosting`."
        );
      }
      const dir = nitro?.options.output.publicDir;
      const publicDir = dir ? relative(process.cwd(), dir) : ".output/public";
      logger.success(
        `You can now deploy \`${publicDir}\` to any static hosting!`
      );
    }
  }
});

export { buildCommand as default };
