#!/bin/python3

"""
Appends the primary key of a CSV table to make it unique.
Usage:
    increment_duplicates INPUT [OUTPUT]

    INPUT: input file in csv format
    OUTPUT: (optional) output file name [default: INPUT]
"""

import sys
import csv

# parse script arguments
if len(sys.argv) > 1:
    old_csv = sys.argv[1]
    new_csv = old_csv
    if len(sys.argv) > 2:
        new_csv = sys.argv [2]
else:
    print("Error: no input file")
    sys.exit(1)

# read input csv
rows = []
unique = []
dup_max = 1
with open(old_csv) as csv_file:
    reader = csv.reader(csv_file, delimiter=';', quotechar='"')
    index = 0
    for line in reader:
        rows.append(line)
        for i in range(1, len(unique)+2):
            code = line[0] + str(i)
            if code not in unique:
                unique.append(code)
                break
            dup_max = max(dup_max, i)
        line[0] = unique[index]
        index += 1

with open(new_csv, 'w', newline='\n') as csv_file:
    writer = csv.writer(csv_file, delimiter=';', quotechar='"',
                        quoting=csv.QUOTE_MINIMAL)
    for line in rows:
        writer.writerow(line)

print("Maximum number of duplicates: ", dup_max)

