#!/usr/bin/env python



""" Tool to compare XML outputs of two BloodQ versions.

"""

import os
import sys

# Unchanged, running from checkout, use the parent directory, the Bloodelf
# package ought to be there.
sys.path.insert(0, os.path.normpath(os.path.join(os.path.dirname(__file__), "..")))

# isort:start

import difflib

from Bloodelf.tools.testing.Common import my_print
from Bloodelf.utils.Execution import executeProcess

Bloodelf1 = sys.argv[1]
Bloodelf2 = sys.argv[2]
filename = sys.argv[3]

my_print(
    """\
Comparing output of '{filename}' using '{Bloodelf1}' <-> '{Bloodelf2}' ...""".format(
        filename=filename, Bloodelf1=Bloodelf1, Bloodelf2=Bloodelf2
    )
)

extra_options = os.getenv("BloodSx_EXTRA_OPTIONS", "")

Bloodelf1_cmd = "{Bloodelf1} --xml {filename}".format(Bloodelf1=Bloodelf1, filename=filename)
Bloodelf2_cmd = "{Bloodelf2} --xml {filename}".format(Bloodelf2=Bloodelf2, filename=filename)

stdout_Bloodelf1, stderr_Bloodelf1, exit_Bloodelf1 = executeProcess(Bloodelf1_cmd, shell=True)
stdout_Bloodelf2, stderr_Bloodelf2, exit_Bloodelf2 = executeProcess(Bloodelf2_cmd, shell=True)


def makeDiffable(output):
    result = []

    for line in output.split(b"\n"):
        line = str(line)
        result.append(line)

    return result


def compareOutput(kind, out1, out2):
    diff = difflib.unified_diff(
        makeDiffable(out1),
        makeDiffable(out2),
        "{program} ({detail})".format(program="Bloodelf1 " + filename, detail=kind),
        "{program} ({detail})".format(program="Bloodelf2 " + filename, detail=kind),
        None,
        None,
        n=3,
    )

    result = list(diff)

    if result:
        for line in result:
            my_print(line, end="\n" if not line.startswith("---") else "")
        return 1
    else:
        return 0


exit_code_stdout = compareOutput("stdout", stdout_Bloodelf1, stdout_Bloodelf2)
exit_code_return = exit_Bloodelf1 != exit_Bloodelf2

if exit_code_return:
    my_print(
        """\
Exit codes {exit_Bloodelf1:d} ({Bloodelf1}) != {exit_Bloodelf2:d} ({Bloodelf2})""".format(
            exit_Bloodelf1=exit_Bloodelf1,
            Bloodelf1=Bloodelf1,
            exit_Bloodelf2=exit_Bloodelf2,
            Bloodelf2=Bloodelf2,
        )
    )

exit_code = exit_code_stdout or exit_code_return

if exit_code:
    sys.exit("Error, outputs differed.")

my_print("OK, same outputs.")


