#!/usr/bin/env bash

set -euo pipefail

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

status() {
    qs ipc call status-events status | jq -r ".${1}"
}

cleanup() {
    qs ipc call status-events reset >/dev/null 2>&1 || true
    if [[ "${restore_dnd:-false}" == "true" ]]; then
        qs ipc call notifications dnd >/dev/null 2>&1 || true
    fi
}
trap cleanup EXIT

qs ipc show | rg -q '^target status-events$' || fail 'IPC target is missing'
qs ipc call status-events reset >/dev/null

qs ipc call status-events fixture ambient >/dev/null
[[ "$(status activeKey)" == "device-output" ]] || fail 'ambient fixture did not become active'
[[ "$(status queueLength)" == "0" ]] || fail 'first event unexpectedly queued'

qs ipc call status-events fixture ambient-replacement >/dev/null
[[ "$(status activeKey)" == "device-output" ]] || fail 'equivalent event changed its stable key'
[[ "$(status title)" == "Studio Display" ]] || fail 'equivalent event did not replace active content'
[[ "$(status queueLength)" == "0" ]] || fail 'equivalent event stacked instead of replacing'

qs ipc call status-events fixture critical >/dev/null
[[ "$(status activeKey)" == "privacy-microphone" ]] || fail 'critical event did not preempt ambient event'
[[ "$(status priority)" == "90" ]] || fail 'critical event priority was not preserved'
[[ "$(status queueLength)" == "1" ]] || fail 'preempted event was not retained once'

qs ipc call status-events dismiss >/dev/null
[[ "$(status activeKey)" == "device-output" ]] || fail 'dismiss did not reveal the queued ambient event'

qs ipc call status-events reset >/dev/null
dnd_now="$(qs ipc call notifications dnd)"
if [[ "$dnd_now" == "true" ]]; then
    restore_dnd=true
fi
qs ipc call status-events fixture ambient >/dev/null
[[ "$(status active)" == "false" ]] || fail 'DND did not suppress an ambient event'

qs ipc call status-events fixture critical >/dev/null
[[ "$(status activeKey)" == "privacy-microphone" ]] || fail 'DND suppressed a privacy event'

trap - EXIT
cleanup
printf 'status-events contract: PASS\n'
