#!/usr/bin/env bash
# verify-agent-fleet.sh - Check the status of stability agents across the fleet

REDIS_CMD="docker exec agent-system-redis redis-cli --raw"

# Check if docker is available
if ! command -v docker &> /dev/null; then
    echo "Error: docker command not found."
    exit 1
fi

# Check if container is running
if ! docker ps --filter "name=agent-system-redis" --format "{{.Names}}" | grep -q "agent-system-redis"; then
    echo "Error: agent-system-redis container not found or not running."
    echo "This script must be run on PIHA (the node hosting the Redis container)."
    exit 1
fi

REQUIRED_NODES=("piha" "chelsty" "solaria" "vps")
MISSING_NODES=0

echo "--- Homelab Agent Fleet Status ---"
printf "%-10s %-15s %-10s %-10s %-30s\n" "NODE" "HOSTNAME" "HEALTH" "STATUS" "LAST_SEEN"
printf "%s\n" "--------------------------------------------------------------------------------"

for NODE in "${REQUIRED_NODES[@]}"; do
    KEY="homelab:nodes:$NODE"
    
    # Check if key exists
    EXISTS=$($REDIS_CMD EXISTS "$KEY" 2>/dev/null | tr -d '\r\n')

    if [[ "$EXISTS" != "1" ]]; then
        printf "%-10s %-15s %-10s %-10s %-30s\n" "$NODE" "MISSING" "N/A" "N/A" "N/A"
        MISSING_NODES=$((MISSING_NODES + 1))
        continue
    fi

    HOSTNAME=$($REDIS_CMD HGET "$KEY" hostname 2>/dev/null | tr -d '\r\n')
    HEALTH=$($REDIS_CMD HGET "$KEY" health 2>/dev/null | tr -d '\r\n')
    STATUS=$($REDIS_CMD HGET "$KEY" status 2>/dev/null | tr -d '\r\n')
    LAST_SEEN=$($REDIS_CMD HGET "$KEY" last_seen 2>/dev/null | tr -d '\r\n')

    printf "%-10s %-15s %-10s %-10s %-30s\n" "$NODE" "$HOSTNAME" "$HEALTH" "$STATUS" "$LAST_SEEN"
done

echo ""
echo "--- Control Plane Summary ---"
if command -v jq >/dev/null; then
    curl -s http://127.0.0.1:18180/summary | jq .
else
    curl -s http://127.0.0.1:18180/summary
fi

echo ""
echo "--- Control Plane Nodes ---"
if command -v jq >/dev/null; then
    curl -s http://127.0.0.1:18180/nodes | jq .
else
    curl -s http://127.0.0.1:18180/nodes
fi

if [[ $MISSING_NODES -gt 0 ]]; then
    echo ""
    echo "Error: $MISSING_NODES required nodes are missing from Redis."
    exit 1
fi

exit 0
