#!/bin/bash
# Multi-agent orchestration for developer analytics dashboard
# Usage: ./docs/run2-14022026/run_agents.sh [iterations]
#
# INTERACTIVE CONTROLS (while agents are running):
#   p     = pause after current iteration finishes
#   P     = pause + open prompt to inject instructions into AGENT_STATE.md
#   r     = resume (clear pause)
#   q     = quit after current iteration

set -euo pipefail

# Allow launching claude from within another claude session
unset CLAUDECODE 2>/dev/null || true

# --- COLORS & FORMATTING ---
BOLD='\033[1m'
DIM='\033[2m'
RESET='\033[0m'
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[0;33m'
BLUE='\033[0;34m'
MAGENTA='\033[0;35m'
CYAN='\033[0;36m'
WHITE='\033[1;37m'
BG_GREEN='\033[42m'
BG_YELLOW='\033[43m'
BG_RED='\033[41m'
BG_BLUE='\033[44m'
BG_MAGENTA='\033[45m'

hr() { echo -e "${DIM}$(printf '─%.0s' $(seq 1 60))${RESET}"; }
box_top()    { echo -e "${CYAN}┌$(printf '─%.0s' $(seq 1 58))┐${RESET}"; }
box_bottom() { echo -e "${CYAN}└$(printf '─%.0s' $(seq 1 58))┘${RESET}"; }
box_line()   { printf "${CYAN}│${RESET} %-56s ${CYAN}│${RESET}\n" "$1"; }
status_badge() {
  local color="$1" label="$2"
  echo -e " ${color}${BOLD} ${label} ${RESET}"
}

ITERATIONS="${1:-100}"
RUN_DIR="$(cd "$(dirname "$0")" && pwd)"
PROJECT_DIR="$(cd "$RUN_DIR/../.." && pwd)"
ANALYSIS_DIR="$PROJECT_DIR/analysis-14022026"

# Run dir = docs, logs, state, changelog (documentation)
LOG_DIR="$RUN_DIR/logs"
STATE_DIR="$RUN_DIR/state"

# Analysis dir = scripts, output JSON, dashboard app (project files)
OUTPUT_DIR="$ANALYSIS_DIR/output"
DASHBOARD_DIR="$ANALYSIS_DIR/dashboard"
SCRIPTS_DIR="$ANALYSIS_DIR/scripts"

# Control files
PAUSE_FILE="$RUN_DIR/PAUSE"
QUIT_FILE="$RUN_DIR/QUIT"
PROMPT_FILE="$RUN_DIR/PROMPT_PENDING"

mkdir -p "$LOG_DIR" "$STATE_DIR" "$OUTPUT_DIR" "$DASHBOARD_DIR" "$SCRIPTS_DIR"
rm -f "$PAUSE_FILE" "$QUIT_FILE" "$PROMPT_FILE"

# Initialize state file if not exists
if [ ! -f "$STATE_DIR/AGENT_STATE.md" ]; then
  cat > "$STATE_DIR/AGENT_STATE.md" << 'INITSTATE'
# Agent State

## Status: STARTING
## Iteration: 0
## Phase: VP-wow (targeting VP of Engineering reaction first)

## What exists:
- Local Postgres with all trace data (sessions, messages, tool_calls, tool_results, token_usage)
- Existing analysis notebooks in notebooks/003-focused-analytics/
- Connection utils in notebooks/utils/

## Next steps:
- Analysis agent: query local DB, compute metrics, produce JSON data files in analysis-14022026/output/ and analysis-14022026/dashboard/public/data/
- Frontend agent: scaffold Vite + React + Tailwind dashboard in analysis-14022026/dashboard/, keep dev server running on port 5173
- Reviewer: verify quality meets "oh fuck what" bar, check dev server is live

## Done so far:
(nothing yet)
INITSTATE
fi

# Initialize changelog if not exists
if [ ! -f "$STATE_DIR/CHANGELOG.md" ]; then
  cat > "$STATE_DIR/CHANGELOG.md" << 'INITLOG'
# Iteration Changelog

Each agent documents what they did per iteration. The reviewer verifies and scores.

---
INITLOG
fi

# --- BACKGROUND KEY LISTENER ---
INPUT_PID=""
start_key_listener() {
  (
    while true; do
      # Read single char with 1s timeout
      if read -rsn1 -t 1 key 2>/dev/null; then
        case "$key" in
          p)
            touch "$PAUSE_FILE"
            echo ""
            echo -e "  $(status_badge "$BG_YELLOW" "PAUSE QUEUED") will pause after current iteration"
            echo -e "  ${DIM}Press 'r' to cancel${RESET}"
            ;;
          P)
            touch "$PAUSE_FILE"
            touch "$PROMPT_FILE"
            echo ""
            echo -e "  $(status_badge "$BG_MAGENTA" "INSTRUCT") will pause for instructions after this iteration"
            ;;
          r)
            rm -f "$PAUSE_FILE" "$PROMPT_FILE"
            echo ""
            echo -e "  $(status_badge "$BG_GREEN" "RESUMED") pause cleared"
            ;;
          q)
            touch "$QUIT_FILE"
            echo ""
            echo -e "  $(status_badge "$BG_RED" "QUIT QUEUED") will stop after current iteration"
            ;;
        esac
      fi
      # Exit if quit file exists and we're done
      [ -f "$QUIT_FILE" ] && [ ! -f "$PAUSE_FILE" ] && break
    done
  ) &
  INPUT_PID=$!
}

stop_key_listener() {
  if [ -n "$INPUT_PID" ]; then
    kill "$INPUT_PID" 2>/dev/null || true
    wait "$INPUT_PID" 2>/dev/null || true
    INPUT_PID=""
  fi
}

# Prompt user for instructions, enhance via Claude, inject into AGENT_STATE.md
prompt_for_instructions() {
  echo ""
  echo -e "  ${CYAN}┌──────────────────────────────────────────────────────────┐${RESET}"
  echo -e "  ${CYAN}│${RESET}  ${MAGENTA}${BOLD}INSTRUCTION MODE${RESET}                                        ${CYAN}│${RESET}"
  echo -e "  ${CYAN}│${RESET}                                                          ${CYAN}│${RESET}"
  echo -e "  ${CYAN}│${RESET}  Type your instruction in plain language — rough is fine. ${CYAN}│${RESET}"
  echo -e "  ${CYAN}│${RESET}  Claude will enhance it into a precise agent directive.  ${CYAN}│${RESET}"
  echo -e "  ${CYAN}│${RESET}  Press ${GREEN}Enter twice${RESET} (empty line) to submit.               ${CYAN}│${RESET}"
  echo -e "  ${CYAN}│${RESET}  Type '${RED}cancel${RESET}' to skip.                                  ${CYAN}│${RESET}"
  echo -e "  ${CYAN}└──────────────────────────────────────────────────────────┘${RESET}"
  echo ""
  echo -ne "  ${MAGENTA}>${RESET} "

  RAW_INPUT=""
  while IFS= read -r line; do
    [ -z "$line" ] && break
    [ "$line" = "cancel" ] && RAW_INPUT="" && break
    RAW_INPUT="${RAW_INPUT}${line}
"
    echo -ne "  ${MAGENTA}>${RESET} "
  done

  if [ -z "$RAW_INPUT" ]; then
    echo ""
    echo -e "  ${DIM}Cancelled — no instruction injected${RESET}"
    echo ""
    rm -f "$PROMPT_FILE"
    return
  fi

  echo ""
  echo -e "  ${YELLOW}Enhancing instruction via Claude...${RESET}"

  # Read current AGENT_STATE for context
  CURRENT_STATE=$(cat "$STATE_DIR/AGENT_STATE.md" 2>/dev/null | head -80)

  # Enhance via Claude Sonnet
  ENHANCED=$(claude -p --model claude-sonnet-4-5-20250929 \
    --dangerously-skip-permissions \
    "You are a prompt enhancer for a multi-agent orchestration system. Three AI agents (analysis, frontend, reviewer) read an AGENT_STATE.md file for instructions.

CURRENT AGENT_STATE.md (first 80 lines for context):
---
$CURRENT_STATE
---

The user typed this rough instruction:
---
$RAW_INPUT
---

Your job: Rewrite this into a precise, actionable agent directive. Rules:
1. Output ONLY the enhanced instruction text — no preamble, no explanation, no markdown code fences
2. Be specific: name files, metrics, components, or behaviors the agents should target
3. Use imperative language: 'Do X', 'Fix Y', 'Add Z'
4. If the instruction implies analysis work, address the analysis agent. If frontend, address frontend. If both, address both.
5. Add acceptance criteria where possible (e.g. 'The tooltip must show X when hovering Y')
6. Add a deduction rule if relevant (e.g. 'Deduct 1 point if X is missing')
7. Keep it concise — 3-10 bullet points max
8. Do NOT repeat existing constraints from AGENT_STATE.md — only add NEW instructions
9. Do NOT use emojis" \
    2>/dev/null) || true

  if [ -z "$ENHANCED" ]; then
    echo -e "  ${RED}Enhancement failed — using raw input instead${RESET}"
    ENHANCED="$RAW_INPUT"
  fi

  # Show enhanced version for approval
  echo ""
  echo -e "  ${CYAN}┌── Enhanced Instruction ──────────────────────────────────┐${RESET}"
  echo "$ENHANCED" | while IFS= read -r eline; do
    printf "  ${CYAN}│${RESET} %-56s ${CYAN}│${RESET}\n" "$eline"
  done
  echo -e "  ${CYAN}└──────────────────────────────────────────────────────────┘${RESET}"
  echo ""
  echo -ne "  ${GREEN}Inject this? [Y/n/e(dit raw)]${RESET} "
  read -r confirm

  case "${confirm:-y}" in
    n|N)
      echo -e "  ${DIM}Discarded${RESET}"
      rm -f "$PROMPT_FILE"
      return
      ;;
    e|E)
      # Fall back to raw input
      ENHANCED="$RAW_INPUT"
      echo -e "  ${DIM}Using raw input instead${RESET}"
      ;;
  esac

  # Inject into AGENT_STATE.md
  TIMESTAMP=$(date '+%Y-%m-%d %H:%M:%S')
  INJECT_BLOCK="
## USER INSTRUCTION (injected at $TIMESTAMP) — HIGHEST PRIORITY
$ENHANCED
"
  {
    head -1 "$STATE_DIR/AGENT_STATE.md"
    echo "$INJECT_BLOCK"
    tail -n +2 "$STATE_DIR/AGENT_STATE.md"
  } > "$STATE_DIR/AGENT_STATE.md.tmp"
  mv "$STATE_DIR/AGENT_STATE.md.tmp" "$STATE_DIR/AGENT_STATE.md"

  echo ""
  echo -e "  $(status_badge "$BG_GREEN" "INJECTED") Enhanced instruction added to AGENT_STATE.md"
  echo -e "  ${DIM}All agents will see it at the start of next iteration${RESET}"
  echo ""

  rm -f "$PROMPT_FILE"
}

# Cleanup on exit
cleanup() {
  stop_key_listener
  rm -f "$PAUSE_FILE" "$QUIT_FILE" "$PROMPT_FILE"
  # Restore terminal
  stty sane 2>/dev/null || true
}
trap cleanup EXIT

echo ""
box_top
box_line "${BOLD}${WHITE}Developer Analytics — Multi-Agent Orchestrator${RESET}"
box_line ""
box_line "Iterations: ${GREEN}$ITERATIONS${RESET}"
box_line "Run dir:    ${DIM}$RUN_DIR${RESET}"
box_line "Analysis:   ${DIM}$ANALYSIS_DIR${RESET}"
box_line ""
box_line "${YELLOW}CONTROLS${RESET}"
box_line "  ${GREEN}p${RESET}  pause after this iteration"
box_line "  ${MAGENTA}P${RESET}  pause + inject instruction into AGENT_STATE"
box_line "  ${CYAN}r${RESET}  resume"
box_line "  ${RED}q${RESET}  quit after this iteration"
box_bottom
echo ""

# Start background key listener
start_key_listener

for i in $(seq 1 "$ITERATIONS"); do
  echo ""
  hr
  echo -e "  ${BG_BLUE}${WHITE}${BOLD} ITERATION $i / $ITERATIONS ${RESET}  ${DIM}$(date '+%Y-%m-%d %H:%M:%S')${RESET}  ${DIM}[p=pause P=instruct r=resume q=quit]${RESET}"
  hr

  # --- QUIT CHECK ---
  if [ -f "$QUIT_FILE" ]; then
    echo ""
    echo -e "  $(status_badge "$BG_RED" "QUIT") Stopping gracefully."
    break
  fi

  # --- PAUSE CHECK ---
  if [ -f "$PAUSE_FILE" ]; then
    # Stop key listener so we can read from stdin directly
    stop_key_listener

    # If prompt was requested, collect instructions
    if [ -f "$PROMPT_FILE" ]; then
      prompt_for_instructions
    else
      echo ""
      echo "  PAUSED — press 'r' then Enter to resume, or 'P' then Enter to inject instructions first"
      while [ -f "$PAUSE_FILE" ]; do
        read -rsn1 -t 2 key 2>/dev/null || true
        case "${key:-}" in
          r) rm -f "$PAUSE_FILE" "$PROMPT_FILE"; echo "  >>> Resumed!"; break ;;
          P)
            prompt_for_instructions
            echo "  Still paused. Press 'r' then Enter to resume."
            ;;
        esac
      done
    fi

    rm -f "$PAUSE_FILE"
    # Restart key listener
    start_key_listener
  fi

  # --- ALL 3 AGENTS IN PARALLEL ---
  echo -e "  ${GREEN}[analysis]${RESET} Starting...  ${BLUE}[frontend]${RESET} Starting...  ${MAGENTA}[reviewer]${RESET} Starting..."
  claude -p \
    --dangerously-skip-permissions \
    "You are the ANALYSIS agent for a developer analytics project.

ENVIRONMENT:
- Working directory: $PROJECT_DIR
- Local Postgres: postgresql://localdev:localdev@localhost:15432/qc_trace
- CRITICAL: ONLY use LOCAL data. NEVER connect to prod. The local utils enforce this automatically.
- Python: $PROJECT_DIR/.venv/bin/python
- Utils: $ANALYSIS_DIR/utils/ (connection.py defaults to .local.env, sessions.py, messages.py, tokens.py, tools.py)
- Reference notebooks: notebooks/003-focused-analytics/002-dev-report.py and 003-qualitative-report.py
- Analysis scripts go in: $SCRIPTS_DIR/
- When writing scripts, use: sys.path.insert(0, '$ANALYSIS_DIR') then 'from utils.connection import init, query_df'

READ THESE FILES FIRST:
1. $STATE_DIR/AGENT_STATE.md — current state and what to do next. PAY SPECIAL ATTENTION to any 'USER INSTRUCTION' sections at the top — these are highest priority.
2. $STATE_DIR/REVIEW_FEEDBACK.md — reviewer feedback from last iteration (if exists)
3. $PROJECT_DIR/notebooks/003-focused-analytics/CONTEXT.md — full context on DB schema, metrics, conventions

DATA FILTER (CRITICAL):
- ONLY analyze data where org LIKE 'pratilipi%' (pratilipi-ai, pratilipi-platform, etc.)
- All SQL queries MUST include: WHERE s.org LIKE 'pratilipi%' (or equivalent join filter)
- Do NOT analyze data from other orgs — privacy constraint

YOUR JOB:
- Query the local Postgres DB and compute analytics
- Write any analysis scripts to $SCRIPTS_DIR/
- Produce JSON data files in $OUTPUT_DIR/ that the frontend agent can consume
- The JSON should contain pre-computed metrics, chart data, tables, insights
- Think about what would make a VP of Engineering say 'oh fuck what' — surface surprising patterns, wasteful behaviors, productivity killers, hidden insights
- Reference the metrics framework in CONTEXT.md but go BEYOND it — find the stories in the data
- NOTE: You are running IN PARALLEL with the frontend and reviewer agents. They are working on the PREVIOUS iteration's data. Focus on improving/adding data for the NEXT iteration.

OUTPUT:
- Write analysis scripts to $SCRIPTS_DIR/
- Write JSON files to $OUTPUT_DIR/ (e.g., overview.json, session_metrics.json, developer_profiles.json, insights.json, chart_data.json)
- ALSO copy all JSON files to $DASHBOARD_DIR/public/data/ (create the dir if needed) so the Vite dashboard can fetch them
- Update $STATE_DIR/AGENT_STATE.md with what you produced and what's next

DOCUMENTATION (MANDATORY):
Append to $STATE_DIR/CHANGELOG.md a section for this iteration:
## Iteration $i — Analysis Agent
- What you did (specific queries, metrics computed, files created/modified)
- What data you produced and why
- What you discovered that was surprising or noteworthy
- Decisions you made and why

ITERATION: $i / $ITERATIONS
Do NOT ask questions. Do as much as you can. Be thorough." \
    > "$LOG_DIR/iter-${i}-analysis.log" 2>&1 &
  PID_ANALYSIS=$!

  claude -p \
    --dangerously-skip-permissions \
    "You are the FRONTEND agent for a developer analytics dashboard.

ENVIRONMENT:
- Working directory: $PROJECT_DIR
- Dashboard app directory: $DASHBOARD_DIR (Vite + React app)
- Analysis JSON data: $OUTPUT_DIR/ (produced by the analysis agent)
- Node/npm available on the system

READ THESE FILES FIRST:
1. $STATE_DIR/AGENT_STATE.md — current state and reviewer feedback. PAY SPECIAL ATTENTION to any 'USER INSTRUCTION' sections at the top — these are highest priority.
2. $STATE_DIR/REVIEW_FEEDBACK.md — reviewer feedback from last iteration (if exists)
3. $PROJECT_DIR/notebooks/003-focused-analytics/CONTEXT.md — domain context
4. All JSON files in $OUTPUT_DIR/ — this is your data source (may be updated mid-iteration by the analysis agent running in parallel)
5. The existing dashboard code in $DASHBOARD_DIR/ (if it exists already)

YOUR JOB:
- Build a Vite + React dashboard app in $DASHBOARD_DIR/
- On the FIRST iteration: scaffold with 'npm create vite@latest' inside $DASHBOARD_DIR/ (or init manually), install dependencies (recharts, framer-motion, lucide-react or similar), set up the project structure
- On SUBSEQUENT iterations: iterate on the existing app — add sections, improve visuals, fix reviewer feedback
- The dev server should always be running. After any changes, make sure 'npm run dev' works. Start it if not already running (port 5173)
- Copy JSON data files from $OUTPUT_DIR/ into $DASHBOARD_DIR/public/data/ so the app can fetch them
- NOTE: You are running IN PARALLEL with the analysis and reviewer agents. Use whatever JSON data currently exists in $OUTPUT_DIR/. If files are missing, build components that gracefully handle missing data.

DESIGN REQUIREMENTS:
- Dark, modern theme — think Linear, Vercel dashboard, or Raycast aesthetic
- Consistent design system: one font family, one color palette, consistent spacing/radius
- Use a charting library (recharts, nivo, or chart.js) for all visualizations
- Smooth transitions and animations between sections
- The dashboard must tell a STORY — it's not a bunch of charts, it's a narrative
- Structure: Hero section with headline insight → Overview metrics → Deep dives → Developer profiles → Surprising findings
- Each section should have a provocative headline that makes someone stop and read (e.g., 'Your AI spends 73% of its time lost' not 'Tool Usage Distribution')
- Responsive layout, but optimize for 1440px+ screens (this will be shown on a projector/large monitor)

TECH STACK:
- Vite + React + TypeScript
- Tailwind CSS (install via npm, configure in the project)
- Recharts or similar for charts
- Framer Motion for animations (optional but preferred)
- NO backend — pure static site loading JSON from public/data/

OUTPUT:
- All code in $DASHBOARD_DIR/
- Ensure 'npm run dev' works after your changes
- Update $STATE_DIR/AGENT_STATE.md with what you built

DOCUMENTATION (MANDATORY):
Append to $STATE_DIR/CHANGELOG.md a section for this iteration:
## Iteration $i — Frontend Agent
- What you built or changed (specific components, pages, charts added/modified)
- Design decisions and why
- What JSON data you consumed and how you visualized it
- Known limitations or things you'd improve with more data

ITERATION: $i / $ITERATIONS
Do NOT ask questions. Make it extraordinary." \
    > "$LOG_DIR/iter-${i}-frontend.log" 2>&1 &
  PID_FRONTEND=$!

  claude -p \
    --dangerously-skip-permissions \
    "You are the REVIEWER agent. You are ruthless and have extremely high standards.

ENVIRONMENT:
- Working directory: $PROJECT_DIR
- Analysis scripts: $SCRIPTS_DIR/
- Analysis output: $OUTPUT_DIR/
- Dashboard app: $DASHBOARD_DIR/
- State: $STATE_DIR/AGENT_STATE.md

READ:
1. $STATE_DIR/AGENT_STATE.md — PAY SPECIAL ATTENTION to any 'USER INSTRUCTION' sections — these override everything else
2. $STATE_DIR/CHANGELOG.md — review what agents documented in previous iterations
3. The Vite dashboard app in $DASHBOARD_DIR/ — read the components, pages, styles
4. All JSON files in $OUTPUT_DIR/
5. $PROJECT_DIR/notebooks/003-focused-analytics/CONTEXT.md
6. Check if the dev server is running: curl -s http://localhost:5173 (if not, start it with 'cd $DASHBOARD_DIR && npm run dev &')

NOTE: You are running IN PARALLEL with the analysis and frontend agents. Review whatever currently exists — the other agents are simultaneously improving their work. Your feedback will be read by them at the START of the next iteration.

YOUR STANDARDS:
Phase 1 (current): VP of Engineering reaction — 'oh fuck what!'
- Does this dashboard surface something a VP has never seen before?
- Does it reveal hidden costs, surprising patterns, or actionable intelligence?
- Is the visual quality executive-grade? Would you be embarrassed showing this in a board meeting?
- Are the insights specific and data-backed, not generic fluff?

Phase 2 (after VP bar is met): Developer reaction — 'oh fuck what!'
- Does this show developers something about their own behavior they didn't know?
- Is it personal, specific, and slightly uncomfortable (in a good way)?
- Does it make them want to change how they work?

YOUR JOB:
1. Review the dashboard app code and the live dev server
2. Check if the analysis JSON data is rich enough
3. Write detailed feedback to $STATE_DIR/REVIEW_FEEDBACK.md with:
   - VERDICT: 'KEEP GOING' or 'VP SATISFIED — MOVE TO DEVS' or 'DONE'
   - What's working
   - What's missing or weak
   - Specific improvements for next iteration
4. Update $STATE_DIR/AGENT_STATE.md with the verdict and next steps
5. If DONE, write 'DONE' as the first line of $STATE_DIR/AGENT_STATE.md

Be specific. Don't say 'make it better' — say exactly what to add, change, or fix.

DOCUMENTATION (MANDATORY):
1. Append to $STATE_DIR/CHANGELOG.md a section for this iteration:
## Iteration $i — Reviewer
- Your verdict and why
- What met the bar and what didn't
- Specific action items for next iteration (numbered list)
- Quality score out of 10 for: Data Depth, Visual Impact, Insight Quality, Storytelling

2. ALSO review the changelog entries from the analysis and frontend agents this iteration.
   If they took shortcuts in documenting (vague descriptions, missing rationale), call it out
   in REVIEW_FEEDBACK.md and tell them to be more specific next iteration.

ITERATION: $i / $ITERATIONS
Do NOT ask questions." \
    > "$LOG_DIR/iter-${i}-reviewer.log" 2>&1 &
  PID_REVIEWER=$!

  echo -e "  ${DIM}All 3 agents running in parallel... waiting${RESET}"
  echo ""

  # Show elapsed time while waiting
  START_TIME=$SECONDS
  while true; do
    # Check if all processes are done
    if ! kill -0 $PID_ANALYSIS 2>/dev/null && ! kill -0 $PID_FRONTEND 2>/dev/null && ! kill -0 $PID_REVIEWER 2>/dev/null; then
      break
    fi

    ELAPSED=$(( SECONDS - START_TIME ))
    MINS=$(( ELAPSED / 60 ))
    SECS=$(( ELAPSED % 60 ))

    # Build status line
    A_STATUS="${GREEN}done${RESET}"; kill -0 $PID_ANALYSIS 2>/dev/null && A_STATUS="${YELLOW}running${RESET}"
    F_STATUS="${GREEN}done${RESET}"; kill -0 $PID_FRONTEND 2>/dev/null && F_STATUS="${YELLOW}running${RESET}"
    R_STATUS="${GREEN}done${RESET}"; kill -0 $PID_REVIEWER 2>/dev/null && R_STATUS="${YELLOW}running${RESET}"

    printf "\r  ${DIM}%02d:%02d${RESET}  analysis:${A_STATUS}  frontend:${F_STATUS}  reviewer:${R_STATUS}    " "$MINS" "$SECS"
    sleep 2
  done

  wait $PID_ANALYSIS $PID_FRONTEND $PID_REVIEWER 2>/dev/null || true

  ELAPSED=$(( SECONDS - START_TIME ))
  MINS=$(( ELAPSED / 60 ))
  SECS=$(( ELAPSED % 60 ))
  printf "\r"
  echo -e "  $(status_badge "$BG_GREEN" "DONE") All 3 agents finished in ${BOLD}${MINS}m ${SECS}s${RESET}                          "

  # Check if reviewer said DONE
  if head -1 "$STATE_DIR/AGENT_STATE.md" 2>/dev/null | grep -qi "DONE"; then
    echo ""
    echo -e "  ${BG_GREEN}${WHITE}${BOLD}                                            ${RESET}"
    echo -e "  ${BG_GREEN}${WHITE}${BOLD}   REVIEWER SAYS: DONE! (iteration $i)       ${RESET}"
    echo -e "  ${BG_GREEN}${WHITE}${BOLD}                                            ${RESET}"
    break
  fi

  echo ""
done

echo ""
hr
echo -e "  ${BOLD}Run complete.${RESET}"
echo -e "  Dashboard: ${CYAN}$DASHBOARD_DIR/${RESET} (npm run dev on :5173)"
echo -e "  Logs:      ${DIM}$LOG_DIR/${RESET}"
echo -e "  State:     ${DIM}$STATE_DIR/AGENT_STATE.md${RESET}"
hr
