#!/usr/bin/env bash

set -euo pipefail

repo_dir="$(cd "$(dirname "${BASH_SOURCE[0]}")/../.." && pwd)"
harness="$repo_dir/config/dot/quickshell/settings-system-harness.qml"

fail() {
    printf 'settings system contract: %s\n' "$1" >&2
    exit 1
}

qs_for_harness() {
    qs -p "$harness" "$@"
}

cleanup() {
    qs_for_harness kill >/dev/null 2>&1 || true
}
trap cleanup EXIT

original_auto_hdr="$(hyprctl -j getoption render:cm_auto_hdr | jq -r .int)"
original_vrr="$(hyprctl -j getoption misc:vrr | jq -r .int)"
original_direct="$(hyprctl -j getoption render:direct_scanout | jq -r .int)"

qs_for_harness --daemonize >/dev/null
for _ in $(seq 1 40); do
    if qs_for_harness ipc show 2>/dev/null | rg -q '^target settings-system-test$'; then
        break
    fi
    sleep 0.1
done
qs_for_harness ipc show 2>/dev/null | rg -q '^target settings-system-test$' || fail 'test IPC target did not start'

qs_for_harness ipc call settings-system-test refresh >/dev/null
status='{}'
for _ in $(seq 1 40); do
    status="$(qs_for_harness ipc call settings-system-test status | jq -c .)"
    if jq -e '.monitorName != "" and .width > 0 and .height > 0 and .busy == false' <<<"$status" >/dev/null; then
        break
    fi
    sleep 0.1
done
jq -e '.monitorName == "DP-2" and .width == 4500 and .height == 3000 and .scale == 1.5 and .format == "XRGB2101010"' <<<"$status" >/dev/null \
    || fail "live monitor data was not normalized: $status"

[[ "$(qs_for_harness ipc call settings-system-test panelAllowed '__definitely_not_a_panel__' | jq -r .)" == "false" ]] \
    || fail 'unsupported GNOME panel was accepted'
[[ "$(qs_for_harness ipc call settings-system-test panelAllowed sound | jq -r .)" == "true" ]] \
    || fail 'supported GNOME sound panel was rejected'

# Apply the exact current values: this exercises the real allow-listed command
# without changing the daily-driver compositor state.
qs_for_harness ipc call settings-system-test apply "$([[ "$original_auto_hdr" == 1 ]] && printf true || printf false)" "$original_vrr" "$original_direct" >/dev/null
sleep 0.3

[[ "$(hyprctl -j getoption render:cm_auto_hdr | jq -r .int)" == "$original_auto_hdr" ]] || fail 'Auto HDR changed unexpectedly'
[[ "$(hyprctl -j getoption misc:vrr | jq -r .int)" == "$original_vrr" ]] || fail 'VRR changed unexpectedly'
[[ "$(hyprctl -j getoption render:direct_scanout | jq -r .int)" == "$original_direct" ]] || fail 'direct scanout changed unexpectedly'

trap - EXIT
cleanup
printf 'settings system contract: PASS\n'
