#!/bin/bash
# debug - Spawn a team for the debug workflow
# Roles: conductor, developer, tester
# Usage: debug [backend] [workdir]

set -e

BACKEND="${1:-claude}"
WORKDIR="${2:-$(pwd)}"

HASH=$(echo -n "$WORKDIR" | md5sum | cut -c1-8)
REQUIRED_ROLES="conductor developer tester"

# Spawn all required roles
anvilspawn "$BACKEND" conductor "$WORKDIR"
anvilspawn "$BACKEND" developer "$WORKDIR"
anvilspawn "$BACKEND" tester    "$WORKDIR"

# Block until all required roles are idle (ready to receive work)
echo "Waiting for all roles to become available..."
MAX_WAIT=120
ELAPSED=0
while [ "$ELAPSED" -lt "$MAX_WAIT" ]; do
    ALL_READY=true
    for role in $REQUIRED_ROLES; do
        alias="${HASH}-${role}"
        state=$(9p read anvillm/list 2>/dev/null | awk -F'\t' -v a="$alias" '$4 == a {print $3}')
        if [ "$state" != "idle" ]; then
            ALL_READY=false
            break
        fi
    done
    if $ALL_READY; then
        echo "All roles available and idle."
        exit 0
    fi
    sleep 2
    ELAPSED=$((ELAPSED + 2))
done

echo "Error: not all roles became idle within ${MAX_WAIT}s" >&2
exit 1
