#!/bin/bash
# Launch tmux with 4 panes: orchestrator + 3 agent log tails
# Usage: bash docs/run1-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="run1"

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

# Create session — orchestrator in first pane
tmux new-session -d -s "$SESSION" -n "agents" \
  "unset CLAUDECODE; $RUN_DIR/run_agents.sh $ITERATIONS 2>&1 | tee $LOG_DIR/orchestrator.log; echo '--- DONE --- (press enter)'; read"

# 3 log tail panes
tmux split-window -h -t "$SESSION:agents" \
  "echo 'Waiting for analysis log...' && while ! ls $LOG_DIR/iter-*-analysis.log >/dev/null 2>&1; do sleep 1; done && tail -f $LOG_DIR/iter-*-analysis.log"

tmux split-window -h -t "$SESSION:agents" \
  "echo 'Waiting for frontend log...' && while ! ls $LOG_DIR/iter-*-frontend.log >/dev/null 2>&1; do sleep 1; done && tail -f $LOG_DIR/iter-*-frontend.log"

tmux split-window -h -t "$SESSION:agents" \
  "echo 'Waiting for reviewer log...' && while ! ls $LOG_DIR/iter-*-reviewer.log >/dev/null 2>&1; do sleep 1; done && tail -f $LOG_DIR/iter-*-reviewer.log"

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