#!/usr/bin/env python
import sys
import numpy as np
import pandas as pd
import json

# these were spot checked, unclear if there's a better way to directly
# obtain this mapping
var_prefixes = {
    'assembly': '*.', # scattered all over the place
    'ccblade': 'rotorse.',
    're': 'rotorse.',
    'rp': 'rotorse.',
    'rs': 'rotorse.',
    'stall_check': 'rotorse.',
    'wt_class': 'rotorse.',
}

# the variable guide in csv format is generated by get_omdao_vars.py
tab = pd.read_csv('variable_guide.csv')
if tab.iloc[-1]['Description'] == 'description':
    # throw out footer
    tab = tab.iloc[:-1]
tab = tab.set_index('Variable')
tab['Units'] = tab['Units'].replace(np.nan, '-')
tab['Description'] = tab['Description'].replace(np.nan,'None')

# convert to dict
varsdict = {}
for varn,info in tab.iterrows():
    curlev = varsdict
    varlevels = varn.split('.')
    toplevel = varlevels[0]
    for lev in varlevels[:-1]:
        if lev not in curlev:
            curlev[lev] = {}
        curlev = curlev[lev]
    curlev[varlevels[-1]] = info.to_dict() # Units, Description
    curlev[varlevels[-1]]['Name'] = var_prefixes.get(toplevel,'') + varn

# save
with open('variable_guide.json','w') as f:
    json.dump(varsdict, f, indent=2)
