#!/usr/bin/env bash
# orchestrate.sh — Orchestrator for qc-traced parallel agents
# Run this in a SEPARATE terminal (not inside tmux)
# Prerequisites: tmux session "trace" with 4 panes, claude CLI installed, uv installed
set -euo pipefail

# ============================================================================
# CONFIG
# ============================================================================
REPO_ROOT="$HOME/work/all-things-quickcall/trace"
TMUX_SESSION="trace"
AGENT_DIR="/tmp/qc-traced-agents"
PROMPT_DIR="$AGENT_DIR/prompts"
LOG_FILE="$AGENT_DIR/orchestrator.log"
POLL_INTERVAL=15

# Agent definitions: name:pane_index:worktree_dir:branch
AGENTS=(
  "daemon-core:1:trace-daemon-core:feat/traced-daemon-core"
  "installer:2:trace-installer:feat/traced-installer"
  "service:3:trace-service:feat/traced-service"
  "cli:4:trace-cli:feat/traced-cli"
)

# ============================================================================
# HELPERS
# ============================================================================
log() { echo "[$(date +%H:%M:%S)] $*" | tee -a "$LOG_FILE"; }
warn() { echo "[$(date +%H:%M:%S)] WARNING: $*" | tee -a "$LOG_FILE"; }
err() { echo "[$(date +%H:%M:%S)] ERROR: $*" | tee -a "$LOG_FILE" >&2; }

send_to_pane() {
  local pane="$1"; shift
  tmux send-keys -t "${TMUX_SESSION}:.${pane}" "$*" Enter
}

read_agent_status() {
  local agent_name="$1"
  local state_file="$AGENT_DIR/agent-${agent_name}.json"
  if [[ -f "$state_file" ]]; then
    python3 -c "import json; d=json.load(open('$state_file')); print(d.get('status','unknown'))" 2>/dev/null || echo "unknown"
  else
    echo "not_started"
  fi
}

read_agent_field() {
  local agent_name="$1" field="$2"
  local state_file="$AGENT_DIR/agent-${agent_name}.json"
  if [[ -f "$state_file" ]]; then
    python3 -c "import json; d=json.load(open('$state_file')); print(d.get('$field',''))" 2>/dev/null || echo ""
  fi
}

# ============================================================================
# PHASE: LAUNCH AGENTS
# ============================================================================
phase_launch() {
  log "========== LAUNCHING AGENTS =========="

  local pane_idx=0
  for agent_def in "${AGENTS[@]}"; do
    IFS=':' read -r name pane wt_dir branch <<< "$agent_def"
    local wt_path="$REPO_ROOT/../$wt_dir"

    # Map agent name to prompt file
    local actual_prompt
    case "$name" in
      daemon-core) actual_prompt="$PROMPT_DIR/agent-1-daemon-core.md" ;;
      installer)   actual_prompt="$PROMPT_DIR/agent-2-installer.md" ;;
      service)     actual_prompt="$PROMPT_DIR/agent-3-service.md" ;;
      cli)         actual_prompt="$PROMPT_DIR/agent-4-cli.md" ;;
    esac

    if [[ ! -f "$actual_prompt" ]]; then
      err "Prompt file not found: $actual_prompt"
      exit 1
    fi

    log "Launching agent '$name' in pane $pane_idx (worktree: $wt_dir)"
    send_to_pane "$pane_idx" "cd $wt_path && claude -p \"\$(cat $actual_prompt)\" --allowedTools 'Bash(*)' 'Read(*)' 'Write(*)' 'Edit(*)' 'Glob(*)' 'Grep(*)'"

    sleep 3  # Stagger launches
    pane_idx=$((pane_idx + 1))
  done

  log "All agents launched. Entering poll loop..."
}

# ============================================================================
# PHASE: POLL LOOP
# ============================================================================
phase_poll() {
  log "========== POLL LOOP (every ${POLL_INTERVAL}s) =========="

  local all_done=false
  local cycle=0

  while [[ "$all_done" != "true" ]]; do
    sleep "$POLL_INTERVAL"
    cycle=$((cycle + 1))

    all_done=true
    local status_line=""

    for agent_def in "${AGENTS[@]}"; do
      IFS=':' read -r name pane wt_dir branch <<< "$agent_def"
      local status
      status=$(read_agent_status "$name")

      case "$status" in
        completed)
          status_line+=" [$name: DONE]"
          ;;
        running)
          all_done=false
          local task
          task=$(read_agent_field "$name" "current_task")
          status_line+=" [$name: $task]"
          ;;
        needs_input)
          all_done=false
          local question
          question=$(read_agent_field "$name" "needs_input")
          echo ""
          warn "Agent '$name' needs input:"
          echo "  $question"
          echo ""
          read -rp "  Your answer (or 'skip'): " answer
          if [[ "$answer" != "skip" ]]; then
            send_to_pane "$pane" "$answer"
            log "Sent input to $name: $answer"
          fi
          ;;
        blocked)
          all_done=false
          local blocker
          blocker=$(read_agent_field "$name" "blocked_on")
          status_line+=" [$name: BLOCKED on $blocker]"
          ;;
        error)
          all_done=false
          local error_msg
          error_msg=$(read_agent_field "$name" "error")
          err "Agent '$name' ERROR: $error_msg"
          echo ""
          read -rp "  Action? (retry/skip/abort): " action
          case "$action" in
            retry)
              send_to_pane "$pane" "Please retry the last failed step"
              ;;
            skip)
              log "Skipping error for $name"
              ;;
            abort)
              err "Aborting orchestration"
              exit 1
              ;;
          esac
          ;;
        not_started|unknown)
          all_done=false
          status_line+=" [$name: waiting...]"
          ;;
      esac
    done

    log "Cycle $cycle:$status_line"
  done

  log "========== ALL AGENTS COMPLETE =========="
}

# ============================================================================
# PHASE: SUMMARY
# ============================================================================
phase_summary() {
  log "========== SUMMARY =========="
  echo ""
  echo "All agents have completed. Next steps:"
  echo ""
  echo "1. Review each branch:"
  for agent_def in "${AGENTS[@]}"; do
    IFS=':' read -r name pane wt_dir branch <<< "$agent_def"
    echo "   cd $REPO_ROOT/../$wt_dir && git log --oneline -5"
  done
  echo ""
  echo "2. Run full test suite from each worktree:"
  echo "   cd ../trace-daemon-core && uv run pytest tests/ -v"
  echo "   cd ../trace-cli && uv run pytest tests/ -v"
  echo ""
  echo "3. Create PRs for each branch"
  echo ""
  log "Orchestration complete."
}

# ============================================================================
# MAIN
# ============================================================================
main() {
  echo ""
  echo "  qc-traced Orchestrator"
  echo "  Parallel Agent Execution Manager"
  echo "  4 agents across tmux panes"
  echo ""

  # Verify prerequisites
  command -v tmux >/dev/null || { err "tmux not found"; exit 1; }
  command -v claude >/dev/null || { err "claude CLI not found"; exit 1; }
  command -v uv >/dev/null || { err "uv not found"; exit 1; }
  tmux has-session -t "$TMUX_SESSION" 2>/dev/null || { err "tmux session '$TMUX_SESSION' not found. Create it first."; exit 1; }

  # Verify prompt files exist
  for f in agent-1-daemon-core.md agent-2-installer.md agent-3-service.md agent-4-cli.md; do
    [[ -f "$PROMPT_DIR/$f" ]] || { err "Prompt file missing: $PROMPT_DIR/$f"; exit 1; }
  done

  phase_launch
  phase_poll
  phase_summary
}

main "$@"
