#!/bin/bash
# One-off: render the 6 writer-bakeoff scripts with VibeVoice, then rebuild the feed.
# Same GPU discipline as daily_podcast.sh: stop vLLM containers, render, restart
# VERIFIED with an EXIT trap backstop.
set -Eeuo pipefail
RF=/home/mgrim/research-feed
CMP=$RF/podcast/comparison
RFPY=$RF/.venv/bin/python
VVPY=/home/mgrim/vibevoice-env/bin/python

VLLM_CONTAINERS=$(docker ps --format '{{.Names}} {{.Image}}' | awk 'tolower($0) ~ /vllm/ {print $1}')

restart_vllm() {
  local failed=0
  for c in $VLLM_CONTAINERS; do
    local up=0 i
    for i in 1 2 3; do
      docker start "$c" >/dev/null 2>&1 || true
      sleep 3
      if [ "$(docker inspect -f '{{.State.Running}}' "$c" 2>/dev/null)" = "true" ]; then
        up=1; break
      fi
      sleep 10
    done
    if [ "$up" -ne 1 ]; then
      failed=1
      echo "!!! FAILED to restart vLLM container '$c' after 3 attempts — SERVICE DOWN" >&2
    fi
  done
  return $failed
}
finish() { restart_vllm || echo "!!! EXIT-trap restart reported failure — check containers NOW" >&2; }
trap finish EXIT

echo "=== render start $(date -u +%FT%TZ) ==="
for c in $VLLM_CONTAINERS; do docker stop "$c"; done

# scripts to render come in as args; default = the original 6 mono scripts
SCRIPTS=("$@")
if [ ${#SCRIPTS[@]} -eq 0 ]; then
  SCRIPTS=($CMP/thu_local.txt $CMP/thu_claude.txt
           $CMP/fri_local.txt $CMP/fri_claude.txt
           $CMP/sat_local.txt $CMP/sat_claude.txt)
fi
$VVPY $RF/podcast/tts_vibevoice.py "${SCRIPTS[@]}"

restart_vllm
trap - EXIT

$RFPY -c "
import sys; sys.path.insert(0, '$RF/podcast')
from make_episode import rebuild_rss
print(rebuild_rss('https://edgexpert-83b2.tail6663b0.ts.net'), 'items in feed')"
echo "=== render done $(date -u +%FT%TZ) ==="
