#!/usr/bin/env bash

set -euo pipefail

repo_dir="$(cd "$(dirname "${BASH_SOURCE[0]}")/../.." && pwd)"
harness="$repo_dir/config/dot/quickshell/settings-preferences-harness.qml"
state_home="$(mktemp -d /tmp/panama-settings-state.XXXXXX)"
config_home="$(mktemp -d /tmp/panama-settings-config.XXXXXX)"

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

qs_for_harness() {
    XDG_STATE_HOME="$state_home" XDG_CONFIG_HOME="$config_home" qs -p "$harness" "$@"
}

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

start_harness() {
    XDG_STATE_HOME="$state_home" XDG_CONFIG_HOME="$config_home" qs -p "$harness" --daemonize >/dev/null
    for _ in $(seq 1 40); do
        if qs_for_harness ipc show 2>/dev/null | rg -q '^target settings-pref-test$'; then
            return
        fi
        sleep 0.1
    done
    fail 'test IPC target did not start'
}

stop_harness() {
    qs_for_harness kill >/dev/null 2>&1 || true
    for _ in $(seq 1 40); do
        if ! qs_for_harness ipc show >/dev/null 2>&1; then
            return
        fi
        sleep 0.1
    done
    fail 'test shell did not stop cleanly'
}

start_harness
qs_for_harness ipc call settings-pref-test applyFixture >/dev/null

expected='{"use24Hour":true,"showSeconds":false,"dockAutohide":false,"focusDurationMinutes":70,"autoHdr":false,"vrrPolicy":0,"directScanoutPolicy":0,"nightLightEnabled":true,"nightLightAutomatic":true,"nightLightTemperature":4100,"lastPage":"desktop"}'
before="$(qs_for_harness ipc call settings-pref-test status | jq -c 'del(.stateDir)')"
[[ "$before" == "$expected" ]] || fail "fixture did not apply: $before"

state_file=""
for _ in $(seq 1 40); do
    state_file="$(find "$config_home" -path '*/panama/settings.json' -print -quit)"
    if [[ -n "$state_file" ]] && jq -e '.lastPage == "desktop" and .focusDurationMinutes == 70' "$state_file" >/dev/null 2>&1; then
        break
    fi
    sleep 0.1
done
[[ -n "$state_file" ]] || fail 'preferences file was not created'
jq -e '.use24Hour == true and .showSeconds == false and .dockAutohide == false and .autoHdr == false and .directScanoutPolicy == 0 and .nightLightEnabled == true and .nightLightAutomatic == true and .nightLightTemperature == 4100' "$state_file" >/dev/null \
    || fail 'preferences file did not contain the complete atomic update'

# The contract is specifically restart persistence, not merely live QML state.
stop_harness
start_harness
after=""
for _ in $(seq 1 40); do
    after="$(qs_for_harness ipc call settings-pref-test status | jq -c 'del(.stateDir)')"
    [[ "$after" == "$expected" ]] && break
    sleep 0.1
done
[[ "$after" == "$expected" ]] || fail "values did not survive restart: $after"

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