#!/usr/bin/env bash
# Paint pass for one finished space job (16 Oct 2026, operator: "texture them as well using Nano Banana Pro or GPT Image 2 +
# our paint technique"): render the craft from 8-10 sides, an image model repaints each render, the Pixel Match painter projects
# the pictures back (forge-repaint on gex44). Result = a static one-material PAINTED COPY next to the game model (which keeps
# its moving parts and Paint recolour). usage: tools/space/paint_ship.sh <slug> [gpt|nb2]
#   gpt = GPT Image 2 through Codex (subscription) via the local spool worker -> jobs/<slug>-v1/painted/ + next card version
#   nb2 = Nano Banana 2 (Google grant) -> jobs/<slug>-v1/painted-nb2/ only (side-by-side comparison, no card)
# JOBDIR = a scratch job copy (pilots); NOCARD=1 = no card version.
set -euo pipefail
S=$1; ED=${2:-gpt}
ROOT=$(cd "$(dirname "$0")/../.." && pwd); J=${JOBDIR:-$ROOT/jobs/$S-v1}
RUN=/opt/forge-repaint/runs/space-20261016; L=/tmp/space-20261016/paint; mkdir -p "$L"
if [ "$ED" = gpt ]; then K=$S; SUB=painted; else K=$S-$ED; SUB=painted-$ED; fi
python3 "$ROOT/tools/space/paint_prep.py" "$J" "$L/$K.glb" "$L/$K.guide.json" >/dev/null
ssh gex44 "mkdir -p $RUN/in"
scp -q "$L/$K.glb" "$L/$K.guide.json" "gex44:$RUN/in/"
scp -q "$ROOT/tools/space/paint_ship_remote.py" "gex44:$RUN/paint_ship_remote.py"
if [ "$ED" = gpt ] && ! pgrep -f '[g]pt-spool-worker.*spool-space' >/dev/null; then   # one worker answers this batch's GPT pictures
  setsid nohup ~/forge-build/forge-repaint/bin/gpt-spool-worker --spool /opt/forge-repaint/spool-space --jobs "${SPOOL_JOBS:-6}" \
    --idle 1800 >> /tmp/space-20261016/spool-worker.log 2>&1 < /dev/null &
fi
ssh gex44 "/opt/forge-repaint/venv/bin/python $RUN/paint_ship_remote.py --dir $RUN --key $K --editor $ED" | tail -1 > "$J/$SUB-row.json" || true
cat "$J/$SUB-row.json"
python3 -c "import json,sys; r=json.load(open('$J/$SUB-row.json')); sys.exit(0 if r.get('applied') and not r.get('error') else 3)" || exit 3
mkdir -p "$J/$SUB"
scp -q "gex44:$RUN/out/$K/painted.glb" "gex44:$RUN/out/$K/sheet.jpg" "gex44:$RUN/out/$K/report.json" "$J/$SUB/"
if [ "$ED" = gpt ] && [ -z "${NOCARD:-}" ]; then python3 "$ROOT/tools/space/paint_card.py" "$J" "$ED"; "$ROOT/tools/space/paint_compare.sh" "$S" || true; fi
