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

if [[ $# -ne 1 ]]; then
  echo "usage: $0 /absolute/runtime/root/harness" >&2
  exit 2
fi

harness_dir="$1"
ruflo_version="3.38.20"
script_dir="$(cd "$(dirname "$0")" && pwd)"
roles_file="$(cd "$script_dir/../config" && pwd)/roles.csv"

if [[ ! -f "$harness_dir/.claude-flow/config.yaml" ]]; then
  echo "Ruflo runtime not initialized: $harness_dir" >&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"
}

run npx --yes "ruflo@$ruflo_version" swarm init --topology hierarchical --max-agents 5

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 [[ -n "$agent_id" && -n "$task_id" ]]; then
    run npx --yes "ruflo@$ruflo_version" task assign "$task_id" --agent "$agent_id"
  else
    echo "failed to parse Ruflo ids for role=$role_name" | tee -a "$log_file" >&2
    exit 1
  fi
  echo "role=$role_name agent=$agent_id task=$task_id write_scope=$write_scope" | tee -a "$log_file"
done

echo "ledger_log=$log_file"
