import * as dotenv from "dotenv";
dotenv.config();
import { readFileSync } from "node:fs";
import { fileURLToPath } from "node:url";
import { confirm } from "@inquirer/prompts";
import * as Sentry from "@sentry/node";
import { gte } from "semver";
import undici from "undici";
import { hideBin } from "yargs/helpers";
import yargs from "yargs/yargs";
import bucket from "./cmds/bucket/index.js";
import build from "./cmds/build.js";
import caCertificate from "./cmds/ca-certificate/index.js";
import compile from "./cmds/compile.js";
import customDomain from "./cmds/custom-domain/index.js";
import deleteZup from "./cmds/delete.js";
import deploy from "./cmds/deploy.js";
import dev from "./cmds/dev.js";
import docs from "./cmds/docs.js";
import editor from "./cmds/editor.js";
import info from "./cmds/info.js";
import init from "./cmds/init.js";
import link from "./cmds/link.js";
import list from "./cmds/list.js";
import login from "./cmds/login.js";
import logout from "./cmds/logout.js";
import mtlsCertificates from "./cmds/mtls-certificates/index.js";
import oas from "./cmds/open-api/index.js";
import project from "./cmds/project/index.js";
import proxies from "./cmds/proxies/index.js";
import source from "./cmds/source/index.js";
import test from "./cmds/test.js";
import tunnel from "./cmds/tunnel/index.js";
import variable from "./cmds/variable/index.js";
import whoami from "./cmds/whoami.js";
import { captureCliInvocationEvent } from "./common/analytics/cli-invocation.js";
import { shutdownAnalytics } from "./common/analytics/lib.js";
import { ApiError } from "./common/api/client.js";
import { MAX_WAIT_PENDING_TIME_MS, SENTRY_DSN } from "./common/constants.js";
import { logger } from "./common/logger.js";
import { checkPnpmLifecycle } from "./common/middleware/check-pnpm-lifecycle.js";
import { logLevel } from "./common/middleware/logging.js";
import { warnIfOutdatedVersion, warnNodeVersion } from "./common/outdated.js";
import setBlocking, { printCriticalFailureToConsole, printCriticalFailureToConsoleAndExit, } from "./common/output.js";
if (process.env.ZUPLO_CLI_PROFILING) {
    await confirm({ message: "Continue executing CLI?", default: true });
}
const MIN_NODE_VERSION = "18.0.0";
const RECOMMENDED_NODE_VERSION = "20.0.0";
if (gte(process.versions.node, MIN_NODE_VERSION)) {
    let cliVersion;
    try {
        const packageJson = JSON.parse(readFileSync(fileURLToPath(new URL("../package.json", import.meta.url)), "utf-8"));
        cliVersion = packageJson.version;
    }
    catch (e) {
        cliVersion = "0.0.0";
        logger.error(e);
        await printCriticalFailureToConsoleAndExit(`Unable to load @zuplo/cli. The package.json is missing or malformed.`);
    }
    await warnNodeVersion(cliVersion, RECOMMENDED_NODE_VERSION);
    undici.setGlobalDispatcher(undici.getGlobalDispatcher().compose((dispatch) => {
        return (opts, handler) => {
            opts.headers = {
                ...opts.headers,
                "user-agent": `ZuploCLI/${cliVersion}`,
                ...(process.env.ZUPLO_CANARY ? { "zp-canary": "true" } : {}),
            };
            return dispatch(opts, handler);
        };
    }));
    Sentry.init({
        dsn: SENTRY_DSN,
        release: cliVersion,
    });
    const cli = yargs(hideBin(process.argv))
        .env("ZUPLO")
        .option("prompt", {
        type: "boolean",
        describe: "Bypass confirmation prompts",
        default: true,
        hidden: true,
    })
        .option("verbose", {
        alias: "v",
        type: "count",
        describe: "Increase verbosity level (-v, -vv, -vvv)",
        default: 0,
    })
        .middleware(setBlocking)
        .middleware(logLevel)
        .middleware(checkPnpmLifecycle)
        .middleware((argv) => {
        void captureCliInvocationEvent(argv, cliVersion);
    })
        .command(caCertificate)
        .command(compile)
        .command(customDomain)
        .command(deleteZup)
        .command(deploy)
        .command(dev)
        .command(docs)
        .command(editor)
        .command(info)
        .command(init)
        .command(list)
        .command(link)
        .command(login)
        .command(logout)
        .command(test)
        .command(oas)
        .command(mtlsCertificates)
        .command(project)
        .command(source)
        .command(tunnel)
        .command(variable)
        .command(build)
        .command(bucket)
        .command(proxies)
        .command(whoami)
        .demandCommand()
        .strictCommands()
        .version(cliVersion)
        .fail(false)
        .help();
    let exitCode = 0;
    try {
        await cli.argv;
        void warnIfOutdatedVersion(cliVersion);
    }
    catch (err) {
        exitCode = 1;
        if (err instanceof Error) {
            Sentry.captureException(err);
        }
        if (err instanceof ApiError) {
        }
        else {
            printCriticalFailureToConsole(err.message ?? err);
            cli.showHelp();
        }
    }
    finally {
        await shutdownAnalytics();
        await Sentry.close(MAX_WAIT_PENDING_TIME_MS);
        process.exit(exitCode);
    }
}
else {
    await printCriticalFailureToConsoleAndExit(`The Zuplo CLI requires at least node.js v${MIN_NODE_VERSION}. You are using v${process.versions.node}. Please update your version of node.js.

    Consider using a Node.js version manager such as https://github.com/nvm-sh/nvm.`);
}
//# sourceMappingURL=cli.js.map