import pandas as pd
import numpy as np
import csv
import json

with open('config.json', 'r') as f:
    js_data = json.load(f)

pv_yield_file_name = js_data["data_path"]["pv_yield"]
print(pv_yield_file_name)
# factory_demand_file_name = 'factory_power1.xlsx'
factory_demand_file_name = js_data["data_path"]["demand"]
print(factory_demand_file_name)
electricity_price_data = js_data["data_path"]["buy"]
print(electricity_price_data)
electricity_price_data_sell = js_data["data_path"]["sell"]
print(electricity_price_data_sell)

pv_df = pd.read_csv(pv_yield_file_name, index_col='Time', usecols=['Time', 'PV yield[kW/kWp]'])
pv_df.index = pd.to_datetime(pv_df.index)

df_power = pd.read_csv(factory_demand_file_name, index_col='Time', usecols=['Time', 'FactoryPower'])
df_power.index = pd.to_datetime(df_power.index)
df_combined = pv_df.join(df_power)

price_df = pd.read_csv(electricity_price_data, index_col='Time', usecols=['Time', 'ElectricityBuy'])
price_df.index = pd.to_datetime(price_df.index)
price_df = price_df.reindex(df_combined.index)
df_combined2 = df_combined.join(price_df)

sell_df = pd.read_csv(electricity_price_data_sell, index_col='Time', usecols=['Time', 'ElectricitySell'])
sell_df.index = pd.to_datetime(sell_df.index)
sell_df = sell_df.reindex(df_combined.index)
df_combined3 = df_combined2.join(sell_df)

with open('combined_data.csv', 'w', newline='') as file:
    writer = csv.writer(file)
    writer.writerow(['time', 'PV yield[kW/kWp]', 'demand','buy', 'sell'])
    cnt = 0
    for index, row in df_combined3.iterrows():
        time_formatted = index.strftime('%H:%M')
        writer.writerow([time_formatted, row['PV yield[kW/kWp]'], row['FactoryPower'],row['ElectricityBuy'], row['ElectricitySell']])
        
    print('The file is written to combined_data.csv')


print("Simulation data with electricity prices has been updated and saved.")