# Preliminaries
import os
import sys
import atexit
import source.lib.JMSLab as jms

sys.path.append('config')
sys.path.append(os.path.dirname(os.path.abspath('SConstruct')))

from source.config import ROOT_PATH, DATASTORE_PATH

# Stata cannot import the Python config, so write it the globals it needs.
# Regenerated on every run, so one setting governs Python, Stata and the
# build graph alike.
(ROOT_PATH / 'source/config.do').write_text(
    '* Generated by SConstruct from source/config.py. Do not edit.\n'
    f'global ROOT "{ROOT_PATH}"\n'
    f'global DATASTORE "{DATASTORE_PATH}"\n')
sys.dont_write_bytecode = True # Don't write .pyc files

# Agg is a non-interactive matplotlib backend: figure scripts save their
# output and plt.show() becomes a no-op, so a build never stops to wait for
# a window to be closed. Running a script by hand still opens figures.
# It is set on this process, not on the SCons environment, because the
# builders call subprocess without passing env through.
os.environ['MPLBACKEND'] = 'Agg'

env = Environment(ENV = {'PATH' : os.environ['PATH']},
                  IMPLICIT_COMMAND_DEPENDENCIES = 0,
                  BUILDERS = {'R'         : Builder(action = jms.build_r),
                              'Tablefill' : Builder(action = jms.build_tables),
                              'Stata'     : Builder(action = jms.build_stata),
                              'Matlab'    : Builder(action = jms.build_matlab),
                              'Python'    : Builder(action = jms.build_python),
                              'Lyx'       : Builder(action = jms.build_lyx),
                              'Latex'     : Builder(action = jms.build_latex)})

env.Decider('MD5-timestamp') # Only computes hash if time-stamp changed
Export('env')

jms.start_log('develop', '')

# Raw downloads are opt-in.  They overwrite the archived raw vintage with
# whatever FRED serves today, and FRED revises its series, so a refresh will
# move the published numbers.  Default builds read the raw data as shipped.
if ARGUMENTS.get('refresh_raw', 0):
    SConscript('source/raw/fred/SConscript')
    SConscript('source/raw/wrds/SConscript')

SConscript('source/derived/empirics/SConscript')
SConscript('source/derived/calibration/SConscript')
SConscript('source/analysis/figures/main/SConscript')
SConscript('source/analysis/figures/appendix/SConscript')
SConscript('source/analysis/tables/main/SConscript')
SConscript('source/analysis/tables/appendix/SConscript')
SConscript('source/analysis/numbers/SConscript')
SConscript('source/paper/SConscript')
