import copy


def speed_map_segs_to_geojson(seg_list):
    """Return a GeoJSON given a list of high resolution segments from the Swiftly Speed Maps API."""
    # Initialize a new GeoJSON object
    new_geojson = {
        'type': 'FeatureCollection',
        'features': []
    }

    # Dont work on the input list
    seg_list_copy = copy.deepcopy(seg_list)

    # Iterativley build the features of the new GeoJSON object
    for i, seg in enumerate(seg_list_copy):
        # Prepare the feature properties
        del seg['fromStop']
        del seg['toStop']

        # New attribute, can be used to identify segments
        seg['order'] = i

        # Prepare the feature geometry coordinates
        pathLocs = seg.pop('pathLocs')
        coords = [[p['lon'], p['lat']] for p in pathLocs]

        # Construct feature
        new_feature = {
            'type': 'Feature',
            'geometry': {'type': 'LineString', 'coordinates': coords},
            'properties': seg
        }

        # Append feature to the list of features in GeoJSON object
        new_geojson['features'].append(new_feature)

    return new_geojson