import os
import pandas as pd
import PySAM.Pvwattsv8 as pv
import PySAM.Grid as gr
import PySAM.Utilityrate5 as ur
import PySAM.Cashloan as co
import numpy as np

# Load the base load profile
base_load_profile_filename = "BaseCaseElectricity.csv"
base_load_profile = pd.read_csv(base_load_profile_filename).values.flatten()

daily_load_kWh = base_load_profile.sum() / 365

# Initialize PySAM models
system_model = pv.default("PVWattsCommercial")
grid_model = gr.from_existing(system_model, "PVWattsCommercial")
utilityrate_model = ur.from_existing(system_model, "PVWattsCommercial")
financial_model = co.from_existing(system_model, "PVWattsCommercial")

# Load weather file
weather_file = "ottawa_45.4218_-75.6912_psm3-2-2_60_2006.csv"
system_model.SolarResource.solar_resource_file = weather_file

# Set Nameplate Capacity, this gives 446 kWdc
efficiency = 0.96  # Inverter efficiency
PSH = 3.76  # Peak Sun Hours
dc_ac = 1.15  # DC to AC ratio
nameplate_capacity = dc_ac * (daily_load_kWh / (PSH * efficiency))
print('Pvwattsv8 input system_capacity = ', nameplate_capacity)
system_model.SystemDesign.system_capacity = nameplate_capacity

# Set total installed cost based on $1.76/Wdc
financial_model.SystemCosts.total_installed_cost = nameplate_capacity * 1000 * 1.76

# Set load data
utilityrate_model.Load.load = base_load_profile

# Run the PySAM models
system_model.execute()
grid_model.execute()
utilityrate_model.execute()
financial_model.execute()

print('Pvwattsv8 ac_annual =', system_model.Outputs.ac_annual)
print('Utilityrate5 year1_electric_load =', utilityrate_model.Outputs.year1_electric_load)
print('Grid annual_energy =', grid_model.SystemOutput.annual_energy)
print('Cashloan npv =', financial_model.Outputs.npv)

print()

print('Utilityrate5 annual_energy_value =', utilityrate_model.Outputs.annual_energy_value[:4])

print('Cashloan cf_after_tax_net_equity_cost_flow =', financial_model.Outputs.cf_after_tax_net_equity_cost_flow[:4])
print('Cashloan cf_after_tax_cash_flow = ', financial_model.Outputs.cf_after_tax_cash_flow[:4])

print('Cashloan cf_operating_expenses =', financial_model.Outputs.cf_operating_expenses[:4])

print('Cashloan cf_sta_tax_savings =', financial_model.Outputs.cf_sta_tax_savings[:4])
print('Cashloan cf_fed_tax_savings =', financial_model.Outputs.cf_fed_tax_savings[:4])

print('Cashloan cf_debt_payment_interest =', financial_model.Outputs.cf_debt_payment_interest[:4])

print('Cashloan total_cost =', financial_model.Outputs.total_cost)