#!/bin/bash
# Paint pass loop (16 Oct 2026): takes carded crafts from /tmp/space-20261016/paint-queue.txt, ${PAINT_P:-2} at a time, through
# tools/space/paint_ship.sh (GPT Image 2 by default), then manifest + review page. A craft is tried once (.painted marker);
# /tmp/space-20261016/STOP-PAINT = take nothing new. Log /tmp/space-20261016/paint.log.
cd ~/forge-build/forge-assets; L=/tmp/space-20261016; ED=${PAINT_EDITOR:-gpt}
running=()
while true; do
  [ -f $L/STOP-PAINT ] && break
  for s in $(cat $L/paint-queue.txt 2>/dev/null); do
    J=jobs/$s-v1
    [ -e $J/.painted ] && continue
    while [ "$(jobs -rp | wc -l)" -ge "${PAINT_P:-2}" ]; do sleep 10; done
    [ -f $L/STOP-PAINT ] && break   # 16 Oct 2026: checked only between rounds, the loop painted 13 more ships after a stop
    touch $J/.painted
    ( printf '%s paint start %s\n' $s "$(date -u +%H:%M)" >> $L/paint.log
      if tools/space/paint_ship.sh $s $ED >> $L/paint-$s.log 2>&1; then
        python3 tools/space/manifest_space.py >> $L/paint.log 2>&1
        [ -f tools/space/build_spike_space.py ] && 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
        printf '%s painted %s\n' $s "$(date -u +%H:%M)" >> $L/paint.log
      else printf '%s paint FAILED (see paint-%s.log) %s\n' $s $s "$(date -u +%H:%M)" >> $L/paint.log; fi ) &
  done
  grep -q 'FINISHER DONE' $L/finish.log 2>/dev/null && [ "$(jobs -rp | wc -l)" = 0 ] &&
    [ -z "$(for s in $(cat $L/paint-queue.txt 2>/dev/null); do [ -e jobs/$s-v1/.painted ] || echo $s; done)" ] && break
  sleep 20
done
wait
printf 'PAINT LOOP DONE %s\n' "$(date -u +%H:%M)" >> $L/paint.log
