import os
import sys
import subprocess

#envarray = {}

# grab current environment
lenv = os.environ.copy()

#for ev, val in envarray.iteritems():
#    lenv[ev.upper()] = val


# <<<  inspect psi_scratch  >>>

psans = os.getenv('PSI_SCRATCH', None)
if psans is not None and os.access(psans, os.W_OK | os.X_OK):
    # all good, can use user's env
    pass
else:
    #envarray['PSI_SCRATCH'] = '/tmp'
    lenv['PSI_SCRATCH'] = '/tmp'


# <<<  force path  >>>
#lenv['PATH'] = """{}/bin:{}""".format(os.environ['PREFIX'], os.environ['PATH'])
path2psi4 = """{}/bin/psi4""".format(os.environ['PREFIX'])
print(path2psi4)

# <<<  test input  >>>

with open('setenvtest.in', 'w') as handle:
    handle.write("""
memory 250 mb

molecule h2o {
  O
  H 1 0.96
  H 1 0.96 2 104.5
}

set basis cc-pVDZ
energy('scf')

compare_values(-76.0266327341067125, get_variable('SCF TOTAL ENERGY'), 6, 'SCF energy')  # right answer
#compare_values(-77.0266327341067125, get_variable('SCF TOTAL ENERGY'), 6, 'SCF energy')  # wrong answer
""")


# <<<  test the environment  >>>
#lenv = os.environ.copy()
#for ev, val in envarray.iteritems():
#    lenv[ev.upper()] = val
#p4ans = subprocess.Popen('psi4 setenvtest.in', shell=True, stdout=subprocess.PIPE, env=lenv).stdout.read()
#sp = subprocess.Popen('/theoryfs2/ds/cdsgroup/psi4-install/miniconda/envs/p4env3/bin/psi4 setenvtest.in', shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE, env=lenv)
#print(lenv['PATH'])
#print(lenv['PSI_SCRATCH'])

#sp = subprocess.Popen("""{}/bin/psi4 setenvtest.in""".format(os.environ['PREFIX']), shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE, env=lenv)
sp = subprocess.Popen("""{} setenvtest.in""".format(path2psi4), shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE, env=lenv)
out, err = sp.communicate()
if out:
    #print("standard output of subprocess:")
    print(out)
if err:
    #print("standard error of subprocess:")
    print(err)
#print("returncode of subprocess:")
#print(sp.returncode)
#print(type(p4ans))
#print(p4ans)
#print(type(p4ans))
#print(p4ans)

#print("""  For command-line use, add to shell or rc file (~/.bashrc or ~/.tcshrc ):\n""")
#
#print("""    bash>>> export PATH={}/bin:$PATH""".format(os.environ['PREFIX']))
#if psans is None:
#    print("""    bash>>> export PSI_SCRATCH=/path/to/existing/writable/local-not-network-disk/for/scratch/files""")
#print('')
#print("""    csh>>> setenv PATH {}/bin:$PATH""".format(os.environ['PREFIX']))
#if psans is None:
#    print("""    csh>>> setenv PSI_SCRATCH /path/to/existing/writable/local-not-network-disk/for/scratch/files""")
#print('')

sys.exit(sp.returncode)
