#!/bin/bash

# Enable debug output
set -x

# Expanded Gruvbox palette with more intermediate shades
colors=(
	# Dark backgrounds
	"#282828" # bg
	"#32302f" # bg0
	"#3c3836" # bg1
	"#504945" # bg2
	"#665c54" # bg3
	"#7c6f64" # bg4

	# Light colors
	"#ebdbb2" # fg
	"#d5c4a1" # fg2
	"#bdae93" # fg3
	"#a89984" # fg4

	# Bright colors with variations
	"#fb4934" # bright red
	"#cc241d" # dark red
	"#9d0006" # darker red

	"#b8bb26" # bright green
	"#98971a" # dark green
	"#79740e" # darker green

	"#fabd2f" # bright yellow
	"#d79921" # dark yellow
	"#b57614" # darker yellow

	"#83a598" # bright blue
	"#458588" # dark blue
	"#076678" # darker blue

	"#d3869b" # bright purple
	"#b16286" # dark purple
	"#8f3f71" # darker purple

	"#8ec07c" # bright aqua
	"#689d6a" # dark aqua
	"#427b58" # darker aqua

	"#fe8019" # bright orange
	"#d65d0e" # dark orange
	"#af3a03" # darker orange
)

if [ -z "$1" ]; then
	echo "Usage: $0 <input_image.png> [output_image.png]"
	exit 1
fi

input_file="$1"
output_file="${2:-${1%.*}_gruvbox.png}"

echo "Processing $input_file..."

# Create color palette file with all colors
palette_cmd="magick convert "
for color in "${colors[@]}"; do
	palette_cmd+="xc:$color "
done
palette_cmd+="+append /tmp/palette.png"
eval $palette_cmd

echo "Created palette..."

# Process the image with refined parameters
magick convert "$input_file" \
	-colorspace RGB \
	-brightness-contrast 3x10 \
	-level 0%,100%,1.1 \
	-colors 128 \
	-dither None \
	-remap /tmp/palette.png \
	-define png:color-type=6 \
	"$output_file"

echo "Conversion complete. Output saved to: $output_file"

# Clean up
rm /tmp/palette.png
