#!/bin/bash
# Space batch finisher (16 Oct 2026): every finished job (rc.txt present) -> pack (tools/vehicles/pack.sh: raw kept as
# <slug>-raw.glb, KTX2 + Draco) -> tools/space/check_space.py -> card (import_space.py) -> browse/spaceships.json -> paint queue
# -> rebuild + republish the review page. Loops until the queue says ALL DONE and every job is finished.
# Order file /tmp/space-20261016/order.txt ("<slug> <pen>"); log /tmp/space-20261016/finish.log.
cd ~/forge-build/forge-assets; L=/tmp/space-20261016
publish() {   # the review page goes up after every new card (operator law: update the spike as items land)
  [ -f tools/space/build_spike_space.py ] || return 0
  python3 tools/space/build_spike_space.py "$(TZ=Europe/Paris date '+%-d %b %H:%M') CET" >> $L/spike.log 2>&1 &&
    bash tools/space/publish_spike_space.sh >> $L/spike.log 2>&1
}
while true; do
  for s in $(cut -d' ' -f1 $L/order.txt); do
    J=jobs/$s-v1
    [ -f $J/rc.txt ] || continue
    [ -f $J/.finished ] && continue
    if [ ! -f $J/$s.glb ]; then printf '%s NO GLB rc=%s %s\n' $s "$(cat $J/rc.txt)" "$(date -u +%H:%M)" >> $L/finish.log; touch $J/.finished; continue; fi
    if ! tools/vehicles/pack.sh $J >> $L/finish.log 2>&1; then printf '%s PACK FAILED\n' $s >> $L/finish.log; touch $J/.finished; continue; fi
    python3 tools/space/check_space.py $J > $J/check.json 2>&1; ok=$?
    if [ $ok = 0 ]; then
      python3 tools/space/import_space.py $J >> $L/finish.log 2>&1 && python3 tools/space/manifest_space.py >> $L/finish.log 2>&1 &&
        echo $s >> $L/paint-queue.txt && publish
    fi
    printf '%s check=%s %s\n' $s $ok "$(date -u +%H:%M)" >> $L/finish.log
    touch $J/.finished
  done
  n=$(cut -d' ' -f1 $L/order.txt | while read s; do [ -f jobs/$s-v1/.finished ] && echo; done | wc -l)
  grep -q 'ALL DONE' $L/queue.log 2>/dev/null && [ "$n" -ge "$(wc -l < $L/order.txt)" ] && break
  sleep 30
done
printf 'FINISHER DONE %s\n' "$(date -u +%H:%M)" >> $L/finish.log
