#!/usr/bin/env bash
# bootstrap.sh — recreate Cameron's agent fleet in tmux from the git repo.
#
# Idempotent: if the session already exists, attaches instead. Pass --reset
# to kill an existing session and rebuild from scratch.
#
# Usage:
#   ./bootstrap.sh             # create session if missing, else attach
#   ./bootstrap.sh --reset     # kill + recreate
#   ./bootstrap.sh --no-attach # create session and exit (don't attach)
#   ./bootstrap.sh --only manager,backbones  # spin up just these
#
# Each agent window:
#   1. cd into its configured cwd
#   2. launches `claude --dangerously-skip-permissions`
#   3. receives an onboarding message: read your ROLE.md, GUIDELINES.md,
#      REPORT_FORMAT.md, and (if it exists) logs/<name>_latest.log

set -euo pipefail

REPO_ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
CONFIG="$REPO_ROOT/config.yaml"
LOGS_DIR="$REPO_ROOT/logs"
SESSION="agents"

CLAUDE_BIN="${CLAUDE_BIN:-claude}"
CLAUDE_FLAGS="${CLAUDE_FLAGS:---dangerously-skip-permissions}"

RESET=0
NO_ATTACH=0
ONLY=""
for arg in "$@"; do
    case "$arg" in
        --reset) RESET=1 ;;
        --no-attach) NO_ATTACH=1 ;;
        --only=*) ONLY="${arg#*=}" ;;
        --only)  shift; ONLY="${1:-}";;
        -h|--help)
            sed -n '2,12p' "$0"; exit 0 ;;
    esac
done

command -v tmux >/dev/null || { echo "tmux not installed"; exit 1; }
command -v "$CLAUDE_BIN" >/dev/null || { echo "claude not on PATH (set CLAUDE_BIN)"; exit 1; }
command -v python3 >/dev/null || { echo "python3 not installed"; exit 1; }

# --- Parse config.yaml via python (avoids needing yq) ----------------------
read_config() {
    python3 - "$CONFIG" "$@" <<'PY'
import sys, yaml
cfg = yaml.safe_load(open(sys.argv[1]))
mode = sys.argv[2]

if mode == "session":
    print(cfg.get("session", "agents"))
elif mode == "agents":
    for name in cfg.get("agents", {}):
        print(name)
elif mode == "services":
    for name in cfg.get("services", {}):
        print(name)
elif mode == "agent_field":
    name, field = sys.argv[3], sys.argv[4]
    print(cfg["agents"][name].get(field, ""))
elif mode == "service_field":
    name, field = sys.argv[3], sys.argv[4]
    print(cfg["services"][name].get(field, ""))
PY
}

SESSION="$(read_config session)"
mapfile -t AGENT_NAMES < <(read_config agents)
mapfile -t SERVICE_NAMES < <(read_config services)

# Filter by --only if set
if [[ -n "$ONLY" ]]; then
    IFS=',' read -ra WANTED <<< "$ONLY"
    declare -a FILTERED
    for n in "${AGENT_NAMES[@]}"; do
        for w in "${WANTED[@]}"; do
            [[ "$n" == "$w" ]] && FILTERED+=("$n")
        done
    done
    AGENT_NAMES=("${FILTERED[@]}")
    declare -a FILTERED_SVC
    for n in "${SERVICE_NAMES[@]}"; do
        for w in "${WANTED[@]}"; do
            [[ "$n" == "$w" ]] && FILTERED_SVC+=("$n")
        done
    done
    SERVICE_NAMES=("${FILTERED_SVC[@]:-}")
fi

# --- Reset existing session if requested -----------------------------------
if tmux has-session -t "$SESSION" 2>/dev/null; then
    if [[ $RESET -eq 1 ]]; then
        echo "Killing existing session '$SESSION'..."
        tmux kill-session -t "$SESSION"
    else
        echo "Session '$SESSION' already exists. Use --reset to rebuild, or attach:"
        echo "  tmux attach -t $SESSION"
        [[ $NO_ATTACH -eq 0 ]] && exec tmux attach -t "$SESSION"
        exit 0
    fi
fi

mkdir -p "$LOGS_DIR"

# --- Create session with first agent as the seed window --------------------
FIRST="${AGENT_NAMES[0]}"
FIRST_CWD="$(read_config agent_field "$FIRST" cwd)"
[[ -d "$FIRST_CWD" ]] || { echo "cwd missing for $FIRST: $FIRST_CWD"; exit 1; }

echo "Creating tmux session '$SESSION' starting with window '$FIRST'..."
tmux new-session -d -s "$SESSION" -n "$FIRST" -c "$FIRST_CWD"

launch_agent() {
    local name="$1"
    local cwd role_file role_path log_path onboarding

    cwd="$(read_config agent_field "$name" cwd)"
    role_file="$(read_config agent_field "$name" role_file)"
    role_path="$REPO_ROOT/$role_file"
    log_path="$LOGS_DIR/${name}_latest.log"

    [[ -d "$cwd" ]] || { echo "  ! skip $name: cwd missing ($cwd)"; return; }
    [[ -f "$role_path" ]] || { echo "  ! skip $name: ROLE.md missing ($role_path)"; return; }

    if ! tmux list-windows -t "$SESSION" -F "#{window_name}" | grep -qx "$name"; then
        tmux new-window -t "$SESSION" -n "$name" -c "$cwd"
    fi

    # Launch claude in the window
    tmux send-keys -t "${SESSION}:${name}" "$CLAUDE_BIN $CLAUDE_FLAGS" Enter

    # Wait a moment for claude to come up before sending the onboarding prompt
    sleep 4

    onboarding="You are the '$name' agent in Cameron's fleet. Bootstrap yourself now:

1. Read your role: $role_path
2. Read fleet guidelines: $REPO_ROOT/shared/GUIDELINES.md
3. Read the report format: $REPO_ROOT/shared/REPORT_FORMAT.md"

    if [[ -s "$log_path" ]]; then
        onboarding+="
4. Read your most recent scrollback to recover prior context: $log_path
   (it shows what you were doing before the last shutdown — pick up from there)"
    else
        onboarding+="
4. (no prior scrollback log yet — fresh start)"
    fi

    onboarding+="

Once you've read these, give a one-line status of what you understand your current task to be, then wait for instructions."

    tmux send-keys -t "${SESSION}:${name}" "$onboarding" Enter
    sleep 1
    tmux send-keys -t "${SESSION}:${name}" Enter

    echo "  ✓ launched $name (cwd=$cwd)"
}

echo "Launching ${#AGENT_NAMES[@]} agent windows..."
for name in "${AGENT_NAMES[@]}"; do
    launch_agent "$name"
done

# --- Service windows (no claude) -------------------------------------------
launch_service() {
    local name="$1"
    local cwd hint
    cwd="$(read_config service_field "$name" cwd)"
    hint="$(read_config service_field "$name" command_hint)"
    [[ -d "$cwd" ]] || { echo "  ! skip service $name: cwd missing ($cwd)"; return; }

    if ! tmux list-windows -t "$SESSION" -F "#{window_name}" | grep -qx "$name"; then
        tmux new-window -t "$SESSION" -n "$name" -c "$cwd"
    fi

    if [[ -n "$hint" ]]; then
        # Print the command hint as a banner — don't auto-execute (may need secrets)
        tmux send-keys -t "${SESSION}:${name}" "clear && cat <<'EOF'
=== Service: $name ===
Run this when ready (edit as needed):

$hint
EOF" Enter
    fi
    echo "  ✓ prepared service window $name (cwd=$cwd)"
}

if [[ ${#SERVICE_NAMES[@]} -gt 0 ]]; then
    echo "Preparing ${#SERVICE_NAMES[@]} service windows..."
    for name in "${SERVICE_NAMES[@]}"; do
        launch_service "$name"
    done
fi

# Select first window when attaching
tmux select-window -t "${SESSION}:${FIRST}"

echo
echo "Fleet is up. Windows:"
tmux list-windows -t "$SESSION" -F "  #{window_index}: #{window_name}"
echo

if [[ $NO_ATTACH -eq 0 ]]; then
    if [[ -n "${TMUX:-}" ]]; then
        echo "(already inside tmux — switch with: tmux switch-client -t $SESSION)"
    else
        exec tmux attach -t "$SESSION"
    fi
fi
