#!/bin/bash
set -e

# Host-specific override (e.g. CONTROL_PLANE_URL for runtime-materializer) — same
# convention as services/control-plane/deploy-local.sh. agent-system currently
# only runs on piha, so this is hardcoded like control-plane hardcodes vps.
COMPOSE_ARGS="-f docker-compose.yml"
OVERRIDE_FILE="../../hosts/piha/runtime/agent-system/docker-compose.override.yml"
if [ -f "$OVERRIDE_FILE" ]; then
    echo ">>> Using override: $OVERRIDE_FILE"
    COMPOSE_ARGS="$COMPOSE_ARGS -f $OVERRIDE_FILE"
fi

echo ">>> Validating docker-compose configuration..."
docker compose $COMPOSE_ARGS config

echo ">>> Building and starting Agent System services..."
docker compose $COMPOSE_ARGS up -d --build

echo ">>> Services status:"
docker ps --filter "name=agent-system" --format "table {{.Names}}\t{{.Status}}\t{{.Ports}}"

if [ -z "$TELEGRAM_BOT_TOKEN" ]; then
  echo ">>> Telegram bot status: DISABLED (token missing)"
else
  echo ">>> Telegram bot status: ENABLED"
fi

echo ">>> Verifying API endpoints..."
sleep 5 # Give it a moment to start

endpoints=("summary" "nodes" "services")
for ep in "${endpoints[@]}"; do
  echo "Checking /$ep..."
  curl -s -f http://localhost:18180/$ep > /dev/null && echo "  OK" || echo "  FAILED"
done

echo ">>> Deployment complete."
