"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 () {
    var ownKeys = function(o) {
        ownKeys = Object.getOwnPropertyNames || function (o) {
            var ar = [];
            for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
            return ar;
        };
        return ownKeys(o);
    };
    return function (mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
        __setModuleDefault(result, mod);
        return result;
    };
})();
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
const promises_1 = __importDefault(require("node:fs/promises"));
const index_js_1 = __importDefault(require("./../lang/index.js"));
const node_path_1 = __importDefault(require("node:path"));
const utils = __importStar(require("./../utils/index.js"));
const db = '.cache/mbler/.path.db';
require("./../commander/index.js");
const node_process_1 = __importDefault(require("node:process"));
const node_os_1 = __importDefault(require("node:os"));
class start {
    command;
    two;
    param;
    dirname;
    DataPath;
    constructor(dir) {
        this.dirname = dir;
        this.param = "";
        this.DataPath = node_path_1.default.join(node_os_1.default.homedir(), db);
        this.command = node_process_1.default.argv[2] || '';
        this.two = (node_process_1.default.argv[3] || '').trim();
        this.start();
    }
    v = () => {
        const { version: v } = require('./../../package.json');
        console.log(`MBLER : ${v}`);
    };
    build = async () => {
        const Bulid = require('./../build').default;
        const build = new Bulid(this.param, this.dirname);
        await build.build();
    };
    help = () => {
        const cmds = index_js_1.default.commands;
        if (cmds.list.includes(this.two) && typeof cmds[this.two] === "string") {
            let cmd = cmds[this.two];
            if (cmd.startsWith("$"))
                cmd = cmds[cmd.slice(1)];
            console.log(`-- '${this.two}' command -- : \n`);
            console.log(`Usage : ${cmd}`);
            return;
        }
        this.echoHelp();
    };
    checkout = async () => {
        if (this.two)
            this.two = utils.join(node_process_1.default.cwd(), this.two || './');
        if (!(await utils.FileExsit(this.two)) || !this.two || this.param === this.two) {
            console.log(this.param);
            return;
        }
        try {
            if (!(await utils.FileExsit(node_path_1.default.dirname(this.DataPath)))) {
                await promises_1.default.mkdir(node_path_1.default.dirname(this.DataPath));
            }
        }
        catch (err) { }
        await promises_1.default.writeFile(this.DataPath, this.two);
        console.log(index_js_1.default.s0, `PATH => ${this.two}`);
    };
    init = () => {
        const Init = require('./init.js');
        const init = new Init(this.param, this.dirname);
        return init.start();
    };
    async start() {
        await this.getWorkDir();
        const commandcc = this.command.toLowerCase().trim();
        const commandMap = {
            build: this.build,
            dev: () => require('./dev')(this.param, this.dirname),
            create: () => require('./create')(this.param, this.dirname, this.two),
            "": () => this.echoHelp(),
            recache: () => require('./rechce')(this.dirname, this.param),
            lang: () => {
                if (this.two)
                    index_js_1.default.__internal.set(this.two);
                console.log(index_js_1.default.__internal.class.currenyLang);
            },
            "-h": this.help,
            "-help": this.help,
            "help": this.help,
            version: () => {
                const version = require('./version.js');
                new version(this.param, this.dirname);
            },
            "v": this.v,
            "-v": this.v,
            checkout: this.checkout,
            "-c": this.checkout,
            init: this.init,
            "-i": this.init,
            "web_edit": () => {
                const edit = require('./../web');
                new edit({
                    PORT: 1025,
                    PATH: this.param
                });
            },
            install: async () => require('./incg.js')(this.dirname, this.param),
            uninstall: () => require('./unincg.js')(this.two, this.dirname),
            add: () => require('./addPack.js')(this.two, this.dirname, this.param),
            remive: () => require('./unaddPack.js')(this.two, this.dirname, this.param),
            clean: async () => {
                const clean = require('./clean.js');
                await (new clean(this.param, this.dirname)).run();
            }
        };
        const run = commandMap[commandcc];
        try {
            if (typeof run === "function") {
                const i = run();
                if (i instanceof Promise)
                    await i;
            }
            else {
                this.defaultCommand(commandcc);
            }
            node_process_1.default.exit(0);
        }
        catch (err) {
            console.error(err);
        }
    }
    defaultCommand(commandcc) {
        console.log(`\x1b[31m${index_js_1.default.uncommand}: ${this.command.toLowerCase().trim()}\x1b[0m`);
        const didvalue = index_js_1.default.commands.list.map((item) => this.getMatchChance(commandcc, item)).reduce((acc, cur, index) => {
            try {
                if (cur > acc.max) {
                    return {
                        max: cur,
                        index: index
                    }; // 更新最大值及索引
                }
                else if (cur === acc.max) {
                    acc.indices.push(index); // 记录重复最大值的索引
                    return acc;
                }
            }
            catch { }
            return acc;
        }, {
            max: -Infinity,
            index: -1,
            indices: []
        });
        const value = index_js_1.default.commands.list[didvalue.index];
        if (value)
            console.log(`${index_js_1.default.noCommandTip} ${value}`);
    }
    async getWorkDir() {
        try {
            this.param = (await promises_1.default.readFile(this.DataPath, 'utf-8')).toString() || "./test";
        }
        catch (err) { }
    }
    echoHelp() {
        console.log(index_js_1.default.help);
    }
    getMatchChance(a, b) {
        let match = 0;
        // b = 比较值，a = 待比较值
        for (let i = 0; i < b.length; i++) {
            if (a[i] == b[i])
                match++;
        }
        return match / b.length;
    }
}
module.exports = start;
