import json

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

# Extract LED positions
led_positions = data['ctrl_zones'][0]['settings']['custom_shape']['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

# Update the JSON data with the new LED positions
data['ctrl_zones'][0]['settings']['custom_shape']['led_positions'] = sorted_positions

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

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