#!/usr/bin/env bash

set -euo pipefail

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

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

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

catalog="$($helper catalog)"

# This asserts a LIVE, authenticated Home Assistant. An absent credential is not
# a defect in Panama, so it skips rather than fails -- otherwise the suite is red
# on any machine that has not been given a token, and a red suite that is
# expected to be red stops being read.
#
# A configured-but-broken bridge still fails, which is the case worth catching.
if [[ "$(jq -r '.configured' <<<"$catalog")" != "true" ]]; then
    printf 'Home Assistant helper contract: SKIP (no token configured)\n'
    printf '  Set PANAMA_HOME_ASSISTANT_TOKEN in config/bash/env to exercise this.\n'
    printf '  Reason reported by the helper: %s\n' "$(jq -r '.error // "unknown"' <<<"$catalog")"
    exit 0
fi

jq -e '
  .ok == true and .configured == true and .error == "" and
  (.entities | type == "array" and length > 0) and
  ([.entities[] | (keys | sort) == (["active", "available", "brightnessPct", "dimmable", "id", "sourceName", "state"] | sort)] | all) and
  ([.entities[] | (.id | startswith("light.")) and (.brightnessPct >= 0 and .brightnessPct <= 100)] | all) and
  (.legacyEntityIds | type == "array")
' <<<"$catalog" >/dev/null || fail 'live catalog shape is invalid'

printf 'Home Assistant helper contract: PASS (configured=true, %s lights; contents redacted)\n' \
    "$(jq '.entities | length' <<<"$catalog")"
