// 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); }
};
var DefaultOneShotCommand_1;
import { SoloError } from '../../core/errors/solo-error.js';
import * as constants from '../../core/constants.js';
import { BaseCommand } from '../base.js';
import { Flags as flags, Flags } from '../flags.js';
import { injectable, inject } from 'tsyringe-neo';
import { v4 as uuid4 } from 'uuid';
import { NamespaceName } from '../../types/namespace/namespace-name.js';
import { StringEx } from '../../business/utils/string-ex.js';
import * as version from '../../../version.js';
import { confirm as confirmPrompt } from '@inquirer/prompts';
import { ClusterReferenceCommandDefinition } from '../command-definitions/cluster-reference-command-definition.js';
import { DeploymentCommandDefinition } from '../command-definitions/deployment-command-definition.js';
import { ConsensusCommandDefinition } from '../command-definitions/consensus-command-definition.js';
import { KeysCommandDefinition } from '../command-definitions/keys-command-definition.js';
import { MirrorCommandDefinition } from '../command-definitions/mirror-command-definition.js';
import { ExplorerCommandDefinition } from '../command-definitions/explorer-command-definition.js';
import { RelayCommandDefinition } from '../command-definitions/relay-command-definition.js';
import { patchInject } from '../../core/dependency-injection/container-helper.js';
import { InjectTokens } from '../../core/dependency-injection/inject-tokens.js';
import { PREDEFINED_ACCOUNT_GROUPS, predefinedEcdsaAccounts, predefinedEcdsaAccountsWithAlias, predefinedEd25519Accounts, } from './predefined-accounts.js';
import { AccountId, HbarUnit, PublicKey } from '@hiero-ledger/sdk';
import * as helpers from '../../core/helpers.js';
import { Duration } from '../../core/time/duration.js';
import { resolveNamespaceFromDeployment } from '../../core/resolvers.js';
import fs from 'node:fs';
import chalk from 'chalk';
import { PathEx } from '../../business/utils/path-ex.js';
import { createDirectoryIfNotExists, entityId, remoteConfigsToDeploymentsTable } from '../../core/helpers.js';
import yaml from 'yaml';
import { BlockCommandDefinition } from '../command-definitions/block-command-definition.js';
import { argvPushGlobalFlags, invokeSoloCommand, newArgv, optionFromFlag } from '../command-helpers.js';
import { Templates } from '../../core/templates.js';
import { ListrInquirerPromptAdapter } from '@listr2/prompt-adapter-inquirer';
let DefaultOneShotCommand = class DefaultOneShotCommand extends BaseCommand {
    static { DefaultOneShotCommand_1 = this; }
    accountManager;
    static SINGLE_DEPLOY_CONFIGS_NAME = 'singleAddConfigs';
    static SINGLE_DESTROY_CONFIGS_NAME = 'singleDestroyConfigs';
    static DEPLOY_FLAGS_LIST = {
        required: [],
        optional: [flags.quiet, flags.numberOfConsensusNodes, flags.force, flags.deployment, flags.minimalSetup],
    };
    static DESTROY_FLAGS_LIST = {
        required: [],
        optional: [flags.quiet],
    };
    static FALCON_DEPLOY_FLAGS_LIST = {
        required: [],
        optional: [flags.quiet, flags.valuesFile, flags.numberOfConsensusNodes],
    };
    static FALCON_DESTROY_FLAGS_LIST = {
        required: [],
        optional: [...DefaultOneShotCommand_1.DESTROY_FLAGS_LIST.optional],
    };
    constructor(accountManager) {
        super();
        this.accountManager = accountManager;
        this.accountManager = patchInject(accountManager, InjectTokens.AccountManager, this.constructor.name);
    }
    /**
     * Appends non-empty config entries to the argv array as CLI flags.
     * @param argv - The argument array to append to
     * @param configSection - The config object to extract key-value pairs from
     */
    appendConfigToArgv(argv, configSection) {
        if (!configSection) {
            return;
        }
        for (const [key, value] of Object.entries(configSection)) {
            if (value !== undefined && value !== null && value !== StringEx.EMPTY) {
                argv.push(`${key}`, value.toString());
            }
        }
    }
    async deploy(argv) {
        return this.deployInternal(argv, DefaultOneShotCommand_1.DEPLOY_FLAGS_LIST);
    }
    async deployFalcon(argv) {
        return this.deployInternal(argv, DefaultOneShotCommand_1.FALCON_DEPLOY_FLAGS_LIST);
    }
    async deployInternal(argv, flagsList) {
        let config = null;
        const tasks = this.taskList.newOneShotSingleDeployTaskList([
            {
                title: 'Initialize',
                task: async (context_, task) => {
                    this.configManager.update(argv);
                    flags.disablePrompts(flagsList.optional);
                    const allFlags = [...flagsList.required, ...flagsList.optional];
                    await this.configManager.executePrompt(task, allFlags);
                    context_.config = this.configManager.getConfig(DefaultOneShotCommand_1.SINGLE_DEPLOY_CONFIGS_NAME, allFlags);
                    config = context_.config;
                    const uniquePostfix = uuid4().slice(-8);
                    // Initialize component config sections to empty objects to prevent undefined errors
                    config.consensusNodeConfiguration = {};
                    config.mirrorNodeConfiguration = {};
                    config.blockNodeConfiguration = {};
                    config.explorerNodeConfiguration = {};
                    config.relayNodeConfiguration = {};
                    config.networkConfiguration = {};
                    config.setupConfiguration = {};
                    // if valuesFile is set, read the yaml file and save flags to different config sections to be used
                    // later for consensus node, mirror node, block node, explorer node, relay node
                    if (context_.config.valuesFile) {
                        const valuesFileContent = fs.readFileSync(context_.config.valuesFile, 'utf8');
                        const profileItems = yaml.parse(valuesFileContent);
                        // Override with values from file if they exist
                        if (profileItems.network) {
                            config.networkConfiguration = profileItems.network;
                        }
                        if (profileItems.setup) {
                            config.setupConfiguration = profileItems.setup;
                        }
                        if (profileItems.consensusNode) {
                            config.consensusNodeConfiguration = profileItems.consensusNode;
                        }
                        if (profileItems.mirrorNode) {
                            config.mirrorNodeConfiguration = profileItems.mirrorNode;
                        }
                        if (profileItems.blockNode) {
                            config.blockNodeConfiguration = profileItems.blockNode;
                        }
                        if (profileItems.explorerNode) {
                            config.explorerNodeConfiguration = profileItems.explorerNode;
                        }
                        if (profileItems.relayNode) {
                            config.relayNodeConfiguration = profileItems.relayNode;
                        }
                    }
                    context_.config.clusterRef = context_.config.clusterRef || `solo-${uniquePostfix}`;
                    context_.config.context = context_.config.context || this.k8Factory.default().contexts().readCurrent();
                    context_.config.deployment = context_.config.deployment || `solo-deployment-${uniquePostfix}`;
                    context_.config.namespace = context_.config.namespace || NamespaceName.of(`solo-${uniquePostfix}`);
                    context_.config.numberOfConsensusNodes = context_.config.numberOfConsensusNodes || 1;
                    context_.config.force = argv.force;
                    context_.createdAccounts = [];
                    return;
                },
            },
            {
                title: 'Check for other deployments',
                task: async (context_, task) => {
                    const existingRemoteConfigs = await this.k8Factory
                        .default()
                        .configMaps()
                        .listForAllNamespaces(Templates.renderConfigMapRemoteConfigLabels());
                    if (existingRemoteConfigs.length > 0) {
                        const existingDeploymentsTable = remoteConfigsToDeploymentsTable(existingRemoteConfigs);
                        const promptOptions = {
                            default: false,
                            message: '⚠️ Warning: Existing solo deployment detected in cluster.\n\n' +
                                existingDeploymentsTable.join('\n') +
                                '\n\nCreating another deployment will require additional' +
                                ' CPU and memory resources. Do you want to proceed and create another deployment?',
                        };
                        const proceed = await task
                            .prompt(ListrInquirerPromptAdapter)
                            .run(confirmPrompt, promptOptions);
                        if (!proceed) {
                            throw new SoloError('Aborted by user');
                        }
                    }
                },
                skip: (context_) => context_.config.force === true,
            },
            invokeSoloCommand(`solo ${ClusterReferenceCommandDefinition.CONNECT_COMMAND}`, ClusterReferenceCommandDefinition.CONNECT_COMMAND, () => {
                const argv = newArgv();
                argv.push(...ClusterReferenceCommandDefinition.CONNECT_COMMAND.split(' '), optionFromFlag(Flags.clusterRef), config.clusterRef, optionFromFlag(Flags.context), config.context);
                return argvPushGlobalFlags(argv);
            }, this.taskList),
            invokeSoloCommand(`solo ${DeploymentCommandDefinition.CREATE_COMMAND}`, DeploymentCommandDefinition.CREATE_COMMAND, () => {
                const argv = newArgv();
                argv.push(...DeploymentCommandDefinition.CREATE_COMMAND.split(' '), optionFromFlag(Flags.deployment), config.deployment, optionFromFlag(Flags.namespace), config.namespace.name);
                return argvPushGlobalFlags(argv);
            }, this.taskList),
            invokeSoloCommand(`solo ${DeploymentCommandDefinition.ATTACH_COMMAND}`, DeploymentCommandDefinition.ATTACH_COMMAND, () => {
                const argv = newArgv();
                argv.push(...DeploymentCommandDefinition.ATTACH_COMMAND.split(' '), optionFromFlag(Flags.deployment), config.deployment, optionFromFlag(Flags.clusterRef), config.clusterRef, optionFromFlag(Flags.numberOfConsensusNodes), config.numberOfConsensusNodes.toString());
                return argvPushGlobalFlags(argv);
            }, this.taskList),
            invokeSoloCommand(`solo ${ClusterReferenceCommandDefinition.SETUP_COMMAND}`, ClusterReferenceCommandDefinition.SETUP_COMMAND, () => {
                const argv = newArgv();
                argv.push(...ClusterReferenceCommandDefinition.SETUP_COMMAND.split(' '), optionFromFlag(Flags.clusterRef), config.clusterRef);
                return argvPushGlobalFlags(argv);
            }, this.taskList),
            invokeSoloCommand(`solo ${KeysCommandDefinition.KEYS_COMMAND}`, KeysCommandDefinition.KEYS_COMMAND, () => {
                const argv = newArgv();
                argv.push(...KeysCommandDefinition.KEYS_COMMAND.split(' '), optionFromFlag(Flags.deployment), config.deployment, optionFromFlag(Flags.generateGossipKeys), 'true', optionFromFlag(Flags.generateTlsKeys));
                return argvPushGlobalFlags(argv, config.cacheDir);
            }, this.taskList),
            invokeSoloCommand(`solo ${BlockCommandDefinition.ADD_COMMAND}`, BlockCommandDefinition.ADD_COMMAND, () => {
                const argv = newArgv();
                argv.push(...BlockCommandDefinition.ADD_COMMAND.split(' '), optionFromFlag(Flags.deployment), config.deployment);
                return argvPushGlobalFlags(argv);
            }, this.taskList, () => constants.ONE_SHOT_WITH_BLOCK_NODE.toLowerCase() !== 'true'),
            invokeSoloCommand(`solo ${ConsensusCommandDefinition.DEPLOY_COMMAND}`, ConsensusCommandDefinition.DEPLOY_COMMAND, () => {
                const argv = newArgv();
                argv.push(...ConsensusCommandDefinition.DEPLOY_COMMAND.split(' '), optionFromFlag(Flags.deployment), config.deployment);
                if (config.networkConfiguration) {
                    this.appendConfigToArgv(argv, config.networkConfiguration);
                }
                return argvPushGlobalFlags(argv, config.cacheDir);
            }, this.taskList),
            invokeSoloCommand(`solo ${ConsensusCommandDefinition.SETUP_COMMAND}`, ConsensusCommandDefinition.SETUP_COMMAND, () => {
                const argv = newArgv();
                argv.push(...ConsensusCommandDefinition.SETUP_COMMAND.split(' '), optionFromFlag(Flags.deployment), config.deployment);
                this.appendConfigToArgv(argv, config.setupConfiguration);
                return argvPushGlobalFlags(argv, config.cacheDir);
            }, this.taskList),
            invokeSoloCommand(`solo ${ConsensusCommandDefinition.START_COMMAND}`, ConsensusCommandDefinition.START_COMMAND, () => {
                const argv = newArgv();
                argv.push(...ConsensusCommandDefinition.START_COMMAND.split(' '), optionFromFlag(Flags.deployment), config.deployment);
                this.appendConfigToArgv(argv, config.consensusNodeConfiguration);
                return argvPushGlobalFlags(argv);
            }, this.taskList),
            invokeSoloCommand(`solo ${MirrorCommandDefinition.ADD_COMMAND}`, MirrorCommandDefinition.ADD_COMMAND, () => {
                const argv = newArgv();
                argv.push(...MirrorCommandDefinition.ADD_COMMAND.split(' '), optionFromFlag(Flags.deployment), config.deployment, optionFromFlag(Flags.clusterRef), config.clusterRef, optionFromFlag(Flags.pinger), optionFromFlag(Flags.enableIngress));
                this.appendConfigToArgv(argv, config.mirrorNodeConfiguration);
                return argvPushGlobalFlags(argv, config.cacheDir);
            }, this.taskList),
            {
                title: 'Extended setup',
                task: async (context_, task) => {
                    const subTasks = [
                        invokeSoloCommand(`solo ${ExplorerCommandDefinition.ADD_COMMAND}`, ExplorerCommandDefinition.ADD_COMMAND, () => {
                            const argv = newArgv();
                            argv.push(...ExplorerCommandDefinition.ADD_COMMAND.split(' '), optionFromFlag(Flags.deployment), config.deployment, optionFromFlag(Flags.clusterRef), config.clusterRef);
                            this.appendConfigToArgv(argv, config.explorerNodeConfiguration);
                            return argvPushGlobalFlags(argv, config.cacheDir);
                        }, this.taskList),
                        invokeSoloCommand(`solo ${RelayCommandDefinition.ADD_COMMAND}`, RelayCommandDefinition.ADD_COMMAND, () => {
                            const argv = newArgv();
                            argv.push(...RelayCommandDefinition.ADD_COMMAND.split(' '), optionFromFlag(Flags.deployment), config.deployment, optionFromFlag(Flags.clusterRef), config.clusterRef, optionFromFlag(Flags.nodeAliasesUnparsed), 'node1');
                            this.appendConfigToArgv(argv, config.relayNodeConfiguration);
                            return argvPushGlobalFlags(argv);
                        }, this.taskList),
                    ];
                    // set up the sub-tasks
                    return task.newListr(subTasks, {
                        concurrent: false,
                        rendererOptions: {
                            collapseSubtasks: false,
                        },
                    });
                },
                skip: () => config.minimalSetup,
            },
            {
                title: 'Create Accounts',
                skip: () => config.predefinedAccounts === false,
                task: async (context_, task) => {
                    await this.localConfig.load();
                    await this.remoteConfig.loadAndValidate(argv);
                    const self = this;
                    const subTasks = [];
                    const accountsToCreate = [
                        ...predefinedEcdsaAccounts,
                        ...predefinedEcdsaAccountsWithAlias,
                        ...predefinedEd25519Accounts,
                    ];
                    await self.accountManager.loadNodeClient(config.namespace, self.remoteConfig.getClusterRefs(), context_.config.deployment);
                    for (const [index, account] of accountsToCreate.entries()) {
                        // inject index to avoid closure issues
                        ((index, account) => {
                            subTasks.push({
                                title: `Creating Account ${index}`,
                                task: async (context_, subTask) => {
                                    await helpers.sleep(Duration.ofMillis(100 * index));
                                    const createdAccount = await self.accountManager.createNewAccount(context_.config.namespace, account.privateKey, account.balance.to(HbarUnit.Hbar).toNumber(), account.alias, context_.config.context);
                                    context_.createdAccounts.push({
                                        accountId: AccountId.fromString(createdAccount.accountId),
                                        data: account,
                                        alias: createdAccount.accountAlias,
                                        publicKey: createdAccount.publicKey,
                                    });
                                    subTask.title = `Account created: ${createdAccount.accountId.toString()}`;
                                },
                            });
                        })(index, account);
                    }
                    // set up the sub-tasks
                    return task.newListr(subTasks, {
                        concurrent: true,
                        rendererOptions: {
                            collapseSubtasks: false,
                        },
                    });
                },
            },
            {
                title: 'Finish',
                task: async (context_) => {
                    const outputDirectory = PathEx.join(constants.SOLO_HOME_DIR, `one-shot-${context_.config.deployment}`);
                    this.showOneShotUserNotes(context_, false, PathEx.join(outputDirectory, 'notes'));
                    this.showVersions(PathEx.join(outputDirectory, 'versions'));
                    this.showPortForwards(PathEx.join(outputDirectory, 'forwards'));
                    this.showAccounts(context_.createdAccounts, context_, PathEx.join(outputDirectory, 'accounts.json'));
                    this.cacheDeploymentName(context_, PathEx.join(constants.SOLO_CACHE_DIR, 'last-one-shot-deployment.txt'));
                    return;
                },
            },
        ], constants.LISTR_DEFAULT_OPTIONS.DEFAULT);
        try {
            await tasks.run();
        }
        catch (error) {
            throw new SoloError(`Error deploying Solo in one-shot mode: ${error.message}`, error);
        }
        finally {
            await this.taskList
                .callCloseFunctions()
                .then()
                .catch((error) => {
                this.logger.error('Error during closing task list:', error);
            });
        }
        return true;
    }
    showOneShotUserNotes(context_, isMultiple = false, outputFile) {
        const messageGroupKey = isMultiple ? 'one-shot-multiple-user-notes' : 'one-shot-user-notes';
        const title = isMultiple ? 'One Shot Multiple User Notes' : 'One Shot User Notes';
        this.logger.addMessageGroup(messageGroupKey, title);
        const data = [
            `Cluster Reference: ${context_.config.clusterRef}`,
            `Deployment Name: ${context_.config.deployment}`,
            `Namespace Name: ${context_.config.namespace.name}`,
        ];
        for (const line of data) {
            this.logger.addMessageGroupMessage(messageGroupKey, line);
        }
        if (isMultiple) {
            this.logger.addMessageGroupMessage(messageGroupKey, `Number of Consensus Nodes: ${context_.config.numberOfConsensusNodes}`);
        }
        this.logger.addMessageGroupMessage(messageGroupKey, 'To quickly delete the deployed resources, run the following command:\n' +
            `kubectl delete ns ${context_.config.namespace.name}`);
        this.logger.showMessageGroup(messageGroupKey);
        if (outputFile) {
            const fileData = data.join('\n') + '\n';
            createDirectoryIfNotExists(outputFile);
            fs.writeFileSync(outputFile, fileData);
            this.logger.showUser(chalk.green(`✅ User notes saved to file: ${outputFile}`));
        }
    }
    showVersions(outputFile) {
        const messageGroupKey = 'versions-used';
        this.logger.addMessageGroup(messageGroupKey, 'Versions Used');
        const data = [
            `Solo Chart Version: ${version.SOLO_CHART_VERSION}`,
            `Consensus Node Version: ${version.HEDERA_PLATFORM_VERSION}`,
            `Mirror Node Version: ${version.MIRROR_NODE_VERSION}`,
            `Explorer Version: ${version.EXPLORER_VERSION}`,
            `JSON RPC Relay Version: ${version.HEDERA_JSON_RPC_RELAY_VERSION}`,
        ];
        for (const line of data) {
            this.logger.addMessageGroupMessage(messageGroupKey, line);
        }
        this.logger.showMessageGroup(messageGroupKey);
        if (outputFile) {
            const fileData = data.join('\n') + '\n';
            createDirectoryIfNotExists(outputFile);
            fs.writeFileSync(outputFile, fileData);
            this.logger.showUser(chalk.green(`✅ Versions used saved to file: ${outputFile}`));
        }
    }
    cacheDeploymentName(context, outputFile) {
        fs.writeFileSync(outputFile, context.config.deployment);
        this.logger.showUser(chalk.green(`✅ Deployment name (${context.config.deployment}) saved to file: ${outputFile}`));
    }
    showAccounts(createdAccounts = [], context, outputFile) {
        if (createdAccounts.length > 0) {
            createdAccounts.sort((a, b) => a.accountId.compare(b.accountId));
            const ecdsaAccounts = createdAccounts.filter((account) => account.data.group === PREDEFINED_ACCOUNT_GROUPS.ECDSA);
            const aliasAccounts = createdAccounts.filter((account) => account.data.group === PREDEFINED_ACCOUNT_GROUPS.ECDSA_ALIAS);
            const ed25519Accounts = createdAccounts.filter((account) => account.data.group === PREDEFINED_ACCOUNT_GROUPS.ED25519);
            const systemAccountsGroupKey = 'system-accounts';
            const messageGroupKey = 'accounts-created';
            const ecdsaGroupKey = 'accounts-created-ecdsa';
            const ecdsaAliasGroupKey = 'accounts-created-ecdsa-alias';
            const ed25519GroupKey = 'accounts-created-ed25519';
            const realm = this.localConfig.configuration.realmForDeployment(context.config.deployment);
            const shard = this.localConfig.configuration.shardForDeployment(context.config.deployment);
            const operatorAccountData = {
                name: 'Operator',
                accountId: entityId(shard, realm, 2),
                publicKey: constants.GENESIS_PUBLIC_KEY,
            };
            if (constants.GENESIS_KEY === constants.DEFAULT_GENESIS_KEY) {
                operatorAccountData.privateKey = constants.DEFAULT_GENESIS_KEY;
            }
            const systemAccounts = [operatorAccountData];
            if (systemAccounts.length > 0) {
                this.logger.addMessageGroup(systemAccountsGroupKey, 'System Accounts');
                for (const account of systemAccounts) {
                    let message = `${account.name} Account ID: ${account.accountId.toString()}, Public Key: ${account.publicKey.toString()}`;
                    if (account.privateKey) {
                        message += `, Private Key: ${account.privateKey}`;
                    }
                    this.logger.addMessageGroupMessage(systemAccountsGroupKey, message);
                }
                this.logger.showMessageGroup(systemAccountsGroupKey);
            }
            this.logger.addMessageGroup(messageGroupKey, 'Created Accounts');
            this.logger.addMessageGroup(ecdsaGroupKey, 'ECDSA Accounts (Not EVM compatible, See ECDSA Alias Accounts above)');
            this.logger.addMessageGroup(ecdsaAliasGroupKey, 'ECDSA Alias Accounts (EVM compatible)');
            this.logger.addMessageGroup(ed25519GroupKey, 'ED25519 Accounts');
            if (aliasAccounts.length > 0) {
                for (const account of aliasAccounts) {
                    this.logger.addMessageGroupMessage(ecdsaAliasGroupKey, `Account ID: ${account.accountId.toString()}, Public address: ${account.alias}, Private Key: 0x${account.data.privateKey.toStringRaw()}, Balance: ${account.data.balance.toString()}`);
                }
                this.logger.showMessageGroup(ecdsaAliasGroupKey);
            }
            if (ed25519Accounts.length > 0) {
                for (const account of ed25519Accounts) {
                    this.logger.addMessageGroupMessage(ed25519GroupKey, `Account ID: ${account.accountId.toString()}, Private Key: 0x${account.data.privateKey.toStringRaw()}, Balance: ${account.data.balance.toString()}`);
                }
                this.logger.showMessageGroup(ed25519GroupKey);
            }
            if (ecdsaAccounts.length > 0) {
                for (const account of ecdsaAccounts) {
                    this.logger.addMessageGroupMessage(ecdsaGroupKey, `Account ID: ${account.accountId.toString()}, Private Key: 0x${account.data.privateKey.toStringRaw()}, Balance: ${account.data.balance.toString()}`);
                }
                this.logger.showMessageGroup(ecdsaGroupKey);
            }
            if (outputFile) {
                createDirectoryIfNotExists(outputFile);
                // Format account data in the same way as it appears in the console output
                const formattedCreatedAccounts = createdAccounts.map(account => {
                    const formattedAccount = {
                        accountId: account.accountId.toString(),
                        privateKey: `0x${account.data.privateKey.toStringRaw()}`,
                        publicKey: `0x${PublicKey.fromString(account.publicKey).toStringRaw()}`,
                        balance: account.data.balance.toString(),
                        group: account.data.group,
                    };
                    // Add alias field for ECDSA_ALIAS accounts
                    if (account.data.group === PREDEFINED_ACCOUNT_GROUPS.ECDSA_ALIAS && account.alias) {
                        formattedAccount['publicAddress'] = account.alias;
                    }
                    return formattedAccount;
                });
                // Format system accounts data
                const formattedSystemAccounts = systemAccounts.map(account => ({
                    name: account.name,
                    accountId: account.accountId.toString(),
                    publicKey: account.publicKey.toString(),
                    privateKey: account.privateKey,
                }));
                // Create the structured output with both systemAccounts and createdAccounts
                const outputData = {
                    systemAccounts: formattedSystemAccounts,
                    createdAccounts: formattedCreatedAccounts,
                };
                fs.writeFileSync(outputFile, JSON.stringify(outputData, null, 2));
                this.logger.showUser(chalk.green(`✅ Created accounts saved to file in JSON format: ${outputFile}`));
            }
            this.logger.showUser('For more information on public and private keys see: https://docs.hedera.com/hedera/core-concepts/keys-and-signatures');
        }
    }
    showPortForwards(outputFile) {
        this.logger.showMessageGroup(constants.PORT_FORWARDING_MESSAGE_GROUP);
        if (outputFile) {
            const messages = this.logger.getMessageGroup(constants.PORT_FORWARDING_MESSAGE_GROUP);
            const fileData = messages.join('\n') + '\n';
            createDirectoryIfNotExists(outputFile);
            fs.writeFileSync(outputFile, fileData);
            this.logger.showUser(chalk.green(`✅ Port forwarding info saved to file: ${outputFile}`));
        }
    }
    async destroy(argv) {
        return this.destroyInternal(argv, DefaultOneShotCommand_1.DESTROY_FLAGS_LIST);
    }
    async destroyFalcon(argv) {
        return this.destroyInternal(argv, DefaultOneShotCommand_1.FALCON_DESTROY_FLAGS_LIST);
    }
    async destroyInternal(argv, flagsList) {
        let config;
        const taskArray = [
            {
                title: 'Initialize',
                task: async (context_, task) => {
                    this.configManager.update(argv);
                    flags.disablePrompts(flagsList.optional);
                    const allFlags = [...flagsList.required, ...flagsList.optional];
                    await this.configManager.executePrompt(task, allFlags);
                    context_.config = this.configManager.getConfig(DefaultOneShotCommand_1.SINGLE_DESTROY_CONFIGS_NAME, allFlags);
                    config = context_.config;
                    await this.localConfig.load();
                    config.cacheDir ??= constants.SOLO_CACHE_DIR;
                    config.clusterRef ??= this.localConfig.configuration.clusterRefs.keys().next().value;
                    config.context ??= this.localConfig.configuration.clusterRefs.get(config.clusterRef).toString();
                    if (!config.deployment) {
                        if (this.localConfig.configuration.deployments.length === 0) {
                            throw new SoloError('Deployments name is not found in local config');
                        }
                        config.deployment = this.localConfig.configuration.deployments.get(0).name;
                        this.configManager.setFlag(flags.deployment, config.deployment);
                    }
                    config.namespace ??= await resolveNamespaceFromDeployment(this.localConfig, this.configManager, task);
                    await this.remoteConfig.loadAndValidate(argv);
                },
            },
            {
                title: 'Destroy extended setup',
                task: async (context_, task) => {
                    const subTasks = [
                        invokeSoloCommand(`solo ${ExplorerCommandDefinition.DESTROY_COMMAND}`, ExplorerCommandDefinition.DESTROY_COMMAND, () => {
                            const argv = newArgv();
                            argv.push(...ExplorerCommandDefinition.DESTROY_COMMAND.split(' '), optionFromFlag(flags.clusterRef), config.clusterRef, optionFromFlag(flags.deployment), config.deployment, optionFromFlag(flags.quiet), optionFromFlag(flags.force));
                            return argvPushGlobalFlags(argv);
                        }, this.taskList),
                        invokeSoloCommand(`solo ${RelayCommandDefinition.DESTROY_COMMAND}`, RelayCommandDefinition.DESTROY_COMMAND, () => {
                            const argv = newArgv();
                            argv.push(...RelayCommandDefinition.DESTROY_COMMAND.split(' '), optionFromFlag(flags.clusterRef), config.clusterRef, optionFromFlag(flags.deployment), config.deployment, optionFromFlag(flags.nodeAliasesUnparsed), 'node1', optionFromFlag(flags.quiet));
                            return argvPushGlobalFlags(argv);
                        }, this.taskList),
                    ];
                    // set up the sub-tasks
                    return task.newListr(subTasks, {
                        concurrent: false,
                        rendererOptions: {
                            collapseSubtasks: false,
                        },
                    });
                },
                skip: () => {
                    const hasExplorers = this.remoteConfig.configuration.components.state.explorers.length > 0;
                    const hasRelays = this.remoteConfig.configuration.components.state.relayNodes.length > 0;
                    return !hasExplorers || !hasRelays;
                },
            },
            invokeSoloCommand(`solo ${MirrorCommandDefinition.DESTROY_COMMAND}`, MirrorCommandDefinition.DESTROY_COMMAND, () => {
                const argv = newArgv();
                argv.push(...MirrorCommandDefinition.DESTROY_COMMAND.split(' '), optionFromFlag(flags.clusterRef), config.clusterRef, optionFromFlag(flags.deployment), config.deployment, optionFromFlag(flags.quiet), optionFromFlag(flags.force), optionFromFlag(flags.devMode));
                return argvPushGlobalFlags(argv);
            }, this.taskList),
            invokeSoloCommand(`solo ${BlockCommandDefinition.DESTROY_COMMAND}`, BlockCommandDefinition.DESTROY_COMMAND, () => {
                const argv = newArgv();
                argv.push(...BlockCommandDefinition.DESTROY_COMMAND.split(' '), optionFromFlag(Flags.deployment), config.deployment, optionFromFlag(flags.clusterRef), config.clusterRef, optionFromFlag(flags.quiet));
                return argvPushGlobalFlags(argv);
            }, this.taskList, () => constants.ONE_SHOT_WITH_BLOCK_NODE.toLowerCase() !== 'true'),
            invokeSoloCommand(`solo ${ConsensusCommandDefinition.DESTROY_COMMAND}`, ConsensusCommandDefinition.DESTROY_COMMAND, () => {
                const argv = newArgv();
                argv.push(...ConsensusCommandDefinition.DESTROY_COMMAND.split(' '), optionFromFlag(flags.deployment), config.deployment, optionFromFlag(flags.quiet), optionFromFlag(flags.force), optionFromFlag(flags.deletePvcs), optionFromFlag(flags.deleteSecrets), optionFromFlag(flags.enableTimeout));
                return argvPushGlobalFlags(argv);
            }, this.taskList),
            invokeSoloCommand(`solo ${ClusterReferenceCommandDefinition.RESET_COMMAND}`, ClusterReferenceCommandDefinition.RESET_COMMAND, () => {
                const argv = newArgv();
                argv.push(...ClusterReferenceCommandDefinition.RESET_COMMAND.split(' '), optionFromFlag(flags.clusterRef), config.clusterRef, optionFromFlag(flags.quiet), optionFromFlag(flags.force));
                return argvPushGlobalFlags(argv);
            }, this.taskList),
            invokeSoloCommand(`solo ${ClusterReferenceCommandDefinition.DISCONNECT_COMMAND}`, ClusterReferenceCommandDefinition.DISCONNECT_COMMAND, () => {
                const argv = newArgv();
                argv.push(...ClusterReferenceCommandDefinition.DISCONNECT_COMMAND.split(' '), optionFromFlag(flags.clusterRef), config.clusterRef, optionFromFlag(flags.quiet));
                return argvPushGlobalFlags(argv);
            }, this.taskList),
            invokeSoloCommand(`solo ${DeploymentCommandDefinition.DELETE_COMMAND}`, DeploymentCommandDefinition.DELETE_COMMAND, () => {
                const argv = newArgv();
                argv.push(...DeploymentCommandDefinition.DELETE_COMMAND.split(' '), optionFromFlag(flags.deployment), config.deployment, optionFromFlag(flags.quiet));
                return argvPushGlobalFlags(argv);
            }, this.taskList),
            {
                title: 'Delete cache folder',
                task: async () => {
                    fs.rmSync(config.cacheDir, { recursive: true, force: true });
                },
            },
            { title: 'Finish', task: async () => { } },
        ];
        const tasks = this.taskList.newOneShotSingleDestroyTaskList(taskArray, constants.LISTR_DEFAULT_OPTIONS.DEFAULT);
        try {
            await tasks.run();
        }
        catch (error) {
            throw new SoloError(`Error destroying Solo in one-shot mode: ${error.message}`, error);
        }
        finally {
            await this.taskList
                .callCloseFunctions()
                .then()
                .catch((error) => this.logger.error('Error during closing task list:', error));
        }
        return true;
    }
    async close() { } // no-op
};
DefaultOneShotCommand = DefaultOneShotCommand_1 = __decorate([
    injectable(),
    __param(0, inject(InjectTokens.AccountManager)),
    __metadata("design:paramtypes", [Function])
], DefaultOneShotCommand);
export { DefaultOneShotCommand };
//# sourceMappingURL=default-one-shot.js.map