#!/usr/bin/env bash
# Stop the sx-loops tmux session. Optionally (--clean) also remove the
# per-language git worktrees. Loops stop immediately; in-progress iterations
# commit whatever they have; nothing is pushed that wasn't already.
set -euo pipefail

SESSION="sx-loops"
WORKTREE_BASE="/root/rose-ash-loops"
CLEAN=0

for arg in "$@"; do
  case "$arg" in
    --clean) CLEAN=1 ;;
    *) echo "Unknown arg: $arg"; exit 2 ;;
  esac
done

if tmux has-session -t "$SESSION" 2>/dev/null; then
  WINDOWS=$(tmux list-windows -t "$SESSION" -F '#W')
  for w in $WINDOWS; do
    tmux send-keys -t "$SESSION:$w" "/exit" C-m 2>/dev/null || true
  done
  echo "Sent /exit to all windows. Waiting 5s for clean shutdown..."
  sleep 5
  tmux kill-session -t "$SESSION"
  echo "Killed tmux session '$SESSION'."
else
  echo "No sx-loops tmux session running."
fi

if [ "$CLEAN" = "1" ]; then
  cd "$(dirname "$0")/.."
  for lang in lua prolog forth erlang haskell js hs smalltalk common-lisp apl ruby tcl; do
    wt="$WORKTREE_BASE/$lang"
    if [ -d "$wt" ]; then
      git worktree remove --force "$wt" 2>/dev/null || rm -rf "$wt"
      echo "Removed worktree: $wt"
    fi
  done
  git worktree prune
  echo "Worktree branches (loops/<lang>) are preserved. Delete manually if desired:"
  echo "  git branch -D loops/lua loops/prolog loops/forth loops/erlang loops/haskell loops/js loops/hs loops/smalltalk loops/common-lisp loops/apl loops/ruby loops/tcl"
fi
