#!/usr/bin/env bash

set -euo pipefail

repo_dir="$(cd "$(dirname "${BASH_SOURCE[0]}")/../.." && pwd)"

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

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

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

cleanup() {
    qs ipc call activity clear >/dev/null 2>&1 || true
    qs ipc call status-events reset >/dev/null 2>&1 || true
}
trap cleanup EXIT

qs ipc show | rg -q '^target activity$' || fail 'activity IPC target is missing'
rg -q 'StatusEvents.publish' "$repo_dir/config/dot/quickshell/services/Capture.qml" || fail 'capture does not publish recording transitions'
rg -q 'status-events screenshot' "$repo_dir/config/dot/quickshell/services/Capture.qml" || fail 'successful screenshot path does not publish an event'
rg -q 'StatusEvents.publish' "$repo_dir/config/dot/quickshell/services/NightLight.qml" || fail 'Night Light does not publish transitions'

qs ipc call status-events reset >/dev/null
qs ipc call activity fixture microphone-on >/dev/null
[[ "$(activity microphoneActive)" == "true" ]] || fail 'microphone state did not become persistent'
[[ "$(event activeKey)" == "privacy-microphone" ]] || fail 'microphone transition did not publish Signal Glass event'

qs ipc call status-events dismiss >/dev/null
[[ "$(activity microphoneActive)" == "true" ]] || fail 'capsule dismissal cleared persistent privacy state'

qs ipc call activity fixture all-off >/dev/null
[[ "$(activity microphoneActive)" == "false" ]] || fail 'microphone state did not clear'
[[ "$(event activeKey)" == "privacy-microphone" ]] || fail 'microphone release did not publish a transition'
[[ "$(event title)" == "Microphone released" ]] || fail 'microphone release copy is incorrect'

trap - EXIT
cleanup
printf 'activity-state contract: PASS\n'
