#!/usr/bin/env bash
# Push a URL to the viewport for the current session.
# Usage: push-view /path/to/page.html
#
# Auto-detects which session we're in. Just works.

URL="${1:?usage: push-view /path}"

# Detect session: env var first (set by run-session.sh — both spellings,
# see docs/environment.md), then tmux, then main
SESSION="${WOLTSPACE_WOLT_SESSION:-${WOLT_SESSION:-}}"
if [ -z "$SESSION" ]; then
  SESSION=$(tmux display-message -p '#S' 2>/dev/null || true)
fi
SESSION="${SESSION:-main}"

# The control plane that owns this session — see `notify` for where the stamp
# comes from. The literal is the container's baked-in default only.
API="${WOLTSPACE_API:-http://localhost:7777}"

# `curl -s` swallows a connection refusal, and the old unconditional echo below
# then reported a push that never happened — the single most misleading thing a
# tool can do to an agent checking its own work. Fail loudly instead.
if ! RESPONSE=$(curl -sS -f -X POST "${API}/current?session=${SESSION}" \
  -H 'Content-Type: application/json' \
  -d "{\"url\":\"${URL}\"}" 2>&1); then
  echo "[viewport:${SESSION}] failed to reach ${API}: ${RESPONSE}" >&2
  exit 1
fi

echo "[viewport:${SESSION}] → ${URL}"
