#!/bin/bash
# VERIFY SWEEP (A, 28 Oct; the user: "rate those first with high priority right now"): every kill in the list through
# _tools/verify_kill.cjs, one worker per weapon (one page load per weapon), P workers at a time through the render slots.
#   bash _tools/verify_sweep.sh [list=/Volumes/Workspace/Scratch/coord/verify251.txt] [out=/Volumes/Workspace/Scratch/coord/verify] [P=2]
# Output: <out>/results.jsonl (one JSON line per kill), <out>/<key>.jpg, <out>/<weapon>_sheet.jpg, <out>/progress.log
cd "$(dirname "$0")/.." || exit 1
LIST=${1:-/Volumes/Workspace/Scratch/coord/verify251.txt}; OUT=${2:-/Volumes/Workspace/Scratch/coord/verify}; P=${3:-2}
mkdir -p "$OUT"
ORDER="pump fists revolver cluster flamer minigun pistol beam golden smg bouncer handcannon"
REST=$(cut -d. -f1 "$LIST" | sort | uniq -c | sort -rn | awk '{print $2}')
WS=""; for w in $ORDER $REST; do case " $WS " in *" $w "*) ;; *) grep -q "^$w\." "$LIST" && WS="$WS $w";; esac; done
echo "$(date +%H:%M:%S) START weapons:$WS P=$P" >> "$OUT/progress.log"
run_one() { w=$1; keys=$(grep "^$w\." "$LIST" | paste -sd, -); n=$(grep -c "^$w\." "$LIST"); t0=$(date +%s)
  bash _tools/render_slot.sh node _tools/verify_kill.cjs "$w" "$keys" "$OUT" > "$OUT/log_$w.txt" 2>&1; rc=$?
  # (DONE only with rc 0 AND a row for every kill; anything else is FAILED, never a silent DONE)
  rows=$(grep -c "\"w\":\"$w\"" "$OUT/results.jsonl" 2>/dev/null); rows=${rows:-0}
  if [ "$rc" != 0 ] || [ "$rows" -lt "$n" ]; then echo "$(date +%H:%M:%S) FAILED $w $rows/$n rows rc=$rc (see log_$w.txt)" >> "$OUT/progress.log"; else echo "$(date +%H:%M:%S) DONE $w $n kills $(( $(date +%s) - t0 ))s" >> "$OUT/progress.log"; fi; }
export -f run_one; export LIST OUT
printf '%s\n' $WS | xargs -P "$P" -I{} bash -c 'run_one {}'
# re-queue every weapon that FAILED in this run, once, one at a time
for w in $(grep " FAILED " "$OUT/progress.log" | awk -v s="$(head -c 0 /dev/null)" '{print $3}' | sort -u); do grep -q "^$w\." "$LIST" && run_one "$w"; done
echo "$(date +%H:%M:%S) ALL DONE" >> "$OUT/progress.log"
