import argparse
import os
import xlsxwriter

def dump_stats(path):
    """
    Reads data from text files for different oracles, processes the data, and writes it to an Excel file.

    The function performs the following steps:
    1. Defines the path and creates an Excel file using xlsxwriter.
    2. Iterates over a list of oracles and reads corresponding text files.
    3. Sorts and processes the lines from each text file using the drivers' names.
    4. Writes the processed data into separate worksheets in the Excel file.

    The text files are expected to contain lines with six space-separated values:
    - Driver: The name of the driver, which includes additional information separated by '--' and a file extension.
    - Checks: an integer value for the overall number of havoc checks
    - TP, TN, FP, FN: integer values for the classification of havoc checks

    The Excel file will have the following columns:
    - Driver: The base name of the driver (extracted from the original driver name).
    - Checks: an integer value for the overall number of checks
    - TP, TN, FP, FN: integer values for the classification of havoc checks
    """

    excel_file = os.path.join(path, path + ".xlsx")
    workbook = xlsxwriter.Workbook(excel_file)

    for oracle in ["pos-nonrel", "def-nonrel", "pos-rel", "def-rel"]:
        oracle_file = os.path.join(path, oracle + ".txt")

        with open(oracle_file, "r") as f:
            lines = f.readlines()

        lines.sort()
        lines = [line.strip() for line in lines]
        lines = [line for line in lines if line != ""]

        worksheet = workbook.add_worksheet(oracle)

        worksheet.write(0, 0, "Driver")
        worksheet.write(0, 1, "Checks")
        worksheet.write(0, 2, "TP")
        worksheet.write(0, 3, "TN")
        worksheet.write(0, 4, "FP")
        worksheet.write(0, 5, "FN")

        for i, line in enumerate(lines):
            driver, checks, tp, tn, fp, fn = line.split()
            # Keep only the driver name after the first -- but before the first .
            base_name = driver.split("--")[1:]
            # Join basename by inserting a -
            base_name = "-".join(base_name)
            # Remove the extension
            base_name = base_name.split(".")[0]
            worksheet.write(i + 1, 0, base_name)
            worksheet.write(i + 1, 1, int(checks))
            worksheet.write(i + 1, 2, int(tp))
            worksheet.write(i + 1, 3, int(tn))
            worksheet.write(i + 1, 4, int(fp))
            worksheet.write(i + 1, 5, int(fn))

    workbook.close()

if __name__ == "__main__":
    argparser = argparse.ArgumentParser()
    argparser.add_argument("--path", help="Path to the directory containing the text files.", required=True)
    args = argparser.parse_args()
    dump_stats(args.path)