#!/usr/bin/env bash

set -euo pipefail

repo_dir="$(cd "$(dirname "${BASH_SOURCE[0]}")/../.." && pwd)"
controls="$repo_dir/config/dot/quickshell/modules/settings/WallpaperControls.qml"
picker="$repo_dir/config/dot/quickshell/modules/settings/WallpaperPicker.qml"
appearance="$repo_dir/config/dot/quickshell/modules/settings/AppearancePage.qml"
harness="$repo_dir/config/dot/quickshell/wallpaper-settings-harness.qml"
state_home="$(mktemp -d /tmp/panama-wallpaper-settings-state.XXXXXX)"
shell_log="$state_home/quickshell.log"
harness_pid=""

fail() {
    printf 'wallpaper settings contract: %s\n' "$1" >&2
    [[ -s "$shell_log" ]] && sed -n '1,160p' "$shell_log" >&2
    exit 1
}

instances_for_harness() {
    qs list --all 2>/dev/null | awk -v expected="$harness" '
        /^Instance / { pid = "" }
        /^[[:space:]]*Process ID:/ { pid = $3 }
        /^[[:space:]]*Config path:/ {
            path = $0
            sub(/^[[:space:]]*Config path: /, "", path)
            if (path == expected && pid ~ /^[0-9]+$/) print pid
        }
    '
}

cleanup() {
    if [[ "$harness_pid" =~ ^[0-9]+$ ]] && kill -0 "$harness_pid" 2>/dev/null; then
        kill "$harness_pid" 2>/dev/null || true
    fi
    rm -rf "$state_home"
}
trap cleanup EXIT

[[ -f "$controls" ]] || fail 'WallpaperControls.qml is missing'
rg -Fq 'WallpaperControls {' "$appearance" || fail 'Appearance does not show wallpaper mode controls'
rg -Fq 'selectedOutput: wallpaperControls.selectedOutput' "$appearance" \
    || fail 'thumbnail actions do not follow the selected display'

qs_for_harness() {
    if [[ "$harness_pid" =~ ^[0-9]+$ && "${1:-}" == "ipc" ]]; then
        XDG_STATE_HOME="$state_home" qs -p "$harness" ipc --pid "$harness_pid" "${@:2}"
    else
        XDG_STATE_HOME="$state_home" qs -p "$harness" "$@"
    fi
}

qs_for_harness --daemonize >"$shell_log" 2>&1 || fail 'isolated settings harness did not launch'
for _ in $(seq 1 60); do
    harness_pid="$(instances_for_harness | head -1)"
    if [[ "$harness_pid" =~ ^[0-9]+$ ]] \
        && qs_for_harness ipc show 2>/dev/null | rg -q '^target wallpaper-settings-test$'; then
        break
    fi
    sleep 0.1
done
[[ "$harness_pid" =~ ^[0-9]+$ ]] || fail 'isolated settings harness process did not start'

[[ "$(qs_for_harness ipc call wallpaper-settings-test activate single /images/a.jpg)" \
    == '["single:/images/a.jpg"]' ]] || fail 'Single mode did not call setSingle'
[[ "$(qs_for_harness ipc call wallpaper-settings-test activate slideshow /images/b.jpg)" \
    == '["toggle:/images/b.jpg"]' ]] || fail 'Slideshow mode did not toggle collection membership'
[[ "$(qs_for_harness ipc call wallpaper-settings-test activate per-monitor /images/c.jpg)" \
    == '["assign:DP-2:/images/c.jpg"]' ]] || fail 'Per-display mode did not assign the selected output'

states="$(qs_for_harness ipc call wallpaper-settings-test states)"
jq -e '.selectedOutput == "DP-2"
    and .single == {"current":true,"selected":true}
    and .slideshow == {"current":false,"selected":true}
    and .perMonitor == {"current":false,"selected":true}' \
    <<<"$states" >/dev/null || fail "active Prism and selection states were conflated: $states"

if rg -n 'ReferenceError|TypeError|Binding loop|Unable to assign|Cannot assign' "$shell_log"; then
    fail 'settings harness emitted a QML runtime warning'
fi

printf 'wallpaper settings contract: PASS\n'
