"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    var desc = Object.getOwnPropertyDescriptor(m, k);
    if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
      desc = { enumerable: true, get: function() { return m[k]; } };
    }
    Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
    Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
    o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
    if (mod && mod.__esModule) return mod;
    var result = {};
    if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
    __setModuleDefault(result, mod);
    return result;
};
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 __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.run = exports.Main = void 0;
const feishu_devtools_core_1 = require("@bdeefe/feishu-devtools-core");
const Logger_1 = __importDefault(require("@bdeefe/feishu-devtools-core/libs/common/Logger"));
const plugin_help_1 = require("@oclif/plugin-help");
const EventTracker_1 = __importDefault(require("./adapters/EventTracker"));
const command_1 = __importDefault(require("./extends/command"));
const base_1 = __importDefault(require("./implements/base"));
const config_1 = __importDefault(require("./utils/config"));
const env_1 = require("./utils/env");
const update_1 = __importStar(require("./utils/update"));
let initSpinner;
Logger_1.default.Config = {
    appenders: ['stdout'],
    logPath: config_1.default.config.CacheRoot,
};
const logger = new Logger_1.default('Index');
logger.info('Init', 'config', 'end', config_1.default);
class Main extends command_1.default {
    static run(argv, options) {
        return super.run(argv, options || __dirname);
    }
    init() {
        const _super = Object.create(null, {
            init: { get: () => super.init }
        });
        return __awaiter(this, void 0, void 0, function* () {
            const [id, ...argv] = this.argv;
            yield this.config.runHook('init', Object.assign({ id,
                argv }, { spinner: initSpinner }));
            return _super.init.call(this);
        });
    }
    run() {
        return __awaiter(this, void 0, void 0, function* () {
            const [id, ...argv] = this.argv;
            this.parse(Object.assign({ strict: false, '--': false }, this.ctor));
            process.env.COMMAND_ID = id;
            process.env.COMMAND_ARGV = argv.toString();
            initSpinner === null || initSpinner === void 0 ? void 0 : initSpinner.stop();
            process.env.ENTER_BIZ = Date.now().toString();
            const base = new base_1.default();
            base.eventTracker('command_start', { tags: { command: id } });
            let resultType = '';
            let err;
            try {
                yield this.config.runCommand(id, argv);
                resultType = 'success';
            }
            catch (e) {
                resultType = 'fail';
                err = e;
            }
            base.eventTracker(`command_end`, {
                tags: { command: id, resultType },
            });
            EventTracker_1.default.prototype[feishu_devtools_core_1.EventTrackerCmdEnum.End]();
            if (err) {
                throw err;
            }
        });
    }
    _helpOverride() {
        initSpinner === null || initSpinner === void 0 ? void 0 : initSpinner.stop();
        if (['-v', '-V', '--version', 'version'].includes(this.argv[0])) {
            return this._version();
        }
        if (['-h', 'help'].includes(this.argv[0])) {
            return true;
        }
        if (['-a', '--all'].includes(this.argv[0])) {
            return true;
        }
        if (this.argv.length === 0) {
            return true;
        }
        for (const arg of this.argv) {
            if (arg === '--help') {
                return true;
            }
            if (arg === '--') {
                return false;
            }
        }
        return false;
    }
    _help() {
        initSpinner === null || initSpinner === void 0 ? void 0 : initSpinner.stop();
        const HelpClass = (0, plugin_help_1.getHelpClass)(this.config);
        const help = new HelpClass(this.config);
        help.showHelp(this.argv);
        return this.exit(0);
    }
}
exports.Main = Main;
function run(spinner, argv = process.argv.slice(2), options) {
    return __awaiter(this, void 0, void 0, function* () {
        initSpinner = spinner;
        initSpinner.start();
        yield (0, env_1.initEnvironments)();
        yield (0, update_1.writeUpdateData)(undefined, false);
        yield (0, update_1.writeFGData)();
        const command = argv[0];
        switch (command) {
            case 'create':
                if (process.env.DEBUG_TEMPLATES_ROOT) {
                    yield update_1.default.writeDebugTemplateMeta();
                }
                break;
        }
        process.env.ENTER_OCLIF = Date.now().toString();
        return Main.run(argv, options);
    });
}
exports.run = run;
const { showError } = require('./utils/error');
process.on('uncaughtException', showError);
process.on('unhandledRejection', showError);
