#!/usr/bin/env python3

import json
import surfex
import argparse
import sys
import os
from jsonmerge import merge


def parse():
    """Parse the command line input arguments."""
    parser = argparse.ArgumentParser("Merge a list of JSON files to one JSON file")

    parser.add_argument('--version', action='version', version='surfex {0}'.format(surfex.__version__))
    parser.add_argument('--json', '-j', type=str, nargs="+", required=True, help="A JSON file with run options")
    parser.add_argument('--indent', required=False, default=2, type=int, help="Indented output")
    parser.add_argument('--output', '-o', required=True, nargs='?')

    if len(sys.argv) == 1:
        parser.print_help()
        sys.exit()

    args = parser.parse_args()

    return args.json, args.output, args.indent


if __name__ == "__main__":

    my_files, my_output, my_indent = parse()
    files = []
    for f in my_files:

        if os.path.exists(f):
            files.append(f)
        else:
            raise FileNotFoundError

    json_settings = None
    for f in files:
        if json_settings is None:
            json_settings = json.load(open(f, "r"))
        else:
            json_settings = merge(json_settings, json.load(open(f, "r")))
        print("merging json_setings: ", json_settings)
    json.dump(json_settings, open(my_output, "w"), indent=my_indent)
