#!/bin/bash

# Quick API restart script
# Finds and kills the running API, then restarts it

echo "🔄 Restarting Aumentum API..."
echo ""

# Find and kill existing API process
API_PID=$(ps aux | grep "python3.*aumentum_api.py" | grep -v grep | awk '{print $2}')

if [ -n "$API_PID" ]; then
    echo "⏹️  Stopping existing API (PID: $API_PID)..."
    kill $API_PID
    sleep 2
    
    # Force kill if still running
    if ps -p $API_PID > /dev/null 2>&1; then
        echo "   Force killing..."
        kill -9 $API_PID
        sleep 1
    fi
    
    echo "   ✅ Stopped"
else
    echo "ℹ️  No existing API process found"
fi

echo ""
echo "🚀 Starting API..."
echo "   Port: 8001"
echo "   Logs: server.log"
echo ""

# Activate virtual environment if it exists
if [ -d "venv" ]; then
    echo "   🐍 Activating virtual environment..."
    source venv/bin/activate
fi

# Start API in background
nohup python3 aumentum_api.py > server.log 2>&1 &
NEW_PID=$!

sleep 2

# Check if it started successfully
if ps -p $NEW_PID > /dev/null 2>&1; then
    echo "✅ API started successfully (PID: $NEW_PID)"
    echo ""
    echo "📊 Testing health check..."
    
    # Wait a bit more for API to be ready
    sleep 2
    
    # Test health endpoint
    HEALTH_STATUS=$(curl -s -o /dev/null -w "%{http_code}" http://localhost:8001/health)
    
    if [ "$HEALTH_STATUS" = "200" ]; then
        echo "   ✅ API is healthy and ready"
    else
        echo "   ⚠️  API started but health check returned: $HEALTH_STATUS"
        echo "   Check server.log for details"
    fi
    
    echo ""
    echo "📝 Recent log output:"
    echo "-------------------"
    tail -20 server.log
    echo "-------------------"
    echo ""
    echo "💡 View live logs: tail -f server.log"
    echo "💡 Stop API: kill $NEW_PID"
    
else
    echo "❌ Failed to start API"
    echo "   Check server.log for errors:"
    tail -20 server.log
    exit 1
fi


