import * as dotenv from "dotenv";
dotenv.config();
import undici from "undici";
import { readFileSync } from "node:fs";
import os from "node:os";
import { fileURLToPath } from "node:url";
import { confirm } from "@inquirer/prompts";
import * as Sentry from "@sentry/node";
import { gte } from "semver";
import { hideBin } from "yargs/helpers";
import yargs from "yargs/yargs";
import build from "./cmds/build.js";
import compile from "./cmds/compile.js";
import convert from "./cmds/convert.js";
import deleteZup from "./cmds/delete.js";
import deploy from "./cmds/deploy.js";
import dev from "./cmds/dev.js";
import editor from "./cmds/editor.js";
import link from "./cmds/link.js";
import list from "./cmds/list.js";
import login from "./cmds/login.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 { shutdownAnalytics } from "./common/analytics/lib.js";
import { MAX_WAIT_PENDING_TIME_MS, SENTRY_DSN } from "./common/constants.js";
import { logger } from "./common/logger.js";
import { warnIfOutdatedVersion, warnNodeVersion } from "./common/outdated.js";
import { printCriticalFailureToConsoleAndExit, printWarningToConsole, } from "./common/output.js";
import { logLevel } from "./common/middleware/logging.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);
    if (os.platform() === "win32") {
        printWarningToConsole("Running the Zuplo CLI on Windows is currently in beta. Please report any issues to support@zuplo.com.");
    }
    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,
        hidden: true,
    })
        .middleware(logLevel)
        .command(compile)
        .command(convert)
        .command(deleteZup)
        .command(deploy)
        .command(dev)
        .command(editor)
        .command(list)
        .command(link)
        .command(login)
        .command(test)
        .command(project)
        .command(source)
        .command(tunnel)
        .command(variable)
        .command(build)
        .command(proxies)
        .command({
        command: "hello",
        handler: async () => {
            await fetch("https://393b4699ced44cc2ae87e4ad86184a29.api.mockbin.io/");
        },
    })
        .demandCommand()
        .strictCommands()
        .version(cliVersion)
        .fail(false)
        .help();
    try {
        await cli.argv;
        void warnIfOutdatedVersion(cliVersion);
        void Sentry.close(MAX_WAIT_PENDING_TIME_MS).then(() => {
            process.exit(0);
        });
    }
    catch (err) {
        if (err instanceof Error) {
            Sentry.captureException(err);
        }
        await printCriticalFailureToConsoleAndExit(err.message ?? err);
        cli.showHelp();
    }
    finally {
        await shutdownAnalytics();
    }
}
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