#!/usr/bin/env bash
# monitor-panes.sh — capture recent output from all other tmux panes in a window.
# Output is plain text (no markdown) suitable for iMessage relay.
set -euo pipefail

lines=15
window=""
session=""

while [[ $# -gt 0 ]]; do
  case "$1" in
    --lines)  lines="$2"; shift 2 ;;
    --window) window="$2"; shift 2 ;;
    --session) session="$2"; shift 2 ;;
    *) echo "Unknown arg: $1" >&2; exit 1 ;;
  esac
done

# Resolve current session/window if not provided
if [[ -z "$session" ]]; then
  session="$(tmux display-message -p '#{session_name}' 2>/dev/null || true)"
fi
if [[ -z "$window" ]]; then
  window="$(tmux display-message -p '#{window_index}' 2>/dev/null || true)"
fi

if [[ -z "$session" || -z "$window" ]]; then
  echo "ERROR: not inside a tmux session and no --session/--window given" >&2
  exit 1
fi

target_window="${session}:${window}"

# Caller PIDs to exclude (this script and its parent shell)
my_pid=$$
parent_pid=${PPID:-0}

# Enumerate panes: index, command, pid
pane_info="$(tmux list-panes -t "$target_window" \
  -F '#{pane_index} #{pane_current_command} #{pane_pid}')"

first=true

while IFS=' ' read -r idx cmd pid; do
  # Skip the pane running this script
  if [[ "$pid" == "$my_pid" || "$pid" == "$parent_pid" ]]; then
    continue
  fi

  # Also check if caller is a descendant of this pane's shell
  if ps -o ppid= -p "$my_pid" 2>/dev/null | grep -qw "$pid"; then
    continue
  fi

  if $first; then
    first=false
  else
    echo ""
  fi

  echo "PANE ${idx} (${cmd}) PID ${pid}"

  captured="$(tmux capture-pane -p -t "${target_window}.${idx}" -S "-${lines}" 2>/dev/null || true)"

  if [[ -n "$captured" ]]; then
    echo "$captured"
  else
    echo "(no output)"
  fi
done <<< "$pane_info"

if $first; then
  echo "No other panes found in ${target_window}."
fi
