import json
import sys

def make_federate(cmd):


    runner = { "federates" : [],
               "name" : "Generated by make samples"}

    for k,v in cmd.items():
        federate = {"directory" : ".",
                    "exec" : v,
                    "host" : "broker",
                    "name" : k,
                    "loglevel" : 3}
        runner["federates"].append(federate)

    helics_runner = json.dumps(runner, indent=4)
    print(helics_runner)

    return runner

    

def main():
    samples = 1
    seed = 1
    port = 12345
    if len(sys.argv) > 1:
        samples = sys.argv[1]
        output_path = sys.argv[2]
        broker = "0.0.0.0" # hardcoding broker for now since we can't use it
    print ("Generating " + samples + " federates")

    with open(output_path+"/samples.csv", "w") as fed:
        for i in range(int(samples)):
            runner_dict = {}
            runner_name = "EVMsgrunner_" + str(i) + ".json"
            fed.write(runner_name+"\n")

            with open (output_path+"/"+runner_name, "w") as h_runner:
                runner_dict.update( {'broker_' + str(i) : "helics_broker --federates=2 --loglevel=5 --type=tcpss --port " + str(port)} )
                runner_dict.update( {'EVMsgFed_' + str(i) : "python3 EVMsgFed.py --port {} --seed {}".format(str(port), str(seed))} )
                runner_dict.update( {'EVController_' + str(i) : "python3 EVControllerMsgFed.py --port {}".format(str(port))} )
                runner = json.dumps(make_federate(runner_dict), indent=4)
                h_runner.write(runner)
                h_runner.close()

            seed += 1
            port += 1

        fed.close()
        

if __name__ == "__main__":
    main()
