#!/usr/bin/env bash
set -uo pipefail
TMP=$(mktemp -d "$HOME/.cache/cifb-test-XXXXXX")
trap 'rm -rf "$TMP"' EXIT
export CI_FALLBACK_NO_MAIN=1 CI_FALLBACK_STATE_DIR="$TMP/state" CI_FALLBACK_LOG="$TMP/log" \
  CI_FALLBACK_START_AFTER=2 CI_FALLBACK_STOP_AFTER=3 CI_FALLBACK_REDUNDANT_AFTER=2
source "$HOME/.claude/bin/ci-fallback.sh"
PASS=0; FAIL=0
t() { local name="$1" want="$2" got="$3"; if [ "$want" = "$got" ]; then echo "PASS $name"; PASS=$((PASS+1)); else echo "FAIL $name want=$want got=$got"; FAIL=$((FAIL+1)); fi; }
clear_counters() { reset pressure; reset idle; reset redundant; }

# A queue that PERSISTS recruits the laptop, even with debian1 online: work that is
# still waiting after START_AFTER polls is not being served by queuing longer.
clear_counters
t "queue-1st-poll-holds" hold "$(decide 3 1 0 inactive)"
t "queue-2nd-poll-spills" start "$(decide 3 1 0 inactive)"

# Same rule when debian1 is down outright.
clear_counters
t "down-1st-poll-holds" hold "$(decide 2 0 0 inactive)"
t "down-2nd-poll-starts" start "$(decide 2 0 0 inactive)"

# A burst debian1 drains inside the window must NOT accumulate toward a spill --
# this is what keeps debian1 primary rather than a peer.
clear_counters
decide 1 1 0 inactive >/dev/null
decide 0 1 0 inactive >/dev/null
t "drained-burst-does-not-accumulate" hold "$(decide 1 1 0 inactive)"

# Already recruited and work remains -> keep helping, never double-start.
clear_counters
t "active-with-queue-holds" hold "$(decide 5 1 1 active)"

# Queue drained + debian1 alive -> retire quickly, ready for the next burst.
clear_counters
t "redundant-1-holds" hold "$(decide 0 1 0 active)"
t "redundant-2-stops" stop "$(decide 0 1 0 active)"

# Queue drained + debian1 still down -> retire on the slower idle window; nothing
# else would serve a job that arrives meanwhile.
clear_counters
t "idle-1-holds" hold "$(decide 0 0 0 active)"
t "idle-2-holds" hold "$(decide 0 0 0 active)"
t "idle-3-stops" stop "$(decide 0 0 0 active)"

# Never stopped mid-job, and the busy poll clears the retirement count.
clear_counters
decide 0 1 0 active >/dev/null
t "busy-blocks-stop" hold "$(decide 0 1 1 active)"
t "busy-reset-restarts-count" hold "$(decide 0 1 0 active)"

# Work arriving again while active clears retirement -> no stop/start flapping.
clear_counters
decide 0 1 0 active >/dev/null
t "queue-return-holds" hold "$(decide 4 1 0 active)"
t "queue-return-still-holds" hold "$(decide 4 1 0 active)"

# Nothing running, nothing queued -> nothing to do.
clear_counters
t "inactive-idle-holds" hold "$(decide 0 1 0 inactive)"

echo "passed=$PASS failed=$FAIL"
[ "$FAIL" -eq 0 ]
