import PySAM.Pvsamv1 as pvsamv1
import PySAM.Grid as grid
import PySAM.Utilityrate5 as utilityrate5
import PySAM.Cashloan as cashloan
import fetch_weather_data as fetcher


# Define key inputs

model_name = 'FlatPlatePVCommercial'

location = {
    'lat': 33.45,
    'lon': -111.98,  # Sedona, AZ
}

# Fetch the solar resource data
# resource_file = fetcher.fetch_weather_data(location['lat'], location['lon'])

# Use the same resource file as used by SAM desktop app
resource_file =  "/Applications/SAM_2023.12.17/SAM.app/Contents/solar_resource/phoenix_az_33.450495_-111.983688_psmv3_60_tmy.csv"

# initialize all models
pv_system = pvsamv1.default(model_name)
grid_model = grid.from_existing(pv_system, model_name)
utility_model = utilityrate5.from_existing(pv_system, model_name)
financial_model = cashloan.from_existing(pv_system, model_name)

# change simulation settings
pv_system.SolarResource.solar_resource_file = resource_file

# Run the PV simulation
pv_system.execute()
grid_model.execute()
utility_model.execute()
financial_model.execute()

print(f"Annual AC energy in Year 1: {pv_system.Outputs.annual_ac_gross:,.0f} kWh")
print(f"DC capacity factor in Year 1: {pv_system.Outputs.capacity_factor:.1f}%")
print(f"Energy yield in Year 1: {pv_system.Outputs.kwh_per_kw:,.0f} kWh/kW")
print(f"Performance ratio in Year 1: {pv_system.Outputs.performance_ratio:.2f}")
print(f"LCOE Levelized cost of energy nominal: {financial_model.Outputs.lcoe_nom:.2f} cent/kWh")
print(f"LCOE Levelized cost of energy real: {financial_model.Outputs.lcoe_real:.2f} cent/kWh")
print(f"Electricity bill without system (year 1): ${utility_model.Outputs.elec_cost_without_system_year1:,.0f}")
print(f"Electricity bill with system (year 1): ${utility_model.Outputs.elec_cost_with_system_year1:,.0f}")
print(f"Net savings with system (year 1): ${utility_model.Outputs.savings_year1:,.0f}")
print(f"Net present value: ${financial_model.Outputs.npv:,.0f}")
print(f"Simple payback period: {financial_model.Outputs.payback:.1f} years")
print(f"Discounted payback period: {financial_model.Outputs.discounted_payback:.1f} years")
print(f"Net capital cost: ${financial_model.Outputs.adjusted_installed_cost:,.0f}")
print(f"Equity: ${financial_model.Outputs.first_cost:,.0f}")
print(f"Debt: ${financial_model.Outputs.loan_amount:,.0f}")
