#!/usr/bin/env python3

import csv
from collections import defaultdict

if __name__ == "__main__":
    # get all rows 
    rows = []
    with open("../data/decrypt_data.csv", newline='') as csvfile: 
        reader = csv.DictReader(csvfile)
        for row in reader: 
            rows.append(row)

    # group by decrypt params
    cols = [k for k in rows[0]][:-2]
    grouped_rows = defaultdict(list) 
    for row in rows: 
        grouped_rows[row["decrypt"]].append(row)

    # take averages per group
    avgs = []
    for decrypt, group in grouped_rows.items(): 
        avg = dict() 
        for c in cols: 
            s = sum(float(run[c]) for run in group)
            avg[c] = s/len(group)
        avg["decrypt"] = decrypt
        avgs.append(avg)

    # persist
    with open('../data/avgs.csv', 'w', newline='') as csvfile: 
        writer = csv.DictWriter(csvfile, fieldnames=[k for k in avgs[0]])
        writer.writeheader()
        for a in avgs: 
            writer.writerow(a) 
