#! /usr/bin/env python3
"""
Convenience script for calling the plenum command line interface (CLI). For now,
the CLI is designed for experimenting with the Plenum Byzantine Fault Tolerant
Protocol, and not for creating a live consensus pool. For that, it's as simple
as defining a node registry, creating a looper, creating a node, and running it.
See the example folder or the tutorial folder.

$ scripts/plenum

or supply a command to be executed first

$ scripts/plenum "new nodes all"

"""
import logging

# NOTE: Loading of plugin should happen as early as possible
# So put all other required imports after loadPlugins function call below
from plenum.common.keygen_utils import initLocalKeys
from plenum.common.util import randomString
from plenum.common.config_util import getConfig
from plenum.common.plugin_helper import loadPlugins

logging.root.handlers = []
logger = logging.getLogger()
logger.propagate = False
logger.disabled = True

config = getConfig()
basedirpath = config.baseDir
loadPlugins(basedirpath)

# NOTE: Put all regular imports below (not related to loadplugin)
import sys
from plenum.cli.cli import Cli
from stp_core.loop.looper import Looper


def run_cli():
    nodeReg = config.nodeReg
    cliNodeReg = config.cliNodeReg
    commands = sys.argv[1:]
    for name in {**nodeReg, **cliNodeReg}:
        initLocalKeys(name, basedirpath, randomString(32), use_bls=True, override=True)
    with Looper(debug=config.LOOPER_DEBUG) as looper:
        cli = Cli(looper=looper,
                  nodeReg=nodeReg,
                  cliNodeReg=cliNodeReg,
                  basedirpath=basedirpath,
                  logFileName='log/cli.log',
                  useNodeReg=True)

        looper.run(cli.shell(*commands))


if __name__ == '__main__':
    run_cli()
