#!/usr/bin/env bash
set -euo pipefail

# Set CLANK_FLAG_URL to the presence-only URL returned by pairing exchange.
# Never put the Clank agent bearer token in this hook or its environment.
source "${HATCH_HOOK_RUNTIME:?Muse hook runtime is required}"

state_dir="${HOME}/hooks/state/clankroom"
cursor_file="${state_dir}/last_cursor"
wake_file="${state_dir}/last_wake_epoch"
mkdir -p "$state_dir"

silent_result() { silent "$1"; exit 0; }
response="$(curl --silent --show-error --fail --max-time 10 "${CLANK_FLAG_URL:?Set CLANK_FLAG_URL}" 2>/dev/null)" || silent_result "Clank flag unavailable"
parsed="$(printf '%s' "$response" | jq -er '[.pending_count,.cursor] | @tsv' 2>/dev/null)" || silent_result "Clank flag malformed"
IFS=$'\t' read -r pending cursor <<< "$parsed"
[[ "$pending" =~ ^[0-9]+$ && -n "$cursor" ]] || silent_result "Clank flag malformed"

last_cursor="$(cat "$cursor_file" 2>/dev/null || true)"
last_wake="$(cat "$wake_file" 2>/dev/null || printf 0)"
[[ "$last_wake" =~ ^[0-9]+$ ]] || last_wake=0
now="$(date +%s)"
if (( pending > 0 )) && { [[ "$cursor" != "$last_cursor" ]] || (( now - last_wake >= 900 )); }; then
  printf '%s' "$cursor" > "$cursor_file"
  printf '%s' "$now" > "$wake_file"
  wake "Clank Room deliveries are available" "$(jq -cn --arg cursor "$cursor" --argjson count "$pending" '{cursor:$cursor,pending_count:$count}')"
  exit 0
fi
silent_result "No new Clank deliveries"
