#!/bin/bash
# Switch active Runabout config and restart dispatch
# Usage: runabout-agent [agent-name]   (no args = show current)

CONFIG_DIR="/etc/runabout"
ACTIVE="$CONFIG_DIR/config.json"

if [ -z "$1" ]; then
  echo "Active: $(python3 -c "import json; d=json.load(open('$ACTIVE')); print(d['agent']+' ('+d['display_name']+')')" 2>/dev/null || echo "unknown")"
  echo "Available: $(ls $CONFIG_DIR/*.json 2>/dev/null | grep -v config.json | xargs -n1 basename | sed 's/.json//')"
  exit 0
fi

SRC="$CONFIG_DIR/$1.json"
if [ ! -f "$SRC" ]; then
  echo "Unknown agent: $1 (no $SRC)" >&2
  echo "Available: $(ls $CONFIG_DIR/*.json 2>/dev/null | grep -v config.json | xargs -n1 basename | sed 's/.json//')" >&2
  exit 1
fi

cp "$SRC" "$ACTIVE"
DISPLAY_NAME=$(python3 -c "import json; print(json.load(open('$ACTIVE'))['display_name'])" 2>/dev/null || echo "$1")
echo "Runabout → $DISPLAY_NAME"

# Restart dispatch for new agent
if systemctl is-active runabout-dispatch.service -q 2>/dev/null; then
  systemctl restart runabout-dispatch.service
  echo "Dispatch restarted"
fi
