import pandas as pd
import json

import PySAM.Pvwattsv8 as pv
import PySAM.Grid as gr
import PySAM.Utilityrate5 as ur
import PySAM.Singleowner as so

# leave this empty if weather file and 'case 1' folder are in same folder as this script
path = ''

# modules required for the PVWatts - Single Owner configuration
# see https://nrel-pysam.readthedocs.io/en/master/Configs.html
system_model = pv.new()
grid_model = gr.from_existing( system_model )
rate_model = ur.from_existing( system_model )
financial_model = so.from_existing(system_model )

# list of modules in the correct execution order
modules = [ system_model, grid_model, rate_model, financial_model ]

# list of JSON input files exported from SAM for Case 1
# see https://nrel-pysam.readthedocs.io/en/master/Import.html
input_files = ['Case_1_pvwattsv8.json', 'Case_1_grid.json', 'Case_1_utilityrate5.json','Case_1_singleowner.json']

# set the weather file
wf_path = path + '41.712_-72.358.csv'
system_model.SolarResource.solar_resource_file = wf_path

# loop through the JSON input files to set inputs for all modules
for f, m in zip(input_files, modules):
    with open( path + 'case 1/' + f, 'r') as file:
        data = json.load(file)
        for k, v in data.items():
            if k != "number_inputs":
                m.value(k, v)

# run the modules in the correct order
for m in modules:
    m.execute()

# display some results
print('Annual Energy =', system_model.Outputs.ac_annual, '| NPV =', financial_model.Outputs.project_return_aftertax_npv)
