#!/usr/bin/env bash

set -euo pipefail

repo_dir="$(cd "$(dirname "${BASH_SOURCE[0]}")/../.." && pwd)"
events="$repo_dir/config/dot/quickshell/services/StatusEvents.qml"
focus="$repo_dir/config/dot/quickshell/services/FocusSession.qml"
devices="$repo_dir/config/dot/quickshell/services/DeviceEvents.qml"
privacy="$repo_dir/config/dot/quickshell/services/PrivacyState.qml"

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

rg -q 'action === "open-workspace"' "$events" || fail 'broker cannot route a retained workspace action'
rg -q 'actionId: "open-workspace"' "$focus" || fail 'focus completion does not retain an actionable workspace destination'
rg -q 'actionData: String\(finishedWorkspaceId\)' "$focus" || fail 'focus completion omits its workspace id'
rg -q 'id: discoverySettle' "$devices" || fail 'device discovery has no silent initialization window'
! rg -Uq 'Component\.onCompleted:[^{\n]*\{[^}]*outputInitialized = true' "$devices" || fail 'output monitoring announces initial discovery'
rg -Uq 'function clearFixture\(\): void \{[^}]*initialized = false' "$privacy" || fail 'leaving a fixture can emit a false privacy transition'

# ── The power transitions ────────────────────────────────────────────────────
#
# The charger is a device transition like any other, and joins the same silent
# startup window: without it, plugging in during login would announce itself
# while the desktop was still drawing.
#
# The two priorities are the actual policy. Do Not Disturb silences anything
# below importantPriority, which is right for a charger and wrong for a battery
# that is about to run out -- the one message you must not miss is the one
# saying the machine is about to stop.
rg -q 'key: "device-power"' "$devices" \
    || fail 'nothing announces the charger being connected or removed'
rg -q 'key: "battery-critical"' "$devices" \
    || fail 'nothing announces a critically low battery'
# Bounded any-character rather than "not a brace": the glyph values are
# \u{...} escapes, so a brace appears between the key and its priority.
rg -Uq 'key: "device-power"(.|\n){0,400}?priority: StatusEvents\.ambientPriority' "$devices" \
    || fail 'the charger is not ambient, so Do Not Disturb would not quiet it'
rg -Uq 'key: "battery-critical"(.|\n){0,400}?priority: StatusEvents\.criticalPriority' "$devices" \
    || fail 'a critically low battery is silenced by Do Not Disturb'
rg -q 'root.previousAcOnline = Battery.acOnline;' "$devices" \
    || fail 'power monitoring does not seed its previous state in the settle window'
! rg -Uq 'Component\.onCompleted:[^{\n]*\{[^}]*powerInitialized = true' "$devices" \
    || fail 'power monitoring announces its initial state'

printf 'curated-events policy: PASS\n'
