"use strict";
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
    function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};
var __generator = (this && this.__generator) || function (thisArg, body) {
    var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
    return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
    function verb(n) { return function (v) { return step([n, v]); }; }
    function step(op) {
        if (f) throw new TypeError("Generator is already executing.");
        while (g && (g = 0, op[0] && (_ = 0)), _) try {
            if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
            if (y = 0, t) op = [op[0] & 2, t.value];
            switch (op[0]) {
                case 0: case 1: t = op; break;
                case 4: _.label++; return { value: op[1], done: false };
                case 5: _.label++; y = op[1]; op = [0]; continue;
                case 7: op = _.ops.pop(); _.trys.pop(); continue;
                default:
                    if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
                    if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
                    if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
                    if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
                    if (t[2]) _.ops.pop();
                    _.trys.pop(); continue;
            }
            op = body.call(thisArg, _);
        } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
        if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
    }
};
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
exports.__esModule = true;
var commander_1 = require("commander");
var figures_1 = __importDefault(require("figures"));
var oas_1 = __importDefault(require("oas"));
var ora_1 = __importDefault(require("ora"));
var validate_npm_package_name_1 = __importDefault(require("validate-npm-package-name"));
var fetcher_1 = __importDefault(require("../../fetcher"));
var codegen_1 = __importDefault(require("../codegen"));
var prompt_1 = __importDefault(require("../lib/prompt"));
var logger_1 = __importDefault(require("../logger"));
var storage_1 = __importDefault(require("../storage"));
// @todo log logs to `.api/.logs` and have `.logs` ignored
var cmd = new commander_1.Command();
cmd
    .name('install')
    .description('install an API SDK into your codebase')
    .argument('<uri>', 'an API to install')
    .addOption(new commander_1.Option('-l, --lang <language>', 'SDK language').choices([
    'js',
    'js-cjs',
    'js-esm',
    'ts',
]))
    .addOption(new commander_1.Option('-y, --yes', 'Automatically answer "yes" to any prompts printed'))
    .action(function (uri, options) { return __awaiter(void 0, void 0, void 0, function () {
    var language, identifier, spinner, storage, oas, generator, sdkSource, err_1;
    return __generator(this, function (_a) {
        switch (_a.label) {
            case 0:
                if (!options.lang) return [3 /*break*/, 1];
                language = options.lang;
                return [3 /*break*/, 3];
            case 1: return [4 /*yield*/, (0, prompt_1["default"])({
                    type: 'select',
                    name: 'value',
                    message: 'What language would you like to generate an SDK for?',
                    choices: [
                        { title: 'TypeScript', value: 'ts' },
                        { title: 'JavaScript', value: 'js' },
                    ],
                    initial: 1
                })];
            case 2:
                (language = (_a.sent()).value);
                _a.label = 3;
            case 3:
                if (!(language === 'js')) return [3 /*break*/, 5];
                return [4 /*yield*/, (0, prompt_1["default"])({
                        type: 'select',
                        name: 'value',
                        message: 'How are your project imports and exports structured?',
                        choices: [
                            { title: 'CommonJS', description: 'require/exports', value: 'cjs' },
                            { title: 'ECMAScript Modules', description: 'import/export', value: 'esm' },
                        ],
                        initial: 0,
                        format: function (sel) { return (sel === 'cjs' ? 'js-cjs' : 'js-esm'); }
                    })];
            case 4:
                (language = (_a.sent()).value);
                _a.label = 5;
            case 5:
                // @todo let them know that we're going to be creating a `.api/ directory
                // @todo detect if they have a gitigore and .npmignore and if .api woudl be ignored by that
                // @todo don't support swagger files without upconverting them
                if (storage_1["default"].isInLockFile({ source: uri })) {
                    // @todo
                    // logger(`It looks like you already have this API installed. Would you like to update it?`);
                }
                if (!fetcher_1["default"].isAPIRegistryUUID(uri)) return [3 /*break*/, 6];
                identifier = fetcher_1["default"].getProjectPrefixFromRegistryUUID(uri);
                return [3 /*break*/, 8];
            case 6: return [4 /*yield*/, (0, prompt_1["default"])({
                    type: 'text',
                    name: 'value',
                    message: 'What would you like to identify this API as? This will be how you import the SDK. (e.g. entering `petstore` would result in `@api/petstore`)',
                    validate: function (value) {
                        if (!value) {
                            return false;
                        }
                        // Is this identifier already in storage?
                        if (storage_1["default"].isInLockFile({ identifier: value })) {
                            return "\"".concat(value, "\" is already taken in your `.api/` directory. Please enter another identifier.");
                        }
                        var isValidForNPM = (0, validate_npm_package_name_1["default"])("@api/".concat(value));
                        if (!isValidForNPM.validForNewPackages) {
                            // `prompts` doesn't support surfacing multiple errors in a `validate` call so we can
                            // only surface the first to the user.
                            return isValidForNPM.errors[0];
                        }
                        return true;
                    }
                })];
            case 7:
                (identifier = (_a.sent()).value);
                _a.label = 8;
            case 8:
                if (!identifier) {
                    (0, logger_1["default"])('You must tell us what you would like to identify this API as in order to install it.', true);
                    process.exit(1);
                }
                spinner = (0, ora_1["default"])('Fetching your API').start();
                storage = new storage_1["default"](uri, identifier);
                return [4 /*yield*/, storage
                        .load()
                        .then(function (res) {
                        spinner.succeed(spinner.text);
                        return res;
                    })
                        .then(oas_1["default"].init)["catch"](function (err) {
                        // @todo cleanup installed files
                        spinner.fail(spinner.text);
                        (0, logger_1["default"])(err.message, true);
                        process.exit(1);
                    })];
            case 9:
                oas = _a.sent();
                // @todo look for a prettier config and if we find one ask them if we should use it
                spinner = (0, ora_1["default"])('Generating your SDK').start();
                generator = (0, codegen_1["default"])(language, oas, './openapi.json', identifier);
                return [4 /*yield*/, generator
                        .generator()
                        .then(function (res) {
                        spinner.succeed(spinner.text);
                        return res;
                    })["catch"](function (err) {
                        // @todo cleanup installed files
                        spinner.fail(spinner.text);
                        (0, logger_1["default"])(err.message, true);
                        process.exit(1);
                    })];
            case 10:
                sdkSource = _a.sent();
                spinner = (0, ora_1["default"])('Saving your SDK into your codebase').start();
                return [4 /*yield*/, storage
                        .saveSourceFiles(sdkSource)
                        .then(function () {
                        spinner.succeed(spinner.text);
                    })["catch"](function (err) {
                        // @todo cleanup installed files
                        spinner.fail(spinner.text);
                        (0, logger_1["default"])(err.message, true);
                        process.exit(1);
                    })];
            case 11:
                _a.sent();
                if (!generator.hasRequiredPackages()) return [3 /*break*/, 17];
                (0, logger_1["default"])("".concat(figures_1["default"].warning, " This generator requires some packages to be installed alongside it:"));
                Object.entries(generator.requiredPackages).forEach(function (_a) {
                    var pkg = _a[0], pkgInfo = _a[1];
                    (0, logger_1["default"])("  ".concat(figures_1["default"].pointerSmall, " ").concat(pkg, ": ").concat(pkgInfo.reason, " ").concat(pkgInfo.url));
                });
                if (!!options.yes) return [3 /*break*/, 13];
                return [4 /*yield*/, (0, prompt_1["default"])({
                        type: 'confirm',
                        name: 'value',
                        message: 'OK to proceed with package installation?',
                        initial: true
                    }).then(function (_a) {
                        var value = _a.value;
                        if (!value) {
                            // @todo cleanup installed files
                            (0, logger_1["default"])('Installation cancelled.', true);
                            process.exit(1);
                        }
                    })];
            case 12:
                _a.sent();
                _a.label = 13;
            case 13:
                spinner = (0, ora_1["default"])('Installing required packages').start();
                _a.label = 14;
            case 14:
                _a.trys.push([14, 16, , 17]);
                return [4 /*yield*/, generator.installer(storage)];
            case 15:
                _a.sent();
                spinner.succeed(spinner.text);
                return [3 /*break*/, 17];
            case 16:
                err_1 = _a.sent();
                // @todo cleanup installed files
                spinner.fail(spinner.text);
                (0, logger_1["default"])(err_1.message, true);
                process.exit(1);
                return [3 /*break*/, 17];
            case 17:
                (0, logger_1["default"])('🚀 All done!');
                return [2 /*return*/];
        }
    });
}); })
    .addHelpText('after', "\nExamples:\n  $ api install @developers/v2.0#nysezql0wwo236\n  $ api install https://raw.githubusercontent.com/readmeio/oas-examples/main/3.0/json/petstore-simple.json\n  $ api install ./petstore.json");
exports["default"] = cmd;
