#!/bin/bash

# Archipelago Docker Environment Startup Script
# This script starts all the containerized apps for development

set -e

echo "🏝️  Starting Archipelago Docker Environment..."
echo ""

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

# Check if docker-compose is available
if ! command -v docker-compose &> /dev/null && ! docker compose version &> /dev/null 2>&1; then
    echo "❌ docker-compose not found. Please install docker-compose."
    exit 1
fi

# Use docker compose (new) or docker-compose (old)
if docker compose version &> /dev/null 2>&1; then
    COMPOSE_CMD="docker compose"
else
    COMPOSE_CMD="docker-compose"
fi

# Check if this is first run (no images pulled)
FIRST_RUN=false
if ! docker images | grep -q "lncm/bitcoind\|homeassistant/home-assistant\|grafana/grafana"; then
    FIRST_RUN=true
    echo "📥 First run detected! This will download Docker images (~3-5GB)."
    echo "   This may take 10-30 minutes depending on your internet speed."
    echo ""
    read -p "   Continue? (y/N) " -n 1 -r
    echo ""
    if [[ ! $REPLY =~ ^[Yy]$ ]]; then
        echo "Cancelled."
        exit 0
    fi
fi

if [ "$FIRST_RUN" = "true" ]; then
    echo "📦 Pulling Docker images (this will take a while)..."
    echo "   💡 Tip: You can monitor progress in Docker Desktop"
    echo ""
    
    # Pull quietly to avoid terminal flooding
    $COMPOSE_CMD pull --quiet
    
    echo ""
    echo "✅ All images downloaded!"
else
    echo "📦 Checking for image updates (quietly)..."
    $COMPOSE_CMD pull --quiet 2>/dev/null || true
fi

echo ""
echo "🚀 Starting all containers..."
$COMPOSE_CMD up -d

echo ""
echo "⏳ Waiting for services to initialize..."
echo ""

# Give containers time to start
sleep 3

# Check health of key services (non-blocking, just for info)
echo "🔍 Checking service health (this may take 30-60 seconds)..."
READY_COUNT=0
MAX_ATTEMPTS=30
ATTEMPT=0

check_service() {
    local name=$1
    local url=$2
    if curl -sf "$url" > /dev/null 2>&1; then
        echo "   ✅ $name is ready"
        return 0
    else
        return 1
    fi
}

# Check services with retries
while [ $ATTEMPT -lt $MAX_ATTEMPTS ]; do
    READY_COUNT=0
    
    check_service "Grafana" "http://localhost:3000" && ((READY_COUNT++)) || true
    check_service "SearXNG" "http://localhost:8082" && ((READY_COUNT++)) || true
    check_service "Endurain" "http://localhost:8084" && ((READY_COUNT++)) || true
    check_service "MorphOS" "http://localhost:8081" && ((READY_COUNT++)) || true
    
    if [ $READY_COUNT -ge 2 ]; then
        echo "   ✅ Core services are ready!"
        break
    fi
    
    if [ $ATTEMPT -eq 0 ]; then
        echo "   ⏳ Services are starting (this is normal)..."
    fi
    
    sleep 2
    ((ATTEMPT++))
done

if [ $READY_COUNT -lt 2 ]; then
    echo ""
    echo "   ℹ️  Some services are still starting (this is normal)"
    echo "   💡 They will be available shortly. Check with: docker compose ps"
fi

echo ""
echo "📊 Container Status:"
$COMPOSE_CMD ps

echo ""
echo "🌐 Apps are available at:"
echo ""
echo "   💰 Bitcoin & Lightning:"
echo "      • Bitcoin Core UI:         http://localhost:18445"
echo "      • Bitcoin Core RPC:        localhost:18443"
echo "      • Lightning (LND) UI:      http://localhost:8085"
echo "      • Lightning REST API:      http://localhost:8080"
echo "      • BTCPay Server:           http://localhost:14142"
echo "      • Mempool Explorer:        http://localhost:4080"
echo "      • Fedimint (Guardian UI):  http://localhost:8175"
echo ""
echo "   🏠 Self-Hosted Services:"
echo "      • Home Assistant:          http://localhost:8123"
echo "      • Grafana:                 http://localhost:3000 (admin/admin)"
echo "      • SearXNG:                 http://localhost:8082"
echo "      • Ollama (API):            http://localhost:11434"
echo ""
echo "   📝 Collaboration:"
echo "      • OnlyOffice:              http://localhost:8083"
echo "      • Penpot:                  http://localhost:9001"
echo ""
echo "   🏃 Fitness & Tracking:"
echo "      • Endurain:                http://localhost:8084 (admin/admin)"
echo ""
echo "   🔄 Utilities:"
echo "      • Morphos File Converter:  http://localhost:8081"
echo ""
echo "   ☁️  Cloud Storage:"
echo "      • Nextcloud:               http://localhost:8086 (admin/admin)"
echo ""
echo "   🚧 Placeholders:"
echo "      • (None - all apps are real!)"
echo ""
echo "💡 Tips:"
echo "   • View logs:       $COMPOSE_CMD logs -f [service-name]"
echo "   • Stop all:        $COMPOSE_CMD down"
echo "   • Restart service: $COMPOSE_CMD restart [service-name]"
echo "   • Check status:    $COMPOSE_CMD ps"
echo ""
echo "🎉 Ready! Open http://localhost:8100 to access the Neode UI"
