#!/usr/bin/env bash
set -euo pipefail

SCRIPT_DIR=$(cd -- "$(dirname -- "$0")" && pwd)
SEND_MESSAGE="$SCRIPT_DIR/send-message.sh"
AGENT_SEND="$SCRIPT_DIR/agent-send.sh"
SOCKET="mosaic-test-$RANDOM-$$"
TARGET="target-$RANDOM"
DEFAULT_TARGET="default-target-$RANDOM"
TMPDIR=$(mktemp -d)
trap 'tmux -L "$SOCKET" kill-server >/dev/null 2>&1 || true; tmux kill-session -t "$DEFAULT_TARGET" >/dev/null 2>&1 || true; rm -rf "$TMPDIR"' EXIT

fail() {
  echo "FAIL: $*" >&2
  exit 1
}

require_tmux() {
  command -v tmux >/dev/null 2>&1 || fail "tmux is required"
}

capture_named() {
  tmux -L "$SOCKET" capture-pane -t "=$TARGET:0.0" -p
}

capture_default() {
  tmux capture-pane -t "=$DEFAULT_TARGET:0.0" -p
}

require_tmux

tmux -L "$SOCKET" new-session -d -s "$TARGET" -c "$TMPDIR" 'bash --noprofile --norc -i'
tmux new-session -d -s "$DEFAULT_TARGET" -c "$TMPDIR" 'bash --noprofile --norc -i'

"$SEND_MESSAGE" -L "$SOCKET" -t "=$TARGET" -m "named socket hello" >/tmp/send-message-named.out
sleep 0.2
capture_named | grep -qF "named socket hello" || fail "send-message.sh did not deliver to named socket"
if capture_default | grep -qF "named socket hello"; then
  fail "send-message.sh leaked named-socket message to default tmux server"
fi

"$AGENT_SEND" -L "$SOCKET" -S "tester:source" -s "=$TARGET" -m "agent socket hello" >/tmp/agent-send-named.out
sleep 0.2
capture_named | grep -qF "[tester:source ->" || fail "agent-send.sh did not include preamble"
capture_named | grep -qF "agent socket hello" || fail "agent-send.sh did not deliver to named socket"
if capture_default | grep -qF "agent socket hello"; then
  fail "agent-send.sh leaked named-socket message to default tmux server"
fi

echo "ok - named tmux socket send tools"
