#!/usr/bin/env bash
# open-log-window.sh — (re)open a read-only tmux tail window for a dev-server log
# in the run-owned session, WITHOUT touching the dev-server process. Idempotent:
# an existing same-name window is replaced with a fresh tail. Used by
# `mm-harness logs --window` to recover a window that was closed while Metro/webpack
# keeps running.
#
# Args: --window <name> --log <path> [--runtime-dir <dir>]
# Exit: 0 opened; 1 no run-owned session / no tmux / log missing (teaches); 2 bad args.
set -euo pipefail

WINDOW=""
LOG=""
RUNTIME_DIR=""
require_value() { [ "$#" -ge 2 ] || { echo "Missing value for $1" >&2; exit 2; }; }
while [ "$#" -gt 0 ]; do
  case "$1" in
    --window) require_value "$@"; WINDOW="$2"; shift 2 ;;
    --log) require_value "$@"; LOG="$2"; shift 2 ;;
    --runtime-dir) require_value "$@"; RUNTIME_DIR="$2"; shift 2 ;;
    -h|--help) echo "Usage: open-log-window.sh --window <name> --log <path> [--runtime-dir <dir>]"; exit 0 ;;
    *) echo "Unknown arg: $1" >&2; exit 2 ;;
  esac
done
[ -n "$WINDOW" ] && [ -n "$LOG" ] || { echo "open-log-window: --window and --log are required" >&2; exit 2; }

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
# shellcheck disable=SC1091
for _src in "$SCRIPT_DIR/tmux-session.sh" "$SCRIPT_DIR/lib/tmux-session.sh"; do
  [ -f "$_src" ] && { . "$_src"; break; }
done
unset _src

if ! command -v tmux >/dev/null 2>&1; then
  echo "open-log-window: tmux is not installed; cannot open a log window." >&2
  echo "  Next: tail the log directly — mm-harness logs --full" >&2
  exit 1
fi
if [ ! -f "$LOG" ]; then
  echo "open-log-window: no log at $LOG (dev server not started for this checkout)." >&2
  echo "  Next: start it — mm-harness launch" >&2
  exit 1
fi
session=""
command -v resolve_run_tmux_session >/dev/null 2>&1 && session="$(resolve_run_tmux_session "$RUNTIME_DIR")"
if [ -z "$session" ] || ! tmux has-session -t "=$session" 2>/dev/null; then
  echo "open-log-window: no run-owned tmux session to place the window in." >&2
  echo "  Next: set RECIPE_TMUX_SESSION=<session>, or configure agentic-runtime.json session, then retry" >&2
  exit 1
fi

tmux kill-window -t "${session}:${WINDOW}" 2>/dev/null || true
log_q="$(printf '%q' "$LOG")"
tmux new-window -d -t "$session" -n "$WINDOW" "exec tail -n +1 -F $log_q"
echo "log window → tmux ${session}:${WINDOW}" >&2
