#!/usr/bin/env bash
# deploy-status: reads the state file deploy-local.sh publishes. Fixture state files only;
# no deploy is started and no service is touched.
set -uo pipefail

ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/../.." && pwd)"
CMD="$ROOT/modules/workstation/claude/bin/deploy-status"

pass=0
fail=0
ok() { echo "ok   - $1"; pass=$((pass + 1)); }
bad() { echo "FAIL - $1"; echo "$2" | sed 's/^/       /'; fail=$((fail + 1)); }

tmp="$(mktemp -d)"
trap 'rm -rf "$tmp"' EXIT
export OVERDECK_DEPLOY_STATE_FILE="$tmp/deploy-status.json"
export OVERDECK_DEPLOY_QUEUE_DIR="$tmp/queue"
mkdir -p "$OVERDECK_DEPLOY_QUEUE_DIR"

write_state() { # STATE STEP DETAIL PID UPDATED_AGO
  local now; now=$(date +%s)
  printf '{"schema":1,"state":"%s","step":"%s","detail":"%s","sha":"abc1234","pid":%s,"started_at":%s,"updated_at":%s}\n' \
    "$1" "$2" "$3" "$4" "$((now - 300))" "$((now - $5))" >"$OVERDECK_DEPLOY_STATE_FILE"
}

out=$(bash "$CMD"); rc=$?
[[ $rc -eq 0 && "$out" == *"No deploy has reported status"* ]] \
  && ok "no state file reports unknown, not an error" \
  || bad "no state file reports unknown, not an error" "rc=$rc $out"

write_state running building-web "building the web app" "$$" 5
out=$(bash "$CMD")
[[ "$out" == *"Deploying now: building the web app"* ]] \
  && ok "live pid reports an in-flight deploy" || bad "live pid reports an in-flight deploy" "$out"

dead=999999
write_state running building-web "building the web app" "$dead" 60
out=$(bash "$CMD")
[[ "$out" == *"stopped without finishing"* ]] \
  && ok "dead pid reports a stalled deploy, never as running" \
  || bad "dead pid reports a stalled deploy, never as running" "$out"

write_state failed build-failed "web build failed" "$dead" 10
out=$(bash "$CMD")
[[ "$out" == *"FAILED"* && "$out" == *"web build failed"* ]] \
  && ok "failure is reported with its reason" || bad "failure is reported with its reason" "$out"

write_state finished deployed "deployed abc1234" "$dead" 10
: >"$OVERDECK_DEPLOY_QUEUE_DIR/req-1"
: >"$OVERDECK_DEPLOY_QUEUE_DIR/req-2"
out=$(bash "$CMD")
[[ "$out" == *"Idle."* && "$out" == *"Waiting to deploy: 2"* ]] \
  && ok "idle state reports queue depth from the queue directory" \
  || bad "idle state reports queue depth from the queue directory" "$out"

printf 'not json\n' >"$OVERDECK_DEPLOY_STATE_FILE"
out=$(bash "$CMD"); rc=$?
[[ $rc -ne 0 && "$out" == *"unreadable"* ]] \
  && ok "unreadable state fails closed" || bad "unreadable state fails closed" "rc=$rc $out"

out=$(OVERDECK_DEPLOY_STATE_FILE="$tmp/missing.json" bash "$CMD" --json)
[[ "$out" == *'"state":"unknown"'* ]] && ok "--json emits a record even with no state file" \
  || bad "--json emits a record even with no state file" "$out"

echo "PASS=$pass FAIL=$fail"
[[ $fail -eq 0 ]]
