#!/bin/bash
# Launch tmux with 4 panes: orchestrator + 3 agent log watchers
# Usage: bash docs/run2-14022026/start.sh [iterations]
# NOTE: Run this from a REGULAR terminal, not from inside Claude Code

set -euo pipefail
unset CLAUDECODE 2>/dev/null || true

RUN_DIR="$(cd "$(dirname "$0")" && pwd)"
LOG_DIR="$RUN_DIR/logs"
ITERATIONS="${1:-100}"

mkdir -p "$LOG_DIR"

SESSION="run2"

# Kill existing session if any
tmux kill-session -t "$SESSION" 2>/dev/null || true

# Create session — orchestrator in first pane (interactive, receives keypresses)
tmux new-session -d -s "$SESSION" -n "agents" \
  "unset CLAUDECODE; $RUN_DIR/run_agents.sh $ITERATIONS; echo '--- DONE --- (press enter)'; read"

# 3 log watcher panes using watch (handles new files appearing)
tmux split-window -h -t "$SESSION:agents" \
  "watch -n 3 -c 'echo \"=== ANALYSIS ===\"; ls -t $LOG_DIR/iter-*-analysis.log 2>/dev/null | head -1 | xargs tail -40 2>/dev/null || echo \"Waiting for logs...\"'"

tmux split-window -h -t "$SESSION:agents" \
  "watch -n 3 -c 'echo \"=== FRONTEND ===\"; ls -t $LOG_DIR/iter-*-frontend.log 2>/dev/null | head -1 | xargs tail -40 2>/dev/null || echo \"Waiting for logs...\"'"

tmux split-window -h -t "$SESSION:agents" \
  "watch -n 3 -c 'echo \"=== REVIEWER ===\"; ls -t $LOG_DIR/iter-*-reviewer.log 2>/dev/null | head -1 | xargs tail -40 2>/dev/null || echo \"Waiting for logs...\"'"

tmux select-layout -t "$SESSION:agents" even-horizontal
tmux attach-session -t "$SESSION"
