import csv
from argon2 import PasswordHasher

hasher = PasswordHasher()


def generate(username, password, roles=None):
    if username is None or not len(username):
        raise AssertionError("Username cannot be empty")

    if password is None or not len(password):
        raise AssertionError("Password cannot be empty")

    if any(map(lambda x: x == "\u2022", password)):
        raise AssertionError("Password cannot contain the forbidden character: \u2022")

    # Create a hash for the password
    password_hash = hasher.hash(password)

    return password_hash


def convert_data(input_csv, output_csv):
    try:
        with open(input_csv, 'r') as csv_file, open(output_csv, 'w', newline='') as output_file:
            csv_reader = csv.reader(csv_file)
            csv_writer = csv.writer(output_file)

            # Write the header to the output file
            header = next(csv_reader)
            csv_writer.writerow(header)

            for row in csv_reader:
                user_id = row[0]
                username = row[1]
                password = row[2]

                hashed_password = generate(username, password)
                roles = "[]"
                empty_string = "\"\""

                csv_writer.writerow([user_id, username, hashed_password, roles, empty_string])

        print(f"{output_csv} created successfully.")
    except Exception as ex:
        print(f"An error occurred: {ex}")


convert_data('config/csv_import/utenti.csv', 'config/csv_import/updated_users.csv')
