#!/usr/bin/env bash

set -euo pipefail

repo_dir="$(cd "$(dirname "${BASH_SOURCE[0]}")/../.." && pwd)"
harness="$repo_dir/config/dot/quickshell/wallpaper-policy-harness.qml"
schema="$repo_dir/config/dot/quickshell/config/PreferenceSchema.qml"
state_home="$(mktemp -d /tmp/panama-wallpaper-policy-state.XXXXXX)"
shell_log="$state_home/quickshell.log"
harness_pid=""

fail() {
    printf 'wallpaper policy 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

for key in wallpaperMode wallpaperSlideshowPaths wallpaperIntervalMinutes wallpaperShuffle wallpaperPerMonitor; do
    rg -Fq "key: \"$key\"" "$schema" || fail "schema is missing $key"
done

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 policy 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-policy-test$'; then
        break
    fi
    sleep 0.1
done
[[ "$harness_pid" =~ ^[0-9]+$ ]] || fail 'isolated policy harness process did not start'

status="$(qs_for_harness ipc call wallpaper-policy-test status)"
jq -e '
    .validAbsolute == true and .invalidComma == false and .invalidUnknown == false
    and .collection == ["/images/a.jpg","/images/b.jpg","/images/c.jpg"]
    and .assignments == {"DP-2":"/images/b.jpg"}
    and .single == {"DP-2":"/images/a.jpg","HDMI-A-1":"/images/a.jpg"}
    and .perMonitor == {"DP-2":"/images/b.jpg","HDMI-A-1":"/images/a.jpg"}
    and .slideshow == {"DP-2":"/images/c.jpg","HDMI-A-1":"/images/c.jpg"}
    and .ordered == ["/images/b.jpg","/images/c.jpg","/images/a.jpg"]
' <<<"$status" >/dev/null || fail "policy result was wrong: $status"

shuffle="$(qs_for_harness ipc call wallpaper-policy-test shuffle)"
jq -e '
    (.emitted[0:3] | sort) == ["/images/a.jpg","/images/b.jpg","/images/c.jpg"]
    and .emitted[3] != .emitted[2]
' <<<"$shuffle" >/dev/null || fail "shuffle repeated before exhausting its bag: $shuffle"

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

printf 'wallpaper policy contract: PASS\n'
