#!/usr/bin/env python3
"""Compare test*.png against up to three ImageMagick reference directories.

Requires ImageMagick's `compare` command.  A comparison passes when the
unnormalized MAE is strictly less than THRESHOLD, matching the Bash script.
"""

import glob
import re
import shutil
import subprocess
import sys
from pathlib import Path

THRESHOLD = 20.0
REFERENCES = [
    Path('/home/jbf/ct/hudson/artifacts'),
    Path('/home/jbf/ct/hudson/artifacts2'),
    Path('/home/jbf/ct/hudson/artifacts3'),
]


def compare_images(actual, reference, difference):
    """Return the unnormalized ImageMagick MAE; write a difference PNG.

    ImageMagick compare returns 1 when images differ, which is not an error.
    """
    cmd = ['compare', '-metric', 'MAE', '-dissimilarity-threshold', '1',
           str(actual), str(reference), str(difference)]
    result = subprocess.run(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE,
                            universal_newlines=True)
    output = (result.stderr + '\n' + result.stdout).strip()
    if result.returncode not in (0, 1):
        raise RuntimeError('ImageMagick compare failed (exit {}): {}'.format(
            result.returncode, output))
    # Typical output: "3783.28 (0.057728)".  Only the first number is used.
    match = re.match(r'^\s*([0-9]+(?:\.[0-9]*)?(?:[eE][+-]?[0-9]+)?)', output)
    if not match or not difference.is_file():
        raise RuntimeError('Unexpected ImageMagick output: {}'.format(output))
    return float(match.group(1))


def main():
    if shutil.which('compare') is None:
        print('ERROR: ImageMagick compare command not found', file=sys.stderr)
        return 2

    for old in glob.glob('diffs.*.png'):
        Path(old).unlink()

    files = sorted(Path('.').glob('test*.png'))
    print('## compareImagesLoose Python version (3 reference directories)')
    if not files:
        print('No files found matching: test*.png')
        return 0

    failures = []
    matches = [0, 0, 0]
    for actual in files:
        print('== {} =='.format(actual.name))
        primary = REFERENCES[0] / actual.name
        if not primary.is_file():
            try:
                primary.parent.mkdir(parents=True, exist_ok=True)
                shutil.copy2(str(actual), str(primary))
            except OSError as exc:
                print('ERROR: cannot create reference {}: {}'.format(primary, exc))
                return 2
            print('****** No primary reference; copied {} to {}'.format(actual, primary))
            failures.append(actual.name)  # Preserve the original new-reference failure.
            continue

        best = None
        matched = False
        for index, directory in enumerate(REFERENCES, 1):
            reference = directory / actual.name
            if not reference.is_file():
                continue
            diff = Path('diffs.{}.{}'.format(index, actual.name))
            try:
                mae = compare_images(actual, reference, diff)
            except RuntimeError as exc:
                print('ERROR: {}: {}'.format(reference, exc), file=sys.stderr)
                return 2
            print('  reference {}: MAE={:.6g} ({})'.format(index, mae, reference))
            if best is None or mae < best[0]:
                best = (mae, diff, index)
            if mae < THRESHOLD:
                print('  --> Matches reference {}'.format(index))
                matches[index - 1] += 1
                matched = True
                break

        # Discard temporary differences for every passing image.
        if matched:
            for diff in glob.glob('diffs.*.{}'.format(actual.name)):
                Path(diff).unlink()
            continue

        failures.append(actual.name)
        if best is None:
            print('  ****** No reference images found')
            continue
        # Keep only the difference against the closest reference, with the
        # original Jenkins-friendly diffs.<testname> naming convention.
        output_diff = Path('diffs.{}'.format(actual.name))
        best[1].replace(output_diff)
        for diff in glob.glob('diffs.*.{}'.format(actual.name)):
            Path(diff).unlink()
        print('  ****** No match (threshold < {}); closest: reference {} '
              '(MAE={:.6g}); leaving {}'.format(
                  THRESHOLD, best[2], best[0], output_diff))

    print('*** Summary ***')
    print('Reference matches: artifacts={}, artifacts2={}, artifacts3={}'.format(*matches))
    if failures:
        print('Differences found in {} image(s): {}'.format(
            len(failures), ', '.join(failures)))
        return 1
    print('--> matches')
    return 0


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