#!/bin/bash

# Dynamic Multi-Agent Router System Setup Script

echo "🚀 Setting up Dynamic Multi-Agent Router System..."

# Check if Docker is running
if ! docker info > /dev/null 2>&1; then
    echo "❌ Docker is not running. Please start Docker first."
    exit 1
fi

echo "✅ Docker is running"

# Create necessary directories
echo "📁 Creating directories..."
mkdir -p agents workflows

# Check if agents directory has files
if [ ! "$(ls -A agents 2>/dev/null)" ]; then
    echo "⚠️  No agent files found in ./agents directory"
    echo "   Please ensure your agent files are in ./agents/"
    echo "   The system will use hardcoded agents as fallback"
fi

# Start the services
echo "🐳 Starting services with Docker Compose..."
docker-compose up -d

# Wait for services to be ready
echo "⏳ Waiting for services to start..."
sleep 10

# Check if n8n is accessible
echo "🔍 Checking n8n accessibility..."
if curl -s http://localhost:5678 > /dev/null; then
    echo "✅ n8n is accessible at http://localhost:5678"
else
    echo "❌ n8n is not accessible. Check Docker logs: docker-compose logs n8n"
fi

# Check if Ollama is accessible
echo "🔍 Checking Ollama accessibility..."
if curl -s http://localhost:11434/api/tags > /dev/null; then
    echo "✅ Ollama is accessible at http://localhost:11434"
    
    # Check if llama3.1 model is available
    if curl -s http://localhost:11434/api/tags | grep -q "llama3.1"; then
        echo "✅ llama3.1 model is available"
    else
        echo "⚠️  llama3.1 model not found. Pulling it now..."
        docker exec ollama-server ollama pull llama3.1
    fi
else
    echo "❌ Ollama is not accessible. Check Docker logs: docker-compose logs ollama"
fi

echo ""
echo "🎉 Setup complete!"
echo ""
echo "📋 Next steps:"
echo "1. Open n8n at http://localhost:5678"
echo "2. Login with admin/admin123"
echo "3. Import the workflow: n8n_agent_system_flow_working.json"
echo "4. Activate the workflow"
echo "5. Test with: curl -X POST http://localhost:5678/webhook/agent-task -H 'Content-Type: application/json' -d '{\"task\": \"Build a mobile app\"}'"
echo ""
echo "📚 For more information, see DYNAMIC_AGENT_SYSTEM_SETUP.md"
