#!/bin/bash
set -e

echo "🌐 Starting Rezepte Klaus for Local Network Access"
echo "=================================================="

# Function to detect host IP
detect_host_ip() {
    # Try different methods to get the local IP
    local ip=""
    
    # Method 1: macOS WiFi
    if command -v ipconfig &> /dev/null; then
        ip=$(ipconfig getifaddr en0 2>/dev/null || echo "")
        if [ -n "$ip" ]; then
            echo "$ip"
            return
        fi
        # Try Ethernet on macOS
        ip=$(ipconfig getifaddr en1 2>/dev/null || echo "")
        if [ -n "$ip" ]; then
            echo "$ip"
            return
        fi
    fi
    
    # Method 2: Linux/Unix
    if command -v ip &> /dev/null; then
        ip=$(ip route get 1 2>/dev/null | awk '{print $7; exit}' || echo "")
        if [ -n "$ip" ]; then
            echo "$ip"
            return
        fi
    fi
    
    # Method 3: Alternative Linux method
    if command -v hostname &> /dev/null; then
        ip=$(hostname -I 2>/dev/null | awk '{print $1}' || echo "")
        if [ -n "$ip" ]; then
            echo "$ip"
            return
        fi
    fi
    
    # Fallback
    echo "192.168.1.100"
}

# Detect the host IP
HOST_IP=$(detect_host_ip)

echo "🔍 Detected Host IP: $HOST_IP"
echo ""

# Verify IP looks valid
if [[ ! $HOST_IP =~ ^[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}$ ]]; then
    echo "⚠️  Warning: Detected IP '$HOST_IP' doesn't look valid."
    echo "Please check your network connection or manually set HOST_IP in .env.local-network"
    echo ""
    read -p "Do you want to continue anyway? (y/N): " -n 1 -r
    echo
    if [[ ! $REPLY =~ ^[Yy]$ ]]; then
        exit 1
    fi
fi

# Export HOST_IP for docker compose
export HOST_IP

echo "🛑 Stopping any existing containers..."
docker compose -f docker compose.local-network.yml down

echo "🏗️  Building and starting containers for local network access..."
docker compose -f docker compose.local-network.yml up --build -d

echo "⏳ Waiting for services to start..."
sleep 20

echo "🔍 Checking service health..."
if docker compose -f docker compose.local-network.yml ps | grep -q "Up"; then
    echo "✅ Services started successfully!"
    echo ""
    echo "🌐 Your application is now accessible from:"
    echo "   Local machine: http://localhost:3000"
    echo "   Network access: http://$HOST_IP:3000"
    echo "   API endpoint: http://$HOST_IP:3001/api"
    echo ""
    echo "📊 Service Status:"
    docker compose -f docker compose.local-network.yml ps
    echo ""
    echo "💡 Share this URL with other devices on your network:"
    echo "   http://$HOST_IP:3000"
else
    echo "❌ Failed to start services. Check logs:"
    docker compose -f docker compose.local-network.yml logs --tail=20
    exit 1
fi

echo ""
echo "📋 Useful commands:"
echo "  View logs: docker compose -f docker compose.local-network.yml logs -f"
echo "  Stop: docker compose -f docker compose.local-network.yml down"
echo "  Restart: docker compose -f docker compose.local-network.yml restart"