import subprocess, os, shutil

# Use Twig to get students answer and the columnwidth template parameter
student_answer = """{{ STUDENT_ANSWER | e('py') }}""".rstrip()
column_widths = []
{% for width in QUESTION.parameters.columnwidths %}
column_widths.append({{width}})
{% endfor %}

if not student_answer.endswith(';'):
    student_answer = student_answer + ';'
db_files = [fname for fname in os.listdir() if fname.endswith('.db')]
if len(db_files) == 0:
    raise Exception("No DB files found!")
elif len(db_files) == 1:
    db_working = db_files[0][:-3]  # Strip .db extension
else:
    raise Exception("Multiple DB files not implemented yet, sorry!")

SEPARATOR = "#<ab@17943918#@>#"
controls = [".mode column", ".headers on"]
if column_widths: # Add column width specifiers if given
    controls.append(".width " + ' '.join(str(width) for width in column_widths))
prelude = '\n'.join(controls) + '\n'

{% for TEST in TESTCASES %}
shutil.copyfile(db_files[0], db_working)  # Copy clean writeable db file
testcode = """{{ TEST.testcode | e('py') }}"""
extra = """{{ TEST.extra | e('py') }}"""
code_to_run = '\n'.join([prelude, extra, student_answer, testcode])
with open('commands', 'w') as sqlite_commands:
    sqlite_commands.write(code_to_run)

with open('commands') as cmd_input:
    text_input = cmd_input.read()
    try:
        output = subprocess.check_output(['sqlite3', db_working], input=text_input,
                 universal_newlines=True)
        print(output)
    except Exception as e:
        raise Exception("sqlite3 error: " + str(e))

{% if not loop.last %}
print(SEPARATOR)
{% endif %}
{% endfor %}