import argparse
import csv
import json
import os


def main():
    parse = argparse.ArgumentParser()
    parse.add_argument("file_path", type=str, default=None, help="File Path")
    args = parse.parse_args()

    anlage = None
    data_file = None

    full_path = os.path.expanduser(os.path.expandvars(args.file_path))
    # print(os.path.dirname(full_path))
    if not os.path.isfile(full_path):
        raise FileNotFoundError(f"Failed to locate {full_path}")

    # read content
    try:
        with open(full_path, mode='r', encoding="utf-8-sig") as f:
            data = list(csv.DictReader(f, delimiter=';'))
    except Exception as error:
        raise Exception(f"Failed to read content from {full_path} (Error: {error})")

    for row in data:
        if anlage is None or anlage != row.get("Anlage"):
            data_file = full_path.replace(".csv", f"_{row.get('Anlage')}.json")
            open(data_file, 'w').close()
            anlage = row.get("Anlage")
        with open(data_file, 'a',  encoding="utf-8-sig") as f:
            f.write(f"{json.dumps(row, ensure_ascii=False)},\n")


if __name__ == "__main__":
    main()