#!/bin/bash

shopt -s nullglob  # Prevent errors if no files match

# Create a temporary directory
temp_dir=$(mktemp -d)

# Associative array to store unique image bases
declare -A unique_images

# Extract base names without resolution suffix
for file in *.64.png; do
    base="${file%.64.png}"
    unique_images["$base"]=1
done

# Convert keys to sorted array
unique_bases=("${!unique_images[@]}")
IFS=$'\n' sorted_bases=($(sort <<<"${unique_bases[*]}"))
unset IFS

# Renaming process
counter=0
for base in "${sorted_bases[@]}"; do
    for res in 64 128 256; do
        old_file="${base}.${res}.png"
        new_file="${temp_dir}/waifu-${counter}.${res}.png"

        if [[ -f "$old_file" ]]; then
            mv "$old_file" "$new_file"
            echo "Copied: $old_file -> $new_file"
        fi
    done
    ((counter++))
done

# Move the renamed files back
echo "Moving new files back..."
mv "${temp_dir}"/* .

# Remove the temporary directory
rmdir "${temp_dir}"

echo "Renaming complete and safe!"

