import mechnet as mn
import numpy as np
import matplotlib.pyplot as plt
import h5py
import sys
sys.path.append("/home/lpyka/hierarchical_interface")
from lib.push_data import push_data_to, push_ivcat 

def get_iv_data(filepath):
    grouppaths = mn.datman.bundle_all_sub_groups(filepath, ["simulationdata"])
    simdata = mn.datman.get_simdata(filepath, grouppaths[0], readpickled=False)
    simdata_dict = simdata.get_simdata_dict()
    iv_data = np.array(simdata_dict["logged_data"]["iv"])
    return iv_data

def plot_iv_curve(data):
    fig, ax = plt.subplots()
    x = data[:,1]
    y = data[:,0]
    ax.plot(x, y)
    plt.show()

def append_data_to_txt(data, seed):
    with open("ivcat.txt", 'a') as file:
        file.write(f"#seed_{seed}\n")
        for point in data:
            x, y = point 
            file.write(f"{x} {y}\n")

def clear_txt_file():
    with open("ivcat.txt", "w")  as f:
        f.write("")

if __name__ == "__main__":
    offset = input("Offset:  ")
    base_path = f"/FASTTEMP/p7/lpyka/hierarchical_interface/2_offset_hierarchical_struct/offset_{offset}"
    clear_txt_file()
    for seed in range(1000,1050):
        file_name = f"FDB_PARSOL_SIRC-FCVC_SOG-IVCG_HFBA_CPC-NIC_-_{seed}.h5" 
        full_path = base_path + "/" + file_name
        iv_data = get_iv_data(full_path)
        #plot_iv_curve(iv_data)
        append_data_to_txt(iv_data, seed)
    push_ivcat(base_path) 
    print("cutoff prev")