import os
import subprocess
import pytest

chemshell_env_var = "CHEMSHELL_TCL"


def test_env():
    envvar = os.environ.get(chemshell_env_var)
    assert envvar != None


filedir = os.path.dirname(os.path.realpath(__file__))
files = [f for f in os.listdir(filedir) if f.endswith(".chm")]


def test_file(fname):
    envvar = os.environ.get(chemshell_env_var)
    process = subprocess.run([envvar + "/scripts/chemsh", fname], stdout=subprocess.PIPE )
    out = str(process.stdout).split("\\n")
    result = None
    for l in out:
        if "RESULT_HOOK" in l:
            result = float(l.split(":")[-1])
    if result == None:
        raise ValueError("NO OUTOUT FOUND")

    return result

with open("tcl_results.dat", "w") as outf:
    for f in files:
        try:
            v = test_file(f)
            outf.write(f"{f}: {v}\n")
        except:
            outf.write(f"{f} did not work\n")
