import os

from django.core.management.base import BaseCommand
from PIL import Image, ImageDraw, ImageFont


def generate_avatar(letter):
    """Generate an avatar for a given letter or number"""
    avatar_size = (100, 100)
    background_color = (0, 123, 255)  # Blue background
    text_color = (255, 255, 255)  # White text
    font_size = 100

    # Create a blank image with background color
    image = Image.new("RGB", avatar_size, background_color)
    draw = ImageDraw.Draw(image)

    # Load a font
    font_path = "[AWS-SECRET-REMOVED]ans-Bold.ttf"
    font = ImageFont.truetype(font_path, font_size)

    # Calculate text size and position using textbbox
    text_bbox = draw.textbbox((0, 0), letter, font=font)
    text_width, text_height = (
        text_bbox[2] - text_bbox[0],
        text_bbox[3] - text_bbox[1],
    )
    text_position = (
        (avatar_size[0] - text_width) / 2,
        (avatar_size[1] - text_height) / 2,
    )

    # Draw the text on the image
    draw.text(text_position, letter, font=font, fill=text_color)

    # Ensure the avatars directory exists
    avatar_dir = "avatars/letters"
    if not os.path.exists(avatar_dir):
        os.makedirs(avatar_dir)

    # Save the image to the avatars directory
    avatar_path = os.path.join(avatar_dir, f"{letter}_avatar.png")
    image.save(avatar_path)


class Command(BaseCommand):
    help = "Generate avatars for letters A-Z and numbers 0-9"

    def handle(self, *args, **kwargs):
        characters = [chr(i) for i in range(65, 91)] + [str(i) for i in range(10)]  # A-Z and 0-9
        for char in characters:
            generate_avatar(char)
            self.stdout.write(self.style.SUCCESS(f"Generated avatar for {char}"))
