#!/usr/bin/env bash
# h3-queue-watch.sh — keep an eye on a ComfyUI generation queue from any terminal.
# Usage: h3-queue-watch.sh [endpoint]   (default http://127.0.0.1:8188 — the tunnel)
# Polls /progress + /queue every 8s, prints one compact line per tick.
# Pairs with the lvrged_factory_job action=watch tool (widget + done/stuck
# notifications) — this is the plain-bash version for any terminal.
ENDPOINT="${1:-http://127.0.0.1:8188}"
BASE="${ENDPOINT%/}"
echo "watching $BASE — ctrl-c to stop"
STUCK_SINCE=""
while true; do
  P=$(curl -s --max-time 6 "$BASE/progress" 2>/dev/null)
  Q=$(curl -s --max-time 6 "$BASE/queue" 2>/dev/null)
  TS=$(date +%H:%M:%S)
  if [ -z "$P" ]; then
    echo "$TS  ⚠ unreachable — is ComfyUI up?"
    STUCK_SINCE=""
  else
    FRAC=$(echo "$P" | python3 -c "import json,sys; print(json.load(sys.stdin).get('progress',0))" 2>/dev/null || echo 0)
    PEND=$(echo "$Q" | python3 -c "import json,sys; d=json.load(sys.stdin); print(len(d.get('queue_pending',[])))" 2>/dev/null || echo 0)
    PCT=$(python3 -c "print(round(float('$FRAC')*100))" 2>/dev/null || echo 0)
    BAR=$(python3 -c "
f=float('$FRAC'); n=max(0,min(10,round(f*10)))
print('▓'*n + '░'*(10-n))
" 2>/dev/null)
    if [ "$PCT" = "100" ]; then
      echo "$TS  ✓ 100% — decode/assemble (check /history)"
    else
      echo "$TS  $PCT% $BAR  pending:$PEND"
    fi
  fi
  sleep 8
done
