import json

def reorder_leds(led_positions):
    # Sort LED positions by y first (row), then x (column)
    sorted_positions = sorted(led_positions, key=lambda pos: (pos['y'], pos['x']))
    
    # Reassign led_num values based on the new order
    for i, position in enumerate(sorted_positions):
        position['led_num'] = i
    
    return sorted_positions

# Load the JSON data
with open('DoubleLEDMatrix.json', 'r') as file:
    data = json.load(file)

# Process each matrix
for ctrl_zone in data['ctrl_zones']:
    matrix_name = ctrl_zone['controller']['name']
    print(f"Processing {matrix_name}...")
    
    # Extract LED positions
    led_positions = ctrl_zone['settings']['custom_shape']['led_positions']
    
    # Reorder LEDs
    reordered_positions = reorder_leds(led_positions)
    
    # Update the JSON data with the new LED positions
    ctrl_zone['settings']['custom_shape']['led_positions'] = reordered_positions

# Save the updated JSON data
with open('DoubleLEDMatrix_row_wise.json', 'w') as file:
    json.dump(data, file, indent=4)

print("LED positions have been reordered from column-wise to row-wise for both matrices.")
print("The updated data has been saved to 'DoubleLEDMatrix_row_wise.json'.")
