#!/usr/bin/env bash
set -euo pipefail

if [[ $# -lt 2 ]]; then
  echo "usage: $0 /absolute/harness-dir /absolute/roles.csv [ruflo-version]" >&2
  exit 2
fi

harness_dir="$1"
roles_file="$2"
ruflo_version="${3:-3.38.20}"

if [[ ! -f "$harness_dir/.claude-flow/config.yaml" || ! -f "$roles_file" ]]; then
  echo "missing Ruflo runtime or roles file" >&2
  exit 1
fi

stop_daemon() {
  (cd "$harness_dir" && npx --yes "ruflo@$ruflo_version" daemon stop >/dev/null 2>&1) || true
}
trap stop_daemon EXIT

log_file="$harness_dir/evidence/ruflo-ledger-$(date +%Y%m%dT%H%M%S).log"
mkdir -p "$(dirname "$log_file")"

run() {
  echo "+ $*" | tee -a "$log_file"
  (cd "$harness_dir" && "$@") 2>&1 | tee -a "$log_file"
}

max_agents="$(($(wc -l < "$roles_file") - 1))"
run npx --yes "ruflo@$ruflo_version" swarm init --topology hierarchical --max-agents "$max_agents"

tail -n +2 "$roles_file" | while IFS=',' read -r role_name agent_type task_type description tags write_scope; do
  agent_out="$(cd "$harness_dir" && npx --yes "ruflo@$ruflo_version" agent spawn --type "$agent_type" --name "$role_name" 2>&1)"
  printf '%s\n' "$agent_out" | tee -a "$log_file"
  agent_id="$(printf '%s\n' "$agent_out" | sed -n 's/.*\(agent-[0-9A-Za-z-]*\).*/\1/p' | head -1)"
  task_out="$(cd "$harness_dir" && npx --yes "ruflo@$ruflo_version" task create --type "$task_type" --description "$description" --priority high --tags "$tags" 2>&1)"
  printf '%s\n' "$task_out" | tee -a "$log_file"
  task_id="$(printf '%s\n' "$task_out" | sed -n 's/.*\(task-[0-9A-Za-z-]*\).*/\1/p' | head -1)"
  if [[ -z "$agent_id" || -z "$task_id" ]]; then
    echo "failed to parse Ruflo ids for role=$role_name" | tee -a "$log_file" >&2
    exit 1
  fi
  run npx --yes "ruflo@$ruflo_version" task assign "$task_id" --agent "$agent_id"
  echo "role=$role_name agent=$agent_id task=$task_id write_scope=$write_scope" | tee -a "$log_file"
done

echo "ledger_log=$log_file"
