from typing import OrderedDict


def extract_segments(key_entries, current_seg_id: int):
    """extracts segment dictionary from trial entries, returns both dictionary and int ID for first seg ID for next trial"""
    # keep only copy to avoid making change to original data
    key_entries = key_entries.copy()
    # # group segments by temporary IDs
    key_entries["humanTimeID"] = (key_entries.trialPhase != key_entries.trialPhase.shift()).cumsum()

    # create info
    segment_info = OrderedDict()
    for i, seg in key_entries.groupby("humanTimeID"):
        # add basic info to segment dict
        seg_dict = {}
        seg_dict["duration"] = seg.seconds.iloc[-1] - seg.seconds.iloc[0]
        seg_dict["reading_num"] = len(seg.index)
        seg_dict["phase"] = seg.trialPhase.iloc[0]
        seg_dict["indices"] = seg.index.tolist()
        seg_dict["trial_key"] = seg.peopleTrialKey.iloc[0]
        seg_dict["subject"] = seg.peopleName.iloc[0]
        seg_dict["start_sec"] = seg.seconds.iloc[0]
        seg_dict["end_sec"] = seg.seconds.iloc[-1]

        # crashed: if current phase is 3, next index within this trial, next index is 4
        crash_ind = -1  # default to -1
        if seg_dict["phase"] == 3:
            next_ind = seg.index[-1] + 1
            if next_ind in key_entries.index:
                if key_entries.trialPhase.loc[next_ind] == 4:
                    crash_ind = next_ind
        seg_dict["crash_ind"] = crash_ind

        # add to overall dictionary
        segment_info[current_seg_id] = seg_dict
        current_seg_id += 1

    return segment_info, current_seg_id