#!/usr/bin/env bash

set -euo pipefail

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

project_root="$(cd "$(dirname "${BASH_SOURCE[0]}")/../.." && pwd)"
helper="$project_root/config/dot/quickshell/scripts/panama-kdeconnect"

[[ -x "$helper" ]] || fail 'helper is missing or not executable'

status="$($helper status)"

# The shape is checked whenever a device is present, but a device being present
# is not itself required. kdeconnectd drops its device objects for a phone it
# has not seen recently -- the pairing survives in its config, the D-Bus object
# does not -- so demanding one makes this fail whenever the phone is off, out of
# range, or simply has not opened the app today. That is the machine's state,
# not a defect in the helper.
jq -e '.available == true and (.devices | type == "array")' <<<"$status" >/dev/null \
    || fail 'live status is not a readable device list'

if [[ "$(jq -r '.devices | length' <<<"$status")" == "0" ]]; then
    printf 'KDE Connect helper contract: PASS (no device visible to the daemon right now; shape checks skipped)\n'
    exit 0
fi

jq -e '
    ([.devices[] | (keys | sort) == (["actions", "id", "name", "paired", "reachable", "type"] | sort)] | all) and
    ([.devices[] | (.id | test("^[A-Fa-f0-9]{32,64}$"))] | all) and
    ([.devices[].actions[] | . == "clipboard" or . == "ping" or . == "ring" or . == "share"] | all)
' <<<"$status" >/dev/null || fail 'live status shape is invalid'

paired_count="$(jq '[.devices[] | select(.paired)] | length' <<<"$status")"
reachable_count="$(jq '[.devices[] | select(.reachable)] | length' <<<"$status")"
printf 'KDE Connect helper contract: PASS (%s paired, %s reachable; identities redacted)\n' \
    "$paired_count" \
    "$reachable_count"
