#!/usr/bin/python3

from shutil import rmtree, copy
from os import mkdir, chdir, listdir, remove, rename
from os.path import isdir
from stuff import compile_cpp

from sys import exit

import subprocess

MODEL_SOLUTION_SRC = 'turtles_ma_qlogn.cpp'

if not isdir('./bin'):
    mkdir('bin')

chdir('bin')

for f in filter(lambda x : len(x) == 2, sorted(listdir())):
    remove(f)

compile_cpp('../' + MODEL_SOLUTION_SRC, './sol')
compile_cpp('../validate.cpp', './validate')

chdir('../src')
print("Generating and validating tests...")
from src.gen import generate_tests
generate_tests()

chdir('../bin')

print("Validating")
for f in filter(lambda x : len(x) == 2, sorted(listdir('../tests/'))):
    print("Validating", f)
    code = subprocess.call(['./validate'], stdin=open('../tests/' + f, 'r'))
    if code != 0:
        print("Error while validating", f)


print("Generating answers")
for f in filter(lambda x : len(x) == 2, sorted(listdir('../tests/'))):
    print("Generating answer for", f)
    copy('../tests/' + f, 'turtles.in')
    code = subprocess.call(['./sol'], stdin=open('turtles.in', 'r'))
    if code != 0:
        print("Error while generating answer for", f)
        exit(1)
    copy('turtles.out', '../tests/' + f + '.a')

    

remove('turtles.in')
remove('turtles.out')
