#!/bin/bash
# Script to provision an attached Agent Node to the Cortex Hub.

set -e

echo "=========================================="
echo "⚡ Cortex Hub - Add Agent Node"
echo "=========================================="
echo ""

if [ -z "$1" ]; then
    read -p "Enter Node ID (e.g. sandbox-node): " AGENT_NODE_ID
else
    AGENT_NODE_ID=$1
fi

if [ -z "$2" ]; then
    read -p "Enter Agent Auth Token (Generated from UI): " AGENT_AUTH_TOKEN
else
    AGENT_AUTH_TOKEN=$2
fi

if [ -z "$3" ]; then
    read -p "Enter gRPC Endpoint [Default for local docker: ai_hub_service:50051]: " GRPC_ENDPOINT
    GRPC_ENDPOINT=${GRPC_ENDPOINT:-ai_hub_service:50051}
else
    GRPC_ENDPOINT=$3
fi

export AGENT_NODE_ID
export AGENT_AUTH_TOKEN
export GRPC_ENDPOINT

# Load the symmetric SECRET_KEY if present for encryption
if [ -f ".env" ]; then
    export $(grep -v '^#' .env | xargs)
fi
export AGENT_SECRET_KEY=${SECRET_KEY:-default-insecure-key}

echo ""
echo "Starting Node: ${AGENT_NODE_ID}..."

if command -v docker-compose &> /dev/null; then
    docker-compose -f docker-compose.node.yml -p "cortex-node-${AGENT_NODE_ID}" up -d --build
elif docker compose version &> /dev/null; then
    docker compose -f docker-compose.node.yml -p "cortex-node-${AGENT_NODE_ID}" up -d --build
else
    echo "❌ Error: Docker Compose is not installed."
    exit 1
fi

# Attach it to the main cortex-hub_default network to ensure it can hit ai_hub_service directly.
if docker network inspect cortex-hub_default &> /dev/null; then
    docker network connect cortex-hub_default "cortex_sandbox_node" || true
fi

echo ""
echo "✅ Node '${AGENT_NODE_ID}' has been spun up in the background."
echo "Use the Web Dashboard to verify its connection status."
