"use strict";
Object.defineProperty(exports, "__esModule", {
    value: true
});
Object.defineProperty(exports, "default", {
    enumerable: true,
    get: function() {
        return _default;
    }
});
var _exitcompat = /*#__PURE__*/ _interop_require_default(require("exit-compat"));
var _fs = /*#__PURE__*/ _interop_require_default(require("fs"));
var _getoptscompat = /*#__PURE__*/ _interop_require_default(require("getopts-compat"));
var _path = /*#__PURE__*/ _interop_require_default(require("path"));
var _spawnterm = require("spawn-term");
var _url = /*#__PURE__*/ _interop_require_default(require("url"));
var _indexts = require("./commands/index.js");
var _indexts1 = /*#__PURE__*/ _interop_require_default(require("./index.js"));
function _interop_require_default(obj) {
    return obj && obj.__esModule ? obj : {
        default: obj
    };
}
var __dirname = _path.default.dirname(typeof __filename !== 'undefined' ? __filename : _url.default.fileURLToPath(require("url").pathToFileURL(__filename).toString()));
var ERROR_CODE = 13;
function getVersion() {
    var packagePath = _path.default.join(__dirname, '..', '..', 'package.json');
    var packageJson = JSON.parse(_fs.default.readFileSync(packagePath, 'utf8'));
    return packageJson.version;
}
function printHelp(name) {
    var version = getVersion();
    console.log("".concat(name, " v").concat(version));
    console.log('');
    console.log("Usage: ".concat(name, " [options] <version> <command> [args...]"));
    console.log("       ".concat(name, " <subcommand> [args...]"));
    console.log('');
    console.log('Run commands with specific Node.js versions');
    console.log('');
    console.log('Subcommands:');
    console.log('  default [version]  Set or display the global default Node version');
    console.log('  local [version]    Set or display the local Node version (.nvmrc)');
    console.log('  install <version>  Download and install a Node version');
    console.log('  uninstall <version> Remove an installed Node version');
    console.log('  list               List installed Node versions');
    console.log('  which              Show which Node version would be used');
    console.log('  setup              Install/reinstall binaries to ~/.nvu/bin');
    console.log('  teardown           Remove binaries from ~/.nvu/bin');
    console.log('');
    console.log('Options:');
    console.log('  -v, --version      Print version number');
    console.log('  -h, --help         Print this help message');
    console.log('  -r, --range        Range type (major, minor, patch) with filters (lts, even, odd)');
    console.log('                     Default: major,even');
    console.log('  -d, --desc         Sort versions in descending order');
    console.log('  -e, --expanded     Use expanded version format');
    console.log('  -s, --streaming    Enable streaming output');
    console.log('  --silent           Suppress logging');
    console.log('');
    console.log('Examples:');
    console.log("  ".concat(name, " 22 node --version           Run with Node 22"));
    console.log("  ".concat(name, " 22,20,18 npm test           Run with multiple versions"));
    console.log("  ".concat(name, " engines node --version      Use version from package.json"));
    console.log("  ".concat(name, " default 20                  Set global default to Node 20"));
    console.log("  ".concat(name, " local 18                    Create .nvmrc with Node 18"));
}
var _default = function(argv, name) {
    var options = (0, _getoptscompat.default)(argv, {
        alias: {
            range: 'r',
            desc: 'd',
            expanded: 'e',
            streaming: 's',
            silent: 'si',
            version: 'v',
            help: 'h'
        },
        default: {
            range: 'major,even',
            interactive: true
        },
        boolean: [
            'silent',
            'desc',
            'expanded',
            'streaming',
            'interactive',
            'version',
            'help'
        ],
        stopEarly: true
    });
    if (options.version) {
        console.log(getVersion());
        (0, _exitcompat.default)(0);
        return;
    }
    if (options.help) {
        printHelp(name);
        (0, _exitcompat.default)(0);
        return;
    }
    // Check if first argument is a subcommand
    var args = options._;
    if (args.length > 0 && (0, _indexts.isCommand)(args[0])) {
        (0, _indexts.runCommand)(args[0], args.slice(1));
        return;
    }
    // define.option('-r, --range [range]', 'range type of major, minor, or patch with filters of lts, even, odd for version string expressions', 'major,even');
    // define.option('-s, --silent', 'suppress logging', false);
    options.sort = options.desc ? -1 : 1;
    if (args.length === 0) {
        console.log("Missing version expression. Example usage: ".concat(name, " version command arg1 arg2"));
        (0, _exitcompat.default)(ERROR_CODE);
        return;
    }
    if (args.length === 1) {
        console.log("Missing command. Example usage: ".concat(name, " version command arg1 arg2"));
        (0, _exitcompat.default)(ERROR_CODE);
        return;
    }
    options.stdio = 'inherit'; // pass through stdio
    (0, _indexts1.default)(args[0], args[1], args.slice(2), options, function(err, results) {
        if (err && !err.results) {
            console.log(err.message);
            (0, _exitcompat.default)(ERROR_CODE);
            return;
        }
        if (err) results = err.results;
        var errors = results.filter(function(result) {
            return !!result.error;
        });
        if (!options.silent) {
            if (!_spawnterm.createSession) {
                console.log('\n======================');
                results.forEach(function(res) {
                    console.log("".concat(res.error ? _spawnterm.figures.cross : _spawnterm.figures.tick, " ").concat(res.version).concat(res.error ? " Error: ".concat(res.error.message) : ''));
                });
                console.log('\n----------------------');
                console.log("".concat(name, " ").concat((0, _spawnterm.formatArguments)(args).join(' ')));
                console.log("".concat(_spawnterm.figures.tick, " ").concat(results.length - errors.length, " succeeded"));
                if (errors.length) console.log("".concat(_spawnterm.figures.cross, " ").concat(errors.length, " failed"));
            }
        }
        (0, _exitcompat.default)(err || errors.length ? ERROR_CODE : 0);
    });
};
/* CJS INTEROP */ if (exports.__esModule && exports.default) { try { Object.defineProperty(exports.default, '__esModule', { value: true }); for (var key in exports) { exports.default[key] = exports[key]; } } catch (_) {}; module.exports = exports.default; }