#!/usr/bin/env bash

set -euo pipefail

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

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

qs ipc show | rg -q '^target focus$' || fail 'focus IPC target is missing'

# Keep this contract reversible even if an assertion fails halfway through.
cleanup() {
    qs ipc call focus end >/dev/null 2>&1 || true
}
trap cleanup EXIT

qs ipc call focus start >/dev/null
[[ "$(read_prop active)" == "true" ]] || fail 'start did not activate a session'
[[ "$(read_prop paused)" == "false" ]] || fail 'new session started paused'
[[ "$(read_prop workspaceId)" =~ ^[1-9][0-9]*$ ]] || fail 'session did not bind a positive workspace'

qs ipc call focus dismiss >/dev/null
[[ "$(read_prop capsuleVisible)" == "false" ]] || fail 'dismiss did not hide the capsule'

qs ipc call focus pause >/dev/null
[[ "$(read_prop paused)" == "true" ]] || fail 'pause did not freeze the session'

qs ipc call focus reveal >/dev/null
[[ "$(read_prop capsuleVisible)" == "true" ]] || fail 'reveal did not show the capsule'

qs ipc call focus overview >/dev/null
sleep 0.2
hyprctl layers | rg -q 'namespace: qs-overview' || fail 'focus overview did not map Mission Control'
qs ipc call overview close >/dev/null

qs ipc call focus end >/dev/null
[[ "$(read_prop active)" == "false" ]] || fail 'end did not clear the session'

trap - EXIT
printf 'focus-session contract: PASS\n'
