#!/bin/bash
# One article at a time, in most-linked order, with the queue kept short so a
# deploy or a failure costs one article rather than a batch.
SD="$1"; A=$(cat "$SD/token.txt"); done_n=0; drew=0
while read -r id; do
  [ -z "$id" ] && continue
  job=$(curl -s -X POST "https://pedshub.com/api/articles/$id/illustrate" -H "Authorization: Bearer $A" \
        | python3 -c "import json,sys;print(json.load(sys.stdin).get('job_id',''))" 2>/dev/null)
  [ -z "$job" ] && { echo "$id: could not queue"; continue; }
  for _ in $(seq 1 60); do
    sleep 10
    st=$(curl -s -H "Authorization: Bearer $A" "https://pedshub.com/api/articles/job/$job" \
         | python3 -c "
import json,sys
d=json.load(sys.stdin)
last=[s.get('message','') for s in (d.get('steps') or [])][-1:]
print(d.get('status',''), '|', last[0] if last else '')" 2>/dev/null)
    case "$st" in completed*|failed*) echo "$id: $st"; break;; esac
  done
  done_n=$((done_n+1))
  echo "--- $done_n articles processed"
done < "$SD/to_illustrate.txt"
echo "FINISHED: $done_n articles"
