#!/usr/bin/env bash
# monitor-loop.sh — periodically run monitor-panes.sh and relay output via Sendblue (iMessage).
set -euo pipefail

SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
INTERVAL=240
# Phone may be supplied either via --to (parsed below) or, as a fallback,
# the SENDBLUE_OWN_NUMBER env var. Resolve AFTER arg parsing so --to can
# override an unset env var.
PHONE=""
LINES=10
SESSION_ARG=""
WINDOWS=()
SENTINEL="/tmp/monitor-paused"
PIDFILE="/tmp/monitor-loop.pid"
MAX_MSG=1500

while [[ $# -gt 0 ]]; do
  case "$1" in
    --interval) INTERVAL="$2"; shift 2 ;;
    --to)       PHONE="$2";    shift 2 ;;
    --lines)    LINES="$2";    shift 2 ;;
    --session)  SESSION_ARG="$2"; shift 2 ;;
    --window)   WINDOWS+=("$2");  shift 2 ;;
    *) echo "Unknown arg: $1" >&2; exit 1 ;;
  esac
done

PHONE="${PHONE:-${SENDBLUE_OWN_NUMBER:?SENDBLUE_OWN_NUMBER must be set or --to <phone> provided}}"

: "${SENDBLUE_API_KEY_ID:?SENDBLUE_API_KEY_ID not set}"
: "${SENDBLUE_API_SECRET_KEY:?SENDBLUE_API_SECRET_KEY not set}"

send_msg() {
  local msg="$1"
  if [[ ${#msg} -gt $MAX_MSG ]]; then
    msg="${msg:0:$MAX_MSG}...(truncated)"
  fi
  local payload
  payload=$(jq -n --arg num "$PHONE" --arg content "$msg" \
    '{"number":$num,"content":$content}')
  curl -sS -X POST "https://api.sendblue.co/api/send-message" \
    -H "Content-Type: application/json" \
    -H "sb-api-key-id: ${SENDBLUE_API_KEY_ID}" \
    -H "sb-api-secret-key: ${SENDBLUE_API_SECRET_KEY}" \
    -d "$payload" >/dev/null 2>&1 || true
}

cleanup() {
  send_msg "Monitor stopped."
  rm -f "$PIDFILE"
  exit 0
}
trap cleanup SIGINT SIGTERM

echo $$ > "$PIDFILE"

# If no windows specified, default to current window
if [[ ${#WINDOWS[@]} -eq 0 ]]; then
  WINDOWS=("$(tmux display-message -p '#{window_name}' 2>/dev/null || echo '')")
fi

send_msg "Monitor started. Reporting every ${INTERVAL}s. Windows: ${WINDOWS[*]}"

while true; do
  sleep "$INTERVAL"

  if [[ -f "$SENTINEL" ]]; then
    send_msg "Monitor paused."
    rm -f "$PIDFILE"
    exit 0
  fi

  output=""
  for win in "${WINDOWS[@]}"; do
    pane_args=(--lines "$LINES")
    [[ -n "$SESSION_ARG" ]] && pane_args+=(--session "$SESSION_ARG")
    [[ -n "$win" ]] && pane_args+=(--window "$win")
    win_output=$("${SCRIPT_DIR}/monitor-panes.sh" "${pane_args[@]}" 2>&1 || true)
    if [[ -n "$win_output" ]]; then
      output+="-- ${win} --
${win_output}

"
    fi
  done

  if [[ -z "$output" ]]; then
    output="(no pane output captured)"
  fi
  send_msg "$output"
done
