import csv
import json

file="STTEN5"
with open(f"tmp/{file}.csv",) as csv_file:
    csv_reader = csv.reader(csv_file, delimiter=',')

    with open(f'tmp/{file}_out.csv', 'w') as csv_out:

        # create the csv writer
        writer = csv.writer(csv_out, lineterminator="\n")

        line_count = 0
        for row in csv_reader:
            if line_count == 0:
                print(f'Column names are {", ".join(row)}')
                row.append("caduta")
                row.append("pressione")
                row.pop(1)  # remove data column
                line_count += 1
                writer.writerow(row)
            else:
                data=json.loads(row[1])
                if "leak_1" in data.keys():
                    leak=data["leak_1"]["0"]["results"]["data"]["""Running test: measured leak"""]
                    press=data["leak_1"]["0"]["results"]["data"]["""Running test: filling pressure"""]
                    leakstr=f'{leak:.3f}'
                    pressstr = f'{press:.3f}'
                    line_count += 1
                    row.append(leakstr)
                    row.append(pressstr)
                    row.pop(1) # remove data column
                    writer.writerow(row)

        print(f'Processed {line_count} lines.')