#!/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)"
jq -e '
    .available == true and
    (.devices | type == "array" and length >= 1) and
    ([.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) and
    ([.devices[] | select(.paired)] | length >= 1)
' <<<"$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"
