#!/usr/bin/env bash

set -euo pipefail

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

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

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

probe="$($helper probe)"
jq -e '.eds == true and .sourceRegistry == true and .enabledSources > 0' <<<"$probe" >/dev/null \
    || fail 'EDS readiness probe failed'

range_start="$(date +%s)"
range_end="$((range_start + 1209600))"
snapshot="$($helper query "$range_start" "$range_end")"

jq -e '
    .ok == true and
    (.sources | type == "array" and length > 0) and
    (.events | type == "array") and
    ([.sources[] | (keys | sort) == (["id", "name", "color"] | sort)] | all) and
    ([.events[] | (keys | sort) == (["id", "sourceId", "uid", "summary", "start", "end", "allDay", "location", "joinUrl"] | sort)] | all)
' <<<"$snapshot" >/dev/null || fail 'live snapshot shape is invalid'

printf 'calendar agenda helper contract: PASS (%s sources, %s events; contents redacted)\n' \
    "$(jq '.sources | length' <<<"$snapshot")" \
    "$(jq '.events | length' <<<"$snapshot")"
