import { existsSync, promises } from 'node:fs';
import { dirname, relative } from 'node:path';
import process from 'node:process';
import { d as defineCommand, a as dotEnvArgs, b as legacyRootDirArgs, e as extendsArgs, f as envNameArgs, l as logLevelArgs, c as cwdArgs } from '../shared/nuxi.C0YEEVs2.mjs';
import { l as logger, e as box, a as colors } from '../shared/nuxi.DQjfoGl0.mjs';
import 'node:tty';
import { g as getArgs } from '../shared/nuxi.BftEtAPJ.mjs';
import { x as ve } from './main.mjs';
import { l as loadKit } from '../shared/nuxi.BiWTNJI4.mjs';
import { r as resolve } from '../shared/nuxi.Do0aYBCO.mjs';
import { s as setupDotenv } from '../shared/nuxi.DRpqwPny.mjs';
import 'node:crypto';
import 'node:url';
import 'node:util';
import '../shared/nuxi.yPqsj7vw.mjs';
import 'node:http';
import 'node:https';
import 'node:net';
import 'node:os';
import 'node:fs/promises';
import '../shared/nuxi.BAGoDD49.mjs';
import 'http';
import 'https';
import '../shared/nuxi.D2_bzAv0.mjs';
import 'node:child_process';
import 'crypto';
import 'node:module';
import 'child_process';
import 'path';
import 'process';
import 'stream';
import 'readline';
import '../shared/nuxi.BLb4POFS.mjs';
import 'node:assert';
import 'node:v8';
import '../shared/nuxi.BHaQQUPr.mjs';
import 'node:perf_hooks';
import 'node:vm';
import 'fs';
import 'os';

const command = defineCommand({
  meta: {
    name: "preview",
    description: "Launches Nitro server for local testing after `nuxi build`."
  },
  args: {
    ...cwdArgs,
    ...logLevelArgs,
    ...envNameArgs,
    ...extendsArgs,
    ...legacyRootDirArgs,
    port: { ...getArgs().port, alias: ["p"] },
    ...dotEnvArgs
  },
  async run(ctx) {
    process.env.NODE_ENV = process.env.NODE_ENV || "production";
    const cwd = resolve(ctx.args.cwd || ctx.args.rootDir);
    const { loadNuxt } = await loadKit(cwd);
    const resolvedOutputDir = await new Promise((res) => {
      loadNuxt({
        cwd,
        envName: ctx.args.envName,
        // c12 will fall back to NODE_ENV
        ready: true,
        overrides: {
          ...ctx.args.extends && { extends: ctx.args.extends },
          modules: [
            function(_, nuxt) {
              nuxt.hook("nitro:init", (nitro) => {
                res(resolve(nuxt.options.srcDir || cwd, nitro.options.output.dir || ".output", "nitro.json"));
              });
            }
          ]
        }
      }).then((nuxt) => nuxt.close()).catch(() => "");
    });
    const defaultOutput = resolve(cwd, ".output", "nitro.json");
    const nitroJSONPaths = [resolvedOutputDir, defaultOutput].filter(Boolean);
    const nitroJSONPath = nitroJSONPaths.find((p) => existsSync(p));
    if (!nitroJSONPath) {
      logger.error(
        "Cannot find `nitro.json`. Did you run `nuxi build` first? Search path:\n",
        nitroJSONPaths
      );
      process.exit(1);
    }
    const outputPath = dirname(nitroJSONPath);
    const nitroJSON = JSON.parse(await promises.readFile(nitroJSONPath, "utf-8"));
    if (!nitroJSON.commands.preview) {
      logger.error("Preview is not supported for this build.");
      process.exit(1);
    }
    const info = [
      ["Node.js:", `v${process.versions.node}`],
      ["Nitro Preset:", nitroJSON.preset],
      ["Working directory:", relative(process.cwd(), outputPath)]
    ];
    const _infoKeyLen = Math.max(...info.map(([label]) => label.length));
    logger.log(
      box(
        [
          "You are running Nuxt production build in preview mode.",
          `For production deployments, please directly use ${colors.cyan(
            nitroJSON.commands.preview
          )} command.`,
          "",
          ...info.map(
            ([label, value]) => `${label.padEnd(_infoKeyLen, " ")} ${colors.cyan(value)}`
          )
        ].join("\n"),
        {
          title: colors.yellow("Preview Mode"),
          style: {
            borderColor: "yellow"
          }
        }
      )
    );
    const envFileName = ctx.args.dotenv || ".env";
    const envExists = existsSync(resolve(cwd, envFileName));
    if (envExists) {
      logger.info(
        `Loading \`${envFileName}\`. This will not be loaded when running the server in production.`
      );
      await setupDotenv({ cwd, fileName: envFileName });
    } else if (ctx.args.dotenv) {
      logger.error(`Cannot find \`${envFileName}\`.`);
    }
    const { port } = _resolveListenOptions(ctx.args);
    logger.info(`Starting preview command: \`${nitroJSON.commands.preview}\``);
    const [command2, ...commandArgs] = nitroJSON.commands.preview.split(" ");
    logger.log("");
    await ve(command2, commandArgs, {
      throwOnError: true,
      nodeOptions: {
        stdio: "inherit",
        cwd: outputPath,
        env: {
          ...process.env,
          NUXT_PORT: port,
          NITRO_PORT: port
        }
      }
    });
  }
});
function _resolveListenOptions(args) {
  const _port = args.port ?? process.env.NUXT_PORT ?? process.env.NITRO_PORT ?? process.env.PORT;
  return {
    port: _port
  };
}

export { command as default };
