# -------------------------------------------------------------------------
#
#  Part of the CodeChecker project, under the Apache License v2.0 with
#  LLVM Exceptions. See LICENSE for license information.
#  SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
#
# -------------------------------------------------------------------------

import argparse
import json
import sys

def __sorted_results(result_file):
    results = json.load(result_file)
    results.sort(
        key=lambda report: report['bugHash'] + str(report['reportId']))
    return results

def __print_missing(needles, haystack, haystack_name):
    for needle in needles:
        if needle not in haystack:
            print(f"Report not found in {haystack_name}:")
            print(json.dumps(needle, indent=4))
            return True
    return False

def main():
    parser = argparse.ArgumentParser(
        description="Compares two CodeChecker results. The results should be "
                    "generated by 'CodeChecker cmd results' command.")

    parser.add_argument(
        "result1",
        type=argparse.FileType("r"),
        help="Path of the first result.")

    parser.add_argument(
        "result2",
        type=argparse.FileType("r"),
        help="Path of the second result.")

    args = parser.parse_args()

    result1 = __sorted_results(args.result1)
    result2 = __sorted_results(args.result2)

    found_missing = False
    found_missing |= __print_missing(result1, result2, "result2")
    found_missing |= __print_missing(result2, result1, "result1")

    args.result1.close()
    args.result2.close()

    return 1 if found_missing else 0

if __name__ == '__main__':
    sys.exit(main())
