#!/bin/bash
# Cortex Hub Setup Script

set -e

echo "=========================================="
echo "⚡ Cortex Hub - Interactive Setup Wizard"
echo "=========================================="
echo ""

# Optional Day 0 Prefill config
CONFIG_FILE=$1

if [ -n "$CONFIG_FILE" ] && [ -f "$CONFIG_FILE" ]; then
    echo "📄 Utilizing provided configuration file: $CONFIG_FILE"
    cp "$CONFIG_FILE" ./config.yaml
else
    if [ ! -f "config.yaml" ]; then
        touch config.yaml
    fi
    echo "💡 No prefill config file provided. An empty config.yaml will be initialized."
    echo "   (You can configure LLM providers later in the Web UI)."
    echo "   To prefill, run: ./setup.sh my_config.yaml"
fi
echo ""

# 1. Prompt for Admin Email
read -p "Enter Admin Email (e.g., admin@example.com): " ADMIN_EMAIL
if [ -z "$ADMIN_EMAIL" ]; then
    echo "❌ Error: Admin Email is required."
    exit 1
fi

# 2. Auto-generate Secrets
echo ""
echo "Generating secure keys..."
SECRET_KEY=$(openssl rand -hex 32)
ADMIN_PASSWORD=$(openssl rand -base64 12)

echo "Creating .env file..."
cat <<EOF > .env
SUPER_ADMINS=${ADMIN_EMAIL}
CORTEX_ADMIN_PASSWORD=${ADMIN_PASSWORD}
SECRET_KEY=${SECRET_KEY}
EOF

# 3. Bring up Docker Services
echo "Starting services via Docker Compose..."
if command -v docker-compose &> /dev/null; then
    docker-compose up -d --build
elif docker compose version &> /dev/null; then
    docker compose up -d --build
else
    echo "❌ Error: Docker Compose is not installed."
    echo "Please install it and run 'docker-compose up -d'"
    exit 1
fi

echo "🏗️ Building standalone Agent Node binaries (this may take a few minutes)..."
if [ -f "agent-node/scripts/build_binaries.sh" ]; then
    bash agent-node/scripts/build_binaries.sh
else
    echo "⚠️ agent-node/scripts/build_binaries.sh not found, skipping binary build."
fi

echo ""
echo "=========================================="
echo "✅ Setup Complete!"
echo "=========================================="
echo ""
echo "🌐 Access the Hub UI: http://localhost:8002 (or your server IP)"
echo "👤 Admin Email:      ${ADMIN_EMAIL}"
echo "🔑 Initial Password: ${ADMIN_PASSWORD}"
echo ""
echo "Please save your password safely! You can change it later in the UI."
echo "=========================================="
echo ""
echo "💡 Looking to attach a Node? "
echo "   1. Login to the Hub UI and generate an Invite Token."
echo "   2. Run: ./add_node.sh"
echo "=========================================="
