#!python

import os
import yaml
import sys
import re
import subprocess

from olypy.oid import to_int


def run_one_test(name, y):
    if y.get('lib', '') != 'qa-default-lib':
        raise ValueError('Sorry, qa-default-lib is the only supported lib atm.')

    subprocess.run('rm -rf lib'.split(), check=True)
    subprocess.run('tar xf {}.tar.gz'.format(y['lib']).split(), check=True)

    pass_counts = {}
    for k in y:
        if k.endswith(' orders'):
            f, _ = k.split(' ', maxsplit=1)
            with open('lib/spool/m.'+f, 'w') as fd:
                fd.write('From l@p.c\n\nbegin {} "{}"\n\n'.format(f, 'xxxxxxxx'))
                fd.write(y[k])
            pass_counts[f] = len(re.findall(r'^\s*assert\s+', y[k], flags=re.M))

    if not os.path.isfile('./oly'):
       raise ValueError('executable file ./oly does not exist')

    subprocess.run('./oly -e'.split(), check=True)
    subprocess.run('./oly -rMS'.split(), check=True)

    expected_pass_count = 0
    actual_pass_count = 0
    for f in pass_counts:
        expected_pass_count += pass_counts[f]
        fname = 'lib/save/2/' + to_int(f)
        if not os.path.exists(fname):
            raise ValueError('expected {} to exist'.format(fname))
        with open(fname, 'r') as fd:
            for line in fd:
                if line.endswith('PASS\n'):
                    actual_pass_count += 1

    print('{}: {}/{} '.format(name, actual_pass_count, expected_pass_count), end='')

    if actual_pass_count == expected_pass_count:
        print('PASS')
    else:
        print('FAIL')

if len(sys.argv) > 1:
    for name in sys.argv[1:]:
        with open(name, 'r') as f:
            run_one_test(name, yaml.safe_load(f))
    sys.exit(0)

tests = os.listdir('test-inputs')
for t in tests:
    if not t.endswith('.yml'):
        continue
    with open('test-inputs/' + t, 'r') as f:
        run_one_test(t, yaml.safe_load(f))
