#!/usr/bin/env bash
# tmux-session — resolve the run-owned tmux session a log-tail window belongs in.
#
# Responsibility split: the orchestrator (farmslot) NAMES the session; the harness
# only POPULATES windows inside it. The name is therefore never guessed from the
# slot number — a renamed pool or a manual run would land the window (and its
# tail -F) in the wrong place. Resolution ladder, first hit wins:
#   1. RECIPE_TMUX_SESSION            — the orchestrator's explicit hand-off.
#   2. agentic-runtime.json `session` — the prepared checkout's recorded session.
# Prints the resolved name (empty when none). Callers still gate on has-session
# before creating a window.

# shellcheck disable=SC2329  # sourced by leaves and by contract tests.
resolve_run_tmux_session() {
  local runtime_dir="${1:-}" ctx="" session=""
  if [ -n "${RECIPE_TMUX_SESSION:-}" ]; then
    printf '%s\n' "$RECIPE_TMUX_SESSION"
    return 0
  fi
  ctx="${RECIPE_RUNTIME_CONTEXT:-}"
  if [ -z "$ctx" ] && [ -n "$runtime_dir" ]; then ctx="$runtime_dir/agentic-runtime.json"; fi
  if [ -n "$ctx" ] && [ -f "$ctx" ] && command -v node >/dev/null 2>&1; then
    session="$(RUN_TMUX_CTX="$ctx" node -e 'try{const d=JSON.parse(require("fs").readFileSync(process.env.RUN_TMUX_CTX,"utf8"));const s=d&&d.session;if(s!==undefined&&s!==null&&s!=="")process.stdout.write(String(s));}catch{}' 2>/dev/null || true)"
    if [ -n "$session" ]; then
      printf '%s\n' "$session"
      return 0
    fi
  fi
  return 0
}
