#!/usr/bin/env bash
# ── Tower Session ──────────────────────────────────────────────────────
# Two-pane tmux session: Hermes ↔ Timmy conversation + status dashboard
#
# Left pane (65%):  Hermes loop — drives the conversation, shows both sides
# Right pane (35%): Status dashboard — loop health, message stats, infra
#
# Communication: file-based message passing via ~/.tower/
# Self-healing: watchdog checks both panes, restarts if dead
#
# Source-controlled: gitea/rockachopa/hermes-config
# ───────────────────────────────────────────────────────────────────────

set -euo pipefail

SESSION="tower"
TOWER_DIR="$HOME/.tower"
TOWER_BIN="$HOME/hermes-config/bin"
export PATH="$HOME/.local/bin:$HOME/.hermes/bin:/usr/local/bin:$PATH"

# ── Setup ─────────────────────────────────────────────────────────────
mkdir -p "$TOWER_DIR"

# If session already exists, just attach
if tmux has-session -t "$SESSION" 2>/dev/null; then
    exec tmux attach -t "$SESSION"
fi

# ── Create session with two panes ─────────────────────────────────────
# Left pane: Hermes conversation loop (drives the conversation, shows both sides)
tmux new-session -d -s "$SESSION" -n "tower" -x 200 -y 50

# Right pane: Status dashboard (35% width)
tmux split-window -h -p 35 -t "$SESSION:1.1"

# Set pane titles
tmux select-pane -t "$SESSION:1.1" -T "⚡ Tower"
tmux select-pane -t "$SESSION:1.2" -T "📊 Status"

# ── Start the loops ──────────────────────────────────────────────────
# Pane 1: Hermes loop (conversation driver — shows Hermes & Timmy messages)
tmux send-keys -t "$SESSION:1.1" \
    "$TOWER_BIN/tower-hermes.sh" Enter

# Pane 2: Status dashboard
tmux send-keys -t "$SESSION:1.2" \
    "$TOWER_BIN/tower-status.sh" Enter

# Hidden window 2: Timmy loop (no need to watch — status pane monitors health)
tmux new-window -t "$SESSION" -n "timmy-bg"
tmux send-keys -t "$SESSION:2" \
    "$TOWER_BIN/tower-timmy.sh" Enter

# Back to window 1, focus conversation pane
tmux select-window -t "$SESSION:1"
tmux select-pane -t "$SESSION:1.1"

# ── Attach ────────────────────────────────────────────────────────────
exec tmux attach -t "$SESSION"
