import json
import logging
import traceback


def run_sarif_merge(sarif_file1, sarif_file2, output_filename, sarif_version='sarifv2.1.0'):
    """This function merges two SARIF files into a single set of results.

    Inputs:
        - sarif_file1: Relative path to the first .sarif file to merge [string]
        - sarif_file2: Relative path to the second .sarif file to merge [string]
        - output_filename: Relative path to the merged .sarif output file [string]
        - sarif_version: Version to use for merged .sarif file, defaults to latest [string]

    Outputs:
        - exit_code: Exit code that represents whether the module completed with errors [int]
                       1 - reports any kind of failure with the merge (i.e. read/write, and schema mismatch)
                       2 - reports any unexpected errors that are not caught by exception handling
    """

    # Initialize variables
    custom_exit_code = 2

    try:
        with open(sarif_file1, 'r') as sarif_one, open(sarif_file2, 'r') as sarif_two:
            sarif_data1 = json.loads(sarif_one.read())
            sarif_data2 = json.loads(sarif_two.read())

        if sarif_data1 and sarif_data2:
            sarif_version = sarif_version.strip('sarifv')

            if (sarif_data1['version'] != sarif_version) or (sarif_data2['version'] != sarif_version):
                logging.warning('SARIF versions mismatched, converting files to: ' + sarif_version)

            merged_sarif = {
                '$schema': sarif_data1['$schema'],
                'version': sarif_version,
                'runs': [
                    sarif_data1['runs'][0],
                    sarif_data2['runs'][0]
                ]
            }

            with open(output_filename, 'w') as sarif_output:
                sarif_output.write(json.dumps(merged_sarif))

            # Update the exit code
            custom_exit_code = 0

    except:     # lgtm [py/catch-base-exception]
        logging.warning('Failed to merge these SARIF results, check traceback error for more details.')
        logging.warning(traceback.format_exc())
        custom_exit_code = 1

    finally:
        return custom_exit_code