#!/usr/bin/env python3

import argparse
import json
import os
import csv


def parse_args():
    parser = argparse.ArgumentParser(
        description="Analyse the instances"
    )
    parser.add_argument(
        "input_file",
        help="Path to the json file containing the data of all experiments",
        default="./data.json",
    )
    parser.add_argument(
        "output_file",
        help="name of the file where to save the results",
        default="instances_analysis.csv",
    )
    args = parser.parse_args()
    return args


if __name__ == "__main__":
    args = parse_args()
    with open(args.input_file, "r") as file:
        data = json.load(file)
    output = []
    for s in data.keys():
        number_of_item_types = 0
        average_quantity = 0
        average_total_quantity = 0
        for instance in data[s]:
            number_of_item_types += len(instance["small_items"])
            average_quantity += sum([item["quantity"] for item in instance["small_items"]]) / len(instance["small_items"])
            average_total_quantity += sum([item["quantity"] for item in instance["small_items"]])
        output.append([
            int(s[4:]),
            len(data[s]),
            int(number_of_item_types / len(data[s])),
            f"{average_quantity / len(data[s]):.1f}",
            f"{average_total_quantity / len(data[s]):.0f}",
        ])

    with open(args.output_file, "w") as file:
        csv = csv.writer(file, delimiter=',', quotechar='"', quoting=csv.QUOTE_NONE)
        csv.writerow(["set", "number of instances", "number of item types", "average quantity of each item", "average quantity of items"])
        csv.writerows(output)
