#!/usr/bin/env python3

import subprocess
import csv

strategies = ["ParBuffer", "Sequential", "RDeepSeq", "RSeq", "RPar", "SixWay", "Chunks","BufferChunks"]

c_filepath = "../corpus/very-small.txt"

def parse_rts_output(rts_out):
    exec("global out; out = {}".format(rts_out))
    d = dict() 
    for k, v in out:
        d[k] = float(v) if '.' in v else int(v) 
    return d

def all_decrypts(): 
    all_decrypts = []
    for strat in strategies: 
        for _ in range(5): 
            if strat == "ParBuffer": 
                for buff_size_exp in range(2, 15, 2): 
                    buff_size = 2**buff_size_exp
                    decrypt_param = 'decrypt{} "{} {}"'.format(strat, buff_size, c_filepath)
                    all_decrypts.append(decrypt_param)
            else: 
                decrypt_param = "decrypt{} {}".format(strat, c_filepath)
                all_decrypts.append(decrypt_param)
    return all_decrypts

def all_out():
    all_out = []
    for i, decrypt in enumerate(all_decrypts()): 
        print("Running {}".format(decrypt), i)
        cmd = "stack exec -- denigma-exe {} +RTS -N6 -t --machine-readable -l -ol{}.eventlog".format(decrypt, i)
        out = subprocess.run(cmd, capture_output=True, text=True, shell=True) 
        d = parse_rts_output(out.stderr)
        d["decrypt"] = decrypt
        d["id"] = i
        all_out.append(d)
    return all_out

if __name__ == "__main__": 
    all_out = all_out()
    with open("decrypt_data.csv", 'w', newline='') as csvfile:
        fieldnames = [k for k in all_out[0]]
        writer = csv.DictWriter(csvfile, fieldnames=fieldnames)
        writer.writeheader()
        for data in all_out: 
            writer.writerow(data)
