#!/bin/bash

# Start AI Debug Phoenix Server with Dynamic Port Allocation
# This allows you to run multiple Phoenix projects simultaneously

echo "🔬 Starting AI Debug Phoenix Server..."
echo "⚙️  Checking for available ports starting from 9090..."

# You can override the port by setting AI_DEBUG_PORT environment variable
# Example: AI_DEBUG_PORT=9091 ./start_ai_debug.sh

if [ -n "$AI_DEBUG_PORT" ]; then
    echo "🎯 Using specified port: $AI_DEBUG_PORT"
else
    echo "🔍 Auto-detecting available port..."
fi

# Start the server
echo "🚀 Launching Phoenix server..."
echo ""
echo "📋 Server Information:"
echo "   • Project: AI Debug Local MCP"
echo "   • Purpose: Debug other Phoenix projects and web applications"
echo "   • Safe for concurrent development"
echo ""

# Start Phoenix and capture the output to show the actual port
mix phx.server 2>&1 | tee >(grep -o "localhost:[0-9]*" | head -1 | while read url; do
    echo ""
    echo "✅ AI Debug Server is running!"
    echo "🌐 Access at: http://$url"
    echo "🔧 Use this URL with inject_debugging tool"
    echo ""
    echo "💡 Tips for multiple Phoenix projects:"
    echo "   • Your other Phoenix project can use any port (3000, 4000, etc.)"
    echo "   • AI Debug automatically found an available port"
    echo "   • Set AI_DEBUG_PORT=XXXX to force a specific port"
    echo ""
done)