#!/usr/bin/env python3
'''Convert a Valgrind Massif output file to a CSV file.'''
import argparse
import msparser

def massif_to_csv(massif_filename):
    '''Convert a Massif file to a CSV string.'''
    data = msparser.parse_file(massif_filename)

    header = 'time,stack,heap,heap_extra'
    lines = [header]

    for snapshot in data['snapshots']:
        time = snapshot['time']
        stack = snapshot['mem_stack']
        heap = snapshot['mem_heap']
        heap_extra = snapshot['mem_heap_extra']
        lines.append(f'{time},{stack},{heap},{heap_extra}')

    return '\n'.join(lines)

def massif_file_to_csv_file(massif_filename, csv_filename):
    '''Convert a Massif file to a CSV file.'''
    with open(csv_filename, 'w') as csv_file:
        csv_content = massif_to_csv(massif_filename) + '\n'
        csv_file.write(csv_content)

def main():
    """
    Program entry point.

    Parses the input arguments then calls massif_file_to_csv_file.
    """
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument('input_massif', type=str, help="The input file (generated by Valgrind's Massif tool)")
    parser.add_argument('output_csv', type=str, help='The output CSV file')
    args = parser.parse_args()

    massif_file_to_csv_file(args.input_massif, args.output_csv)

if __name__ == "__main__":
    main()
