#!/bin/sh

set -eu

root=$(CDPATH= cd -- "$(dirname -- "$0")/.." && pwd)
tmpdir=$(mktemp -d)
trap 'rm -rf "$tmpdir"' EXIT HUP INT TERM
config_dir="$tmpdir/config"
fake_bin="$tmpdir/bin"
log="$tmpdir/commands.log"
mkdir -p "$config_dir" "$fake_bin"

printf 'background #111111\n' > "$config_dir/dark-theme.auto.conf"
printf 'background #eeeeee\nmacos_titlebar_color system\n' \
    > "$config_dir/light-theme.auto.conf"
printf 'background #222222\nmacos_titlebar_color background\n' \
    > "$config_dir/no-preference-theme.auto.conf"

"$root/repair-auto-themes.sh" "$config_dir"
"$root/tests/verify_auto_themes.sh" "$config_dir"

for appearance in dark light no-preference; do
    count=$(grep -c '^macos_titlebar_color background$' \
        "$config_dir/$appearance-theme.auto.conf")
    [ "$count" -eq 1 ]
done

before=$(shasum "$config_dir"/*-theme.auto.conf)
"$root/repair-auto-themes.sh" "$config_dir"
after=$(shasum "$config_dir"/*-theme.auto.conf)
[ "$before" = "$after" ]

cat > "$fake_bin/kitten" <<'EOF'
#!/bin/sh
printf 'kitten %s\n' "$*" >> "$TEST_LOG"
exit 0
EOF
cat > "$fake_bin/kitty" <<'EOF'
#!/bin/sh
printf 'kitty %s\n' "$*" >> "$TEST_LOG"
exit 0
EOF
chmod +x "$fake_bin/kitten" "$fake_bin/kitty"

printf 'background #fafafa\n' > "$config_dir/light-theme.auto.conf"
TEST_LOG="$log" PATH="$fake_bin:$PATH" \
    KITTY_CONFIG_DIRECTORY="$config_dir" KITTY_WINDOW_ID=1 \
    fish --no-config -c \
    'source "$HOME/.config/fish/functions/kitten.fish"; kitten themes Tomorrow'
grep -q '^kitten themes Tomorrow$' "$log"
grep -q '^kitty @ load-config$' "$log"
"$root/tests/verify_auto_themes.sh" "$config_dir"

: > "$log"
TEST_LOG="$log" PATH="$fake_bin:$PATH" \
    KITTY_CONFIG_DIRECTORY="$config_dir" KITTY_WINDOW_ID=1 \
    fish --no-config -c \
    'source "$HOME/.config/fish/functions/kitten.fish"; kitten icat image.png'
grep -q '^kitten icat image.png$' "$log"
if grep -q '^kitty ' "$log"; then
    echo "non-theme kitten command triggered a Kitty reload" >&2
    exit 1
fi

echo "PASS: theme repair is idempotent and the Fish shim only intercepts themes"
