#!/usr/bin/env bash
# Poll a tmux pane until a success or error pattern appears.
#
# Usage: wait-for-pane.sh <target> <timeout_secs> <success_pattern> [error_pattern] [--send-enter]
#
# Arguments:
#   target          tmux target pane (e.g. mysession:server)
#   timeout_secs    max seconds to wait
#   success_pattern extended grep pattern (case-insensitive) for success
#   error_pattern   extended grep pattern (case-insensitive) for failure (optional)
#   --send-enter    send Enter to the pane once before polling (useful for dojo)
#
# Exit codes: 0 = success pattern matched, 1 = error/timeout
# Outputs last 20 lines of pane on error or timeout.

set -euo pipefail

# Parse --send-enter flag from any position, remaining positional args are target/timeout/patterns
SEND_ENTER=false
POSITIONAL=()
for arg in "$@"; do
  if [ "$arg" = "--send-enter" ]; then
    SEND_ENTER=true
  else
    POSITIONAL+=("$arg")
  fi
done

TARGET="${POSITIONAL[0]:?tmux target required}"
TIMEOUT="${POSITIONAL[1]:?timeout required}"
SUCCESS_PAT="${POSITIONAL[2]:?success pattern required}"
ERROR_PAT="${POSITIONAL[3]:-}"

INTERVAL=1
ELAPSED=0

if [ "$SEND_ENTER" = "true" ]; then
  tmux send-keys -t "=${TARGET}" "" Enter 2>/dev/null || true
  sleep 1
fi

while [ "$ELAPSED" -lt "$TIMEOUT" ]; do
  OUTPUT=$(tmux capture-pane -t "=${TARGET}" -p -S -30 2>/dev/null || true)

  if echo "$OUTPUT" | grep -qiE "$SUCCESS_PAT"; then
    echo "OK"
    exit 0
  fi

  if [ -n "$ERROR_PAT" ] && echo "$OUTPUT" | grep -qiE "$ERROR_PAT"; then
    echo "ERROR"
    echo "$OUTPUT" | tail -20
    exit 1
  fi

  sleep "$INTERVAL"
  ELAPSED=$((ELAPSED + INTERVAL))
done

echo "TIMEOUT after ${TIMEOUT}s"
tmux capture-pane -t "=${TARGET}" -p -S -30 | tail -20
exit 1
