#!/usr/bin/env python3
import os
import subprocess
import sys

MAX_FAILED = 1
START_TEST = 0

TEMPFILE = subprocess.run("mktemp -u".split(), stdout=subprocess.PIPE).stdout.decode().strip() # use linux :)
FILL_SIZE = os.get_terminal_size().columns
filled = lambda x: f"{x}{' ' * (FILL_SIZE - len(x.replace('\r', '').replace('\n', '')))}"

with open("tests.csv") as f:
    tests = [[y for y in x.split(',')] for x in f.read().strip().split('\n')[1:]][START_TEST:]

print('Compiling...', end='')
ps = subprocess.run(f'iverilog -g2012 -o {TEMPFILE} ./sqrt2_tb.sv'.split(), stderr=subprocess.PIPE)
exit_code = ps.returncode
output = ps.stderr.decode().strip()

if exit_code != 0:
    print('\r!COMPILATION FAILED!')
    print(output, file=sys.stderr)
    exit(exit_code)
elif output:
    print("\rCompiled with warnings")
    print(output)
else:
    print("\rCompiled successfully")

good = bad = 0
for i, test in enumerate(tests):
    try:
        ps = subprocess.run([TEMPFILE, '+' + test[0]], stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, timeout=.1)
    except subprocess.TimeoutExpired:
        out = 'TIMEOUT'
    else:
        out = ps.stdout.decode().strip().split('\n')[0]

    cmp = ' '.join(test[1:])
    if out != cmp:
        bad += 1
        print('\n'.join((
            filled(f'\rTEST #{i + 1 + START_TEST}' + (' (TIMEOUT)' if out == 'TIMEOUT' else '')),
            filled(f'INPUT:     {test[0]}'),
            filled(f'OUTPUT:    {out}'),
            filled(f'EXPECTED:  {cmp}'),
        )), end='\n\n')
    else:
        good += 1

    print(filled(f'\rGOOD: {good}, BAD: {bad}, TOTAL: {len(tests)}'), end='')

    if MAX_FAILED and bad >= MAX_FAILED:
        print("\nToo many failed tests. Aborting.")
        exit(1)
print()
