// SPDX-License-Identifier: Apache-2.0
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
    var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
    if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
    else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
    return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var __metadata = (this && this.__metadata) || function (k, v) {
    if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
};
var __param = (this && this.__param) || function (paramIndex, decorator) {
    return function (target, key) { decorator(target, key, paramIndex); }
};
import { Flags as flags } from '../commands/flags.js';
import chalk from 'chalk';
import { SilentBreak } from './errors/silent-break.js';
import { patchInject } from './dependency-injection/container-helper.js';
import { InjectTokens } from './dependency-injection/inject-tokens.js';
import { inject, injectable } from 'tsyringe-neo';
import { LocalConfigRuntimeState } from '../business/runtime-state/config/local/local-config-runtime-state.js';
import { SoloError } from './errors/solo-error.js';
import { NpmClient } from '../integration/npm/npm-client.js';
let Middlewares = class Middlewares {
    configManager;
    remoteConfig;
    k8Factory;
    logger;
    localConfig;
    helpRenderer;
    taskList;
    initCommand;
    npmClient;
    constructor(configManager, remoteConfig, k8Factory, logger, localConfig, helpRenderer, taskList, initCommand, npmClient) {
        this.configManager = configManager;
        this.remoteConfig = remoteConfig;
        this.k8Factory = k8Factory;
        this.logger = logger;
        this.localConfig = localConfig;
        this.helpRenderer = helpRenderer;
        this.taskList = taskList;
        this.initCommand = initCommand;
        this.npmClient = npmClient;
        this.configManager = patchInject(configManager, InjectTokens.ConfigManager, this.constructor.name);
        this.remoteConfig = patchInject(remoteConfig, InjectTokens.RemoteConfigRuntimeState, this.constructor.name);
        this.k8Factory = patchInject(k8Factory, InjectTokens.K8Factory, this.constructor.name);
        this.logger = patchInject(logger, InjectTokens.SoloLogger, this.constructor.name);
        this.localConfig = patchInject(localConfig, InjectTokens.LocalConfigRuntimeState, this.constructor.name);
        this.helpRenderer = patchInject(helpRenderer, InjectTokens.HelpRenderer, this.constructor.name);
        this.taskList = patchInject(taskList, InjectTokens.TaskList, this.constructor.name);
        this.initCommand = patchInject(initCommand, InjectTokens.InitCommand, this.constructor.name);
        this.npmClient = patchInject(npmClient, InjectTokens.NpmClient, this.constructor.name);
    }
    initSystemFiles() {
        return async (argv) => {
            const tasks = 
            // @ts-expect-error - TS2445: Property taskList is protected and only accessible within class BaseCommand and its subclasses.
            this.initCommand.taskList.newTaskList(this.initCommand.setupSystemFilesTasks(argv), { renderer: 'silent' });
            if (tasks.isRoot()) {
                try {
                    await tasks.run();
                }
                catch (error) {
                    throw new SoloError('Error initiating Solo system files', error);
                }
            }
            return argv;
        };
    }
    printCustomHelp(rootCmd) {
        /**
         * @param argv - listr Argv
         */
        return (argv) => {
            if (!argv['help']) {
                return;
            }
            rootCmd.showHelp((output) => {
                this.helpRenderer.render(rootCmd, output);
            });
            throw new SilentBreak('printed help, exiting');
        };
    }
    setLoggerDevFlag() {
        const logger = this.logger;
        /**
         * @param argv - listr Argv
         */
        return (argv) => {
            if (argv.dev) {
                logger.debug('Setting logger dev flag');
                logger.setDevMode(argv.dev);
            }
            return argv;
        };
    }
    detectLocalSoloPackages() {
        const SOLO_PACKAGES_TO_UNLINK = ['@hashgraph/solo', '@hiero-ledger/solo'];
        /**
         * @param argv - listr Argv
         */
        return async (argv) => {
            try {
                const listResult = await this.npmClient.listGlobal();
                const foundLinkedPackages = [];
                for (const item of listResult) {
                    // Check if any of the globally linked packages match the SOLO_PACKAGES_TO_UNLINK
                    // and unlink them if they point to a local directory (indicated by '->' in the npm list output)
                    const matchesSoloPackages = SOLO_PACKAGES_TO_UNLINK.filter((soloPackage) => item.includes(soloPackage) && item.includes('->'));
                    for (const packageName of matchesSoloPackages) {
                        try {
                            const logMessage = `Warning: Found locally linked installation of ${packageName}.`;
                            this.logger.showUser(chalk.yellow(logMessage));
                            this.logger.info(logMessage);
                            foundLinkedPackages.push(packageName);
                        }
                        catch (error) {
                            this.logger.error(new SoloError(`Failed to parse npm list output line "${item}". Please check for any globally linked Solo packages and unlink them manually using "npm unlink -g <package-name>".`, error));
                        }
                    }
                }
            }
            catch (error) {
                this.logger.warn(new SoloError('Failed to detect globally linked Solo packages. Please check for any globally linked Solo packages and' +
                    ' unlink them manually using "npm unlink -g <package-name>".', error));
            }
            return argv;
        };
    }
    /**
     * Processes the Argv and display the command header
     *
     * @returns callback function to be executed from listr
     */
    processArgumentsAndDisplayHeader() {
        const k8Factory = this.k8Factory;
        const configManager = this.configManager;
        const logger = this.logger;
        /**
         * @param argv - listr Argv
         * @param yargs - listr Yargs
         */
        return (argv, yargs) => {
            logger.debug('Processing arguments and displaying header');
            let clusterName = 'N/A';
            let contextName = 'N/A';
            // reset config on `solo init` command
            if (argv._[0] === 'init') {
                configManager.reset();
            }
            // set cluster and namespace in the global configManager from kubernetes context
            // so that we don't need to prompt the user
            try {
                const k8 = k8Factory.default();
                const contextNamespace = k8.contexts().readCurrentNamespace();
                const currentClusterName = k8.clusters().readCurrent();
                contextName = k8.contexts().readCurrent();
                clusterName = configManager.getFlag(flags.clusterRef) || currentClusterName;
                // Set namespace if not provided
                if (contextNamespace?.name) {
                    configManager.setFlag(flags.namespace, contextNamespace);
                }
            }
            catch {
                /* empty */
            }
            // apply precedence for flags
            argv = configManager.applyPrecedence(argv, yargs.parsed.aliases);
            // update config manager
            configManager.update(argv);
            // Build data to be displayed
            const currentCommand = argv._.join(' ');
            const commandArguments = flags.stringifyArgv(argv);
            const commandData = (currentCommand + ' ' + commandArguments).trim();
            // Check if output format is set (machine-readable modes: json, yaml, wide)
            const outputFormat = configManager.getFlag(flags.output) || '';
            const isMachineReadable = ['json', 'yaml', 'wide'].includes(outputFormat);
            if (this.taskList.parentTaskListMap.size === 0 && !isMachineReadable) {
                // Display command header (skip in machine-readable output modes)
                logger.showUser(chalk.cyan('\n******************************* Solo *********************************************'));
                logger.showUser(chalk.cyan('Version\t\t\t:'), chalk.yellow(configManager.getVersion()));
                logger.showUser(chalk.cyan('Kubernetes Context\t:'), chalk.yellow(contextName));
                logger.showUser(chalk.cyan('Kubernetes Cluster\t:'), chalk.yellow(clusterName));
                logger.showUser(chalk.cyan('Current Command\t\t:'), chalk.yellow(commandData));
                if (configManager.getFlag(flags.namespace)?.name) {
                    logger.showUser(chalk.cyan('Kubernetes Namespace\t:'), chalk.yellow(configManager.getFlag(flags.namespace)));
                }
                logger.showUser(chalk.cyan('**********************************************************************************'));
            }
            return argv;
        };
    }
};
Middlewares = __decorate([
    injectable(),
    __param(0, inject(InjectTokens.ConfigManager)),
    __param(1, inject(InjectTokens.RemoteConfigRuntimeState)),
    __param(2, inject(InjectTokens.K8Factory)),
    __param(3, inject(InjectTokens.SoloLogger)),
    __param(4, inject(InjectTokens.LocalConfigRuntimeState)),
    __param(5, inject(InjectTokens.HelpRenderer)),
    __param(6, inject(InjectTokens.TaskList)),
    __param(7, inject(InjectTokens.InitCommand)),
    __param(8, inject(InjectTokens.NpmClient)),
    __metadata("design:paramtypes", [Function, Object, Object, Object, LocalConfigRuntimeState, Function, Object, Function, NpmClient])
], Middlewares);
export { Middlewares };
//# sourceMappingURL=middlewares.js.map