#!/bin/bash

# start.sh - Start all services

echo "🚀 Starting PHP MCP SQL Agent..."

# Check if composer dependencies are installed
if [ ! -d "vendor" ]; then
    echo "📦 Installing composer dependencies..."
    composer install
fi

# Check if .env exists
if [ ! -f ".env" ]; then
    echo "⚠️  No .env file found. Copying from .env.example..."
    cp .env.example .env
    echo "⚠️  Please edit .env with your credentials before continuing."
    exit 1
fi

# Function to cleanup on exit
cleanup() {
    echo ""
    echo "🛑 Shutting down services..."
    kill $MCP_PID $API_PID 2>/dev/null
    exit 0
}

trap cleanup SIGINT SIGTERM

# Start MCP Server
echo "🔧 Starting MCP Server on port 8085..."
php -S 0.0.0.0:8085 mcp_server.php > mcp.log 2>&1 &
MCP_PID=$!
sleep 2

# Start API Server
echo "🌐 Starting API Server on port 3000..."
php -S 0.0.0.0:3000 endpoint.php > api.log 2>&1 &
API_PID=$!
sleep 2

echo ""
echo "┌────────────────────────────────────────────────────┐"
echo "│  ✅ All services are running!                      │"
echo "│                                                    │"
echo "│  MCP Server:  http://localhost:8085               │"
echo "│  API Server:  http://localhost:3000               │"
echo "│                                                    │"
echo "│  Endpoints:                                        │"
echo "│  - POST /chat                                      │"
echo "│  - GET  /health                                    │"
echo "│  - GET  /webhook/whatsapp                          │"
echo "│  - POST /webhook/whatsapp                          │"
echo "│                                                    │"
echo "│  Logs:                                             │"
echo "│  - MCP: tail -f mcp.log                           │"
echo "│  - API: tail -f api.log                           │"
echo "│                                                    │"
echo "│  Press Ctrl+C to stop all services                │"
echo "└────────────────────────────────────────────────────┘"
echo ""

# Wait for processes
wait
