import pickle


def build_save_route_by_stop(stop_times_file, FOLDER):
    """
    This function saves a dictionary to provide easy access to all the routes passing through a stop_id.
    Args:
        stop_times_file (pandas.dataframe): stop_times.txt file in GTFS.
        FOLDER (str): path to network folder.
    Returns:
        route_by_stop_dict_new (dict): keys: stop_id, values: list of routes passing through the stop_id. Format-> dict[stop_id] = [route_id]
    """
    print("building routes_by_stop")
    stops_by_route = stop_times_file.drop_duplicates(subset=['route_id', 'stop_sequence'])[
        ['stop_id', 'route_id']].groupby('stop_id')
    route_by_stop_dict_new = {id: list(routes.route_id) for id, routes in stops_by_route}

    with open(f'./dict_builder/{FOLDER}/routes_by_stop.pkl', 'wb') as pickle_file:
        pickle.dump(route_by_stop_dict_new, pickle_file)
    print("routes_by_stop done")
    return route_by_stop_dict_new