#!/bin/bash -e

if [ -z "$1" ]; then
    echo "Usage: $0 <path/to/flair/dir>"
    exit 1
fi

script_dir=$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)
custom_txt="$script_dir/flair/custom.txt"
list_txt="$script_dir/../public/flair/list.txt"

exit_code=0
flairs_checked=0

missing=$(comm -23 <(sort "$custom_txt") <(sort "$list_txt"))
if [ -n "$missing" ]; then
    echo "Missing custom flair from list.txt:"
    echo "$missing"
    exit_code=1
fi

img_names=$(for f in "$1"/*; do basename "$f" .webp; done | sort)

missing_imgs=$(comm -23 <(sort "$list_txt") <(echo "$img_names"))
if [ -n "$missing_imgs" ]; then
    echo "Missing from $1:"
    echo "$missing_imgs"
    exit_code=1
fi

extra_imgs=$(comm -13 <(sort "$list_txt") <(echo "$img_names"))
if [ -n "$extra_imgs" ]; then
    echo "Extra files in $1 not in list.txt:"
    echo "$extra_imgs"
    exit_code=1
fi

for img_file in "$1"/*; do
    if [[ ! "$img_file" =~ \.webp$ ]]; then
        echo "Not a WEBP: $img_file"
        exit_code=1
        continue
    fi

    dimensions=$(identify -format "%wx%h" "$img_file")

    width=$(echo "$dimensions" | cut -d 'x' -f 1)
    height=$(echo "$dimensions" | cut -d 'x' -f 2)

    if [ "$width" -ne "$height" ]; then
        echo "Not square: $img_file ($dimensions)"
        exit_code=1

        echo "Converting to square..."
        max_dimension=$((width > height ? width : height))
        convert "$img_file" -gravity center -background transparent -extent "${max_dimension}x${max_dimension}" "$img_file"
    fi

    if [ "$width" -lt 60 ] || [ "$width" -gt 100 ]; then
        echo "Not between 60-100px: $img_file ($dimensions)"
        exit_code=1

        echo "Resizing to 100px..."
        convert "$img_file" -resize 100x100 "$img_file"
    fi

    # animated WEBPs contain the string "ANMF" in the file
    if grep -q "ANMF" "$img_file"; then
        echo "Animated: $img_file"
        exit_code=1
    fi

    flairs_checked=$((flairs_checked + 1))
    if [ $((flairs_checked % 100)) -eq 0 ]; then
        echo "Checked $flairs_checked flair images so far..."
    fi
done

if [ "$exit_code" -eq 0 ]; then
    echo "✅ Images are OK"
fi

exit $exit_code
