from PIL import Image, ImageDraw, ImageFont
import os
import random

# Define the colors to be used
colors = [
    ("red", "红色"),
    ("blue", "蓝色"),
    ("yellow", "黄色"),
    ("green", "绿色"),
    ("orange", "橙色"),
    ("purple", "紫色"),
    ("pink", "粉色"),
    ("black", "黑色"),
    ("white", "白色"),
    ("brown", "棕色")
]

# Load the uploaded font
font_path = '/mnt/data/Mengshen-Handwritten.ttf'
font_size = 20  # Adjust font size as needed
font = ImageFont.truetype(font_path, font_size)

# Calculate total image size needed
# Assuming 30px vertical spacing between rectangles, 1px border, and 30px for text height
rect_height = 10  # Adjusted for horizontal orientation as in Code 2
rect_width = 40   # Adjusted width as in Code 2
border_size = 1
spacing = 30
text_height = 30  # Approximation
num_colors = len(colors)

# Image width: width of rectangles + maximum text width (approximation) + spacing
# Calculate maximum text width
max_text_width = max([font.getsize(color[1])[0] for color in colors]) + spacing

image_width = rect_width + max_text_width + (border_size * 2) + spacing * 2
image_height = (rect_height + text_height + spacing * 3) * num_colors

# Shuffle the texts to not match the colors directly
shuffled_colors = colors[:]
while True:
    random.shuffle(shuffled_colors)
    if all(shuffled_color[1] != color[1] for shuffled_color, color in zip(shuffled_colors, colors)):
        break

# Create a new image with white background
image = Image.new("RGB", (image_width, image_height), "white")
draw = ImageDraw.Draw(image)

# Draw each color rectangle and corresponding shuffled text
y_offset = spacing
for (color, _), (_, text) in zip(colors, shuffled_colors):
    # Calculate x coordinates for rectangle and text to center them
    rect_x1 = (image_width - rect_width - max_text_width - spacing) // 2
    rect_x2 = rect_x1 + rect_width
    text_x = rect_x2 + spacing * 2  # Leave some space after the rectangle

    # Rectangle coordinates and border
    draw.rectangle([rect_x1-border_size, y_offset-border_size, rect_x2+border_size, y_offset+rect_height+border_size], outline="black")
    draw.rectangle([rect_x1, y_offset, rect_x2, y_offset + rect_height], fill=color)

    # Text position: vertically centered with the rectangle
    text_y = y_offset + (rect_height - font.getsize(text)[1]) // 2
    draw.text((text_x, text_y), text, fill="black", font=font)

    # Update y_offset for the next color
    y_offset += rect_height + text_height + spacing * 3

# show the updated image
output_path_shuffled = '/mnt/data/color_rectangles_with_shuffled_text.png'
image = Image.open(output_path_shuffled)
image.show()
