#!/usr/bin/env bash
# Stop the sx-hs-e tmux session. Optionally (--clean) remove worktrees.
set -euo pipefail

SESSION="sx-hs-e"
WORKTREE_BASE="/root/rose-ash-e"
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..."
  sleep 5
  tmux kill-session -t "$SESSION"
  echo "Killed tmux session '$SESSION'."
else
  echo "No $SESSION tmux session running."
fi

if [ "$CLEAN" = "1" ]; then
  cd "$(dirname "$0")/.."
  for item in e36 e37 e38 e39 e40; do
    wt="$WORKTREE_BASE/$item"
    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 "Branches preserved. Remove manually if desired:"
  echo "  git branch -D hs-e36-websocket hs-e37-tokenizer hs-e38-sourceinfo hs-e39-webworker hs-e40-fetch"
fi
