#!/bin/bash
set -e

echo "🐧 Setting up Rezepte Klaus for Remote Development on Linux"
echo "=========================================================="

# Check if we're on a Linux system
if [[ "$OSTYPE" != "linux-gnu"* ]]; then
    echo "⚠️  Warning: This script is optimized for Linux servers"
fi

# Check if Docker is installed
if ! command -v docker &> /dev/null; then
    echo "❌ Docker is not installed. Please install Docker first:"
    echo "   curl -fsSL https://get.docker.com -o get-docker.sh"
    echo "   sudo sh get-docker.sh"
    exit 1
fi

# Check if Docker Compose plugin is available
if ! docker compose version &> /dev/null; then
    echo "❌ Docker Compose plugin is not available. Please install Docker with Compose plugin:"
    echo "   Modern Docker installations include Compose plugin by default"
    echo "   Alternative: sudo apt install docker-compose-plugin"
    exit 1
fi

# Detect Linux distribution for IP detection
if command -v ip &> /dev/null; then
    HOST_IP=$(ip route get 1.1.1.1 | grep -oP 'src \K\S+' 2>/dev/null || echo "")
elif command -v hostname &> /dev/null; then
    HOST_IP=$(hostname -I | awk '{print $1}' 2>/dev/null || echo "")
else
    echo "⚠️  Could not detect IP automatically. Please check manually:"
    echo "   ip addr show"
    HOST_IP="YOUR_SERVER_IP"
fi

if [ -z "$HOST_IP" ] || [ "$HOST_IP" = "YOUR_SERVER_IP" ]; then
    echo "❌ Could not detect server IP. Please find your server IP:"
    echo "   ip addr show | grep 'inet '"
    echo "   hostname -I"
    exit 1
fi

echo "🔍 Detected Server IP: $HOST_IP"

# Create development environment file
echo "📝 Creating development environment configuration..."
cat > .env.development << EOF
# Development Environment - Linux Server
# Generated on $(date)

# Server Configuration
HOST_IP=$HOST_IP
DEVELOPMENT_MODE=true

# Database Configuration (local development DB)
MYSQL_PASSWORD=dev_password_123
MYSQL_ROOT_PASSWORD=dev_root_password_123

# CORS Configuration for remote access
CORS_ORIGIN=*

# Development URLs:
# - Frontend: http://$HOST_IP:3000
# - Backend API: http://$HOST_IP:3001/api
# - phpMyAdmin: http://$HOST_IP:8080
# - MySQL: $HOST_IP:3307

# Registry Configuration (for image pulls)
DOCKER_REGISTRY=docker.citysensor.de
# DOCKER_USERNAME=your_username
# DOCKER_PASSWORD=your_password

# Development Notes:
# - Use this for testing Linux-specific behavior
# - Access from Mac via: http://$HOST_IP:3000
# - SSH tunnel for secure access: ssh -L 3000:$HOST_IP:3000 user@server
EOF

echo "✅ Created .env.development with server IP: $HOST_IP"

# Create development-specific docker-compose
echo "📝 Creating development docker-compose configuration..."
cat > docker-compose.development.yml << 'EOF'
services:
  mysql:
    image: mysql:8.0
    container_name: rezepte-mysql-dev
    restart: unless-stopped
    environment:
      - MYSQL_DATABASE=rezepte_klaus
      - MYSQL_USER=rezepte
      - MYSQL_PASSWORD=${MYSQL_PASSWORD}
      - MYSQL_ROOT_PASSWORD=${MYSQL_ROOT_PASSWORD}
    ports:
      - "0.0.0.0:3307:3306"
    volumes:
      - mysql_dev_data:/var/lib/mysql
      # Initialize with data
      - ./Rezepte.sql:/docker-entrypoint-initdb.d/01-Rezepte.sql
      - ./ingredients.sql:/docker-entrypoint-initdb.d/02-ingredients.sql
      - ./Zubereitung.sql:/docker-entrypoint-initdb.d/03-Zubereitung.sql
      - ./rezepte_bilder.sql:/docker-entrypoint-initdb.d/04-rezepte_bilder.sql
    healthcheck:
      test: ["CMD", "mysqladmin", "ping", "-h", "localhost", "-u", "root", "-p${MYSQL_ROOT_PASSWORD}"]
      interval: 30s
      timeout: 10s
      retries: 5
    networks:
      - rezepte-network

  backend:
    build:
      context: ./nodejs-version/backend
      dockerfile: Dockerfile
    container_name: rezepte-backend-dev
    restart: unless-stopped
    environment:
      - NODE_ENV=development
      - DATABASE_URL=mysql://rezepte:${MYSQL_PASSWORD}@mysql:3306/rezepte_klaus
      - CORS_ORIGIN=${CORS_ORIGIN:-*}
      - PORT=3001
    ports:
      - "0.0.0.0:3001:3001"
    volumes:
      - uploads_dev_data:/app/uploads
      # Development: Mount source code for hot reload
      - ./nodejs-version/backend/src:/app/src:ro
      - ./nodejs-version/backend/prisma:/app/prisma:ro
    depends_on:
      mysql:
        condition: service_healthy
    healthcheck:
      test: ["CMD", "curl", "-f", "http://localhost:3001/api/health"]
      interval: 30s
      timeout: 10s
      retries: 3
    networks:
      - rezepte-network

  frontend:
    build:
      context: ./nodejs-version/frontend
      dockerfile: Dockerfile
    container_name: rezepte-frontend-dev
    restart: unless-stopped
    ports:
      - "0.0.0.0:3000:80"
    depends_on:
      - backend
    healthcheck:
      test: ["CMD", "curl", "-f", "http://localhost/"]
      interval: 30s
      timeout: 10s
      retries: 3
    networks:
      - rezepte-network

  phpmyadmin:
    image: phpmyadmin/phpmyadmin:latest
    container_name: rezepte-phpmyadmin-dev
    restart: unless-stopped
    environment:
      - PMA_HOST=mysql
      - PMA_PORT=3306
      - PMA_USER=root
      - PMA_PASSWORD=${MYSQL_ROOT_PASSWORD}
      - UPLOAD_LIMIT=2G
      - MEMORY_LIMIT=2G
    ports:
      - "0.0.0.0:8080:80"
    depends_on:
      mysql:
        condition: service_healthy
    networks:
      - rezepte-network

volumes:
  mysql_dev_data:
    driver: local
  uploads_dev_data:
    driver: local

networks:
  rezepte-network:
    driver: bridge
EOF

echo "✅ Created docker-compose.development.yml"

# Create development startup script
echo "📝 Creating development startup script..."
cat > start-development.sh << 'EOF'
#!/bin/bash
set -e

echo "🚀 Starting Rezepte Klaus Development Environment on Linux"
echo "========================================================="

# Load environment variables
if [ -f .env.development ]; then
    export $(cat .env.development | grep -v '^#' | xargs)
else
    echo "❌ Error: .env.development file not found!"
    echo "Please run setup-development.sh first."
    exit 1
fi

echo "🔍 Server IP: $HOST_IP"

# Stop any existing containers
echo "🛑 Stopping existing containers..."
docker compose -f docker-compose.development.yml down

# Build and start services
echo "🏗️  Building and starting services..."
docker compose -f docker-compose.development.yml up -d --build

# Wait for services
echo "⏳ Waiting for services to start..."
sleep 30

# Check service health
echo "🔍 Checking service health..."
HEALTHY_SERVICES=$(docker compose -f docker-compose.development.yml ps --filter "status=running" | grep -c "Up" || true)

if [ "$HEALTHY_SERVICES" -ge 4 ]; then
    echo "✅ Development environment started successfully!"
    echo ""
    echo "🌐 Access URLs:"
    echo "   Frontend: http://$HOST_IP:3000"
    echo "   Backend API: http://$HOST_IP:3001/api"
    echo "   phpMyAdmin: http://$HOST_IP:8080"
    echo ""
    echo "🔒 SSH Tunnel (for secure access from Mac):"
    echo "   ssh -L 3000:localhost:3000 -L 3001:localhost:3001 -L 8080:localhost:8080 user@$HOST_IP"
    echo "   Then access: http://localhost:3000"
    echo ""
    echo "📊 Service Status:"
    docker compose -f docker-compose.development.yml ps
else
    echo "❌ Some services failed to start. Check logs:"
    docker compose -f docker-compose.development.yml logs --tail=20
fi

echo ""
echo "📋 Development Commands:"
echo "  View logs: docker compose -f docker-compose.development.yml logs -f"
echo "  Rebuild frontend: docker compose -f docker-compose.development.yml build frontend && docker compose -f docker-compose.development.yml restart frontend"
echo "  Rebuild backend: docker compose -f docker-compose.development.yml build backend && docker compose -f docker-compose.development.yml restart backend"
echo "  Stop: docker compose -f docker-compose.development.yml down"
EOF

chmod +x start-development.sh
echo "✅ Created executable start-development.sh"

echo ""
echo "🎯 Setup completed! Next steps:"
echo ""
echo "1. 📝 Review configuration:"
echo "   cat .env.development"
echo ""
echo "2. 🚀 Start development environment:"
echo "   ./start-development.sh"
echo ""
echo "3. 🌐 Access from your Mac:"
echo "   Direct: http://$HOST_IP:3000"
echo "   SSH Tunnel: ssh -L 3000:localhost:3000 user@$HOST_IP"
echo ""
echo "4. 🔄 For code changes:"
echo "   - Edit files locally on Mac"
echo "   - Sync to server (git, rsync, or VS Code Remote)"
echo "   - Rebuild containers as needed"
EOF