#!/usr/bin/env python3

import os.path
import tempfile
import subprocess
from glob import glob


if __name__ == '__main__':
    json_tests = "@CMAKE_CURRENT_SOURCE_DIR@/test/json/pointer/validate/"
    json_pointer = "@CMAKE_CURRENT_BINARY_DIR@/json-pointer"
    json_compare = "@CMAKE_CURRENT_BINARY_DIR@/json-compare"

    paths = glob(os.path.join(json_tests, "*.pointer"))
    paths = (os.path.splitext(p)[0] for p in paths)
    names = sorted(p for p in paths)

    failures = 0

    for n in names:
        input = f"{n}.input.json"
        truth = f"{n}.truth.json"
        with open(f"{n}.pointer") as f: pointer = f.read()

        success = False

        try:
            with tempfile.NamedTemporaryFile(delete=True) as result:
                do_query = [json_pointer, pointer.rstrip(), input]
                do_compare = [json_compare, result.name, truth]

                #print(do_query)
                #print(do_compare)

                subprocess.check_call(do_query, stdout=result)
                subprocess.check_call(do_compare)
                success = True
        except subprocess.CalledProcessError:
            failures += 1

        prefix = "not " if not success else ""
        print(f"{prefix}ok - {n}")

    exit(1 if failures else 0)