"""
Construct CSV-formatted file, named growth_factors.csv, that is suitable
for use by MYI-Tax-Analyzer, from the growth assumptions contained in the
grow.csv file.

USAGE: execute this script in the MYI-Tax-Analyzer/data directory as follows:
$ python grow.py
"""

import os
import pandas as pd
import taf  # Tax Analyzer Framework


START_YEAR = 2018
END_YEAR = 2025
GROW_CSV_FILEPATH = os.path.join('.', 'grow.csv')
GROWTHFACTORS_JSON_FILEPATH = os.path.join('..', 'myitaxanalyzer',
                                           'growth_factors.json')
USE_BASIC = {
    'PRICES': 'Pgf',
    'WAGES': 'Ygf',
    'WEIGHTS': 'Lgf'
}
GROWTHFACTORS_CSV_FILEPATH = os.path.join('..', 'myitaxanalyzer',
                                          'growth_factors.csv')


def main():
    """
    High-level logic of the script.
    """
    print('data/grow.py executing ...')

    # read GROW_CSV file into a data frame containing decimal rates
    gdf = pd.read_csv(GROW_CSV_FILEPATH)
    # check that years in gdf are as expected
    gdf_years = gdf.year.to_list()
    exp_years = list(range(START_YEAR, END_YEAR+1))
    assert gdf_years == exp_years

    # construct basic growth factors from gdf grow rates
    bgf = pd.DataFrame()
    bgf['Lgf'] = 1.0 + gdf.Lgrate  # labor force employed (workers)
    bgf['Qgf'] = 1.0 + gdf.Qgrate  # real GDP per worker
    bgf['Pgf'] = 1.0 + gdf.Pgrate  # GDP price deflator
    bgf['Ygf'] = bgf.Qgf * bgf.Pgf  # nominal GDP per worker

    # read GROWTHFACTORS_JSON file into a dictionary
    gfdict = taf.json2dict(GROWTHFACTORS_JSON_FILEPATH)

    # construct GROWTHFACTORS data frame
    gfdf = pd.DataFrame()
    gfdf['YEAR'] = gdf_years
    for gfname in gfdict:
        gfdf[gfname] = bgf[USE_BASIC[gfname]]
        if gfname not in ('PRICES', 'WAGES'):
            gfdf[gfname].at[0] = 1.0  # START_YEAR value must be one

    # write GROWTHFACTORS_CSV file
    taf.df2csv(gfdf, GROWTHFACTORS_CSV_FILEPATH, float_format='%.6f')

    return 0


if __name__ == '__main__':
    main()
