#!/usr/bin/env bash
# tmux-viewer — open a read-only tmux window tailing the Metro log, but ONLY in a
# session that belongs to this run. Sourced by start-metro.sh; kept separate so
# the session-resolution rule (the part that must never leak into a user session)
# is unit-testable in isolation.
#
# Contract: never create a window in "whatever session happens to be attached".
# Outside a tmux client `tmux display-message -p '#S'` returns the last-attached
# session (e.g. the user's own), which would land the window — and its `tail -F` —
# in an unrelated session that outlives the run. When no run-owned session can be
# resolved, skip the viewer entirely (Metro still runs detached to the log).
#
# Inputs (env/args): $1 = metro log path; PORT, LOG_DIR, and optional `slot` from
# the caller.

# Session resolution (RECIPE_TMUX_SESSION → agentic-runtime.json session). Sourced
# relative to this lib; harness-path fallback for the installed layout where shared
# libs live beside this file.
_tv_dir="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
# shellcheck disable=SC1091
for _tv_src in "$_tv_dir/tmux-session.sh" "$_tv_dir/../../shared/tmux-session.sh"; do
  [ -f "$_tv_src" ] && { . "$_tv_src"; break; }
done
unset _tv_src _tv_dir

# shellcheck disable=SC2329  # sourced by start-metro.sh; also sourced by tests.
start_viewer_window() {
  local metro_log="$1"
  command -v tmux >/dev/null 2>&1 || return 0
  local window="metro-${PORT}"
  local metro_tmux="$LOG_DIR/metro.tmux"
  # The orchestrator names the session; the harness only populates windows. No
  # slot-number derivation — the name comes from the run-owned session ladder.
  local session
  session="$(resolve_run_tmux_session "$LOG_DIR")"
  # No run-owned session → skip the viewer; no orphaned tail-window is left behind.
  { [ -n "$session" ] && tmux has-session -t "=$session" 2>/dev/null; } || return 0
  # Hygiene: close stale metro-<port> windows in this session whose port has no
  # live listener — a previous run's window left tailing a dead log. The current
  # window is (re)created below, so skip it here.
  if command -v lsof >/dev/null 2>&1; then
    tmux list-windows -t "$session" -F '#{window_name}' 2>/dev/null | while IFS= read -r _win; do
      [ "$_win" = "$window" ] && continue
      case "$_win" in
        metro-*) : ;;
        *) continue ;;
      esac
      _p="${_win#metro-}"
      case "$_p" in ''|*[!0-9]*) continue ;; esac
      if ! lsof -nP -iTCP:"$_p" -sTCP:LISTEN -t >/dev/null 2>&1; then
        tmux kill-window -t "${session}:${_win}" >/dev/null 2>&1 || true
      fi
    done
  fi
  tmux kill-window -t "${session}:${window}" >/dev/null 2>&1 || true
  tmux new-window -d -t "$session" -n "$window" "exec tail -n +1 -F $(printf '%q' "$metro_log")"
  printf '%s:%s\n' "$session" "$window" > "$metro_tmux"
  printf 'Metro log viewer → tmux %s:%s\n' "$session" "$window" >&2
}
