# %%
import pandas as pd

# following code computes final mapping + classification accuracy
# %%
def run(fold):
    data_path = f'exports/result_group_{fold}.csv'
    df = pd.read_csv(data_path, skipinitialspace=True)
    p_mdm = df['p_mdm']

    data_path = f'../../../train/mapping_t5_complete_desc_unit_name/mapping_prediction/exports/result_group_{fold}.csv'
    df = pd.read_csv(data_path, skipinitialspace=True)
    actual_mdm = df['MDM']

    thing_correctness = df['thing'] == df['p_thing']
    property_correctness = df['property'] == df['p_property']
    answer = thing_correctness & property_correctness

    # if is non-MDM -> then should be unmapped
    # if is MDM -> then should be mapped correctly

    # out of correctly predicted relevant data, how many are mapped correctly?
    correct_positive_mdm_and_map = sum(p_mdm & actual_mdm & answer)

    # number of correctly predicted non-relevant data
    correct_negative_mdm = sum(~(p_mdm) & ~(actual_mdm))

    overall_correct = (correct_positive_mdm_and_map + correct_negative_mdm)/len(actual_mdm)
    print(overall_correct)
# %%
for fold in [1,2,3,4,5]:
    run(fold)

# %%
# check for "duplicates" in each ship
# we want to enforce a unique mapping
fold = 1

data_path = f'exports/result_group_{fold}.csv'
df = pd.read_csv(data_path, skipinitialspace=True)

# get predicted mdm labels
p_mdm = df['p_mdm'].to_numpy()
predicted_mdm_mask = p_mdm.astype(bool)

# %%
# get the mapped data
data_path = f'../../../train/mapping_t5_complete_desc_unit_name/mapping_prediction/exports/result_group_{fold}.csv'
df = pd.read_csv(data_path, skipinitialspace=True)
df['mapping'] = df['p_thing'] + ' ' + df['p_property']


# get ship list
ship_list = sorted(list(set(df['ships_idx'])))

# assign ship
ship = ship_list[1]

ship_boolean_mask = df['ships_idx'] == ship

# isolate predicted mdm data of the ship
ship_predicted_mdm_mask = predicted_mdm_mask & ship_boolean_mask

mapping_list = df['mapping'][ship_predicted_mdm_mask].to_list()

mapping_count = {}

for mapping in mapping_list:
    if mapping in mapping_count:
        mapping_count[mapping] = mapping_count[mapping] + 1
    else:
        mapping_count[mapping] = 1

# print the mapping count
mapping_count

# %%
# we can take one of the elements that exceeded 1 mapping and check
df_ship = df[ship_predicted_mdm_mask]
df_ship[df_ship['mapping'] == 'GeneratorEngine2 RunningState']
# %%
