#!/bin/bash
set -e

# Colors for output
RED='\033[0;31m'
GREEN='\033[0;32m'
BLUE='\033[0;34m'
YELLOW='\033[1;33m'
NC='\033[0m' # No Color

echo_info() {
    echo -e "${BLUE}📦 $1${NC}"
}

echo_success() {
    echo -e "${GREEN}✅ $1${NC}"
}

echo_warning() {
    echo -e "${YELLOW}⚠️  $1${NC}"
}

echo_error() {
    echo -e "${RED}❌ $1${NC}"
}

# Ensure we're in the app directory
cd /app

# Create node_modules directory if it doesn't exist
mkdir -p /app/node_modules

# Files to track changes
PACKAGE_JSON="/app/package.json"
YARN_LOCK="/app/yarn.lock"
HASH_FILE="/app/node_modules/.dependency-hashes"
INSTALL_RESULT_FILE="/app/node_modules/.install-result"

# Check if required files exist
if [ ! -f "$PACKAGE_JSON" ]; then
    echo_error "package.json not found at $PACKAGE_JSON"
    echo "1" > "$INSTALL_RESULT_FILE"
    exit 1
fi

# Calculate hashes for change detection
echo_info "Calculating dependency hashes..."
PACKAGE_HASH=$(md5sum "$PACKAGE_JSON" | cut -d' ' -f1)
LOCK_HASH=""
if [ -f "$YARN_LOCK" ]; then
    LOCK_HASH=$(md5sum "$YARN_LOCK" | cut -d' ' -f1)
fi

echo_info "Package hash: $PACKAGE_HASH"
echo_info "Lock hash: $LOCK_HASH"

# Determine if we need to install
NEED_INSTALL=false
INSTALL_REASON=""

if [ ! -f "$HASH_FILE" ]; then
    NEED_INSTALL=true
    INSTALL_REASON="First run or hash file missing"
elif [ ! -d "/app/node_modules" ] || [ -z "$(ls -A /app/node_modules 2>/dev/null)" ]; then
    NEED_INSTALL=true
    INSTALL_REASON="Node modules missing or empty"
else
    # Check if hashes changed
    STORED_HASHES=$(cat "$HASH_FILE" 2>/dev/null || echo "")
    CURRENT_HASHES="$PACKAGE_HASH:$LOCK_HASH"
    
    if [ "$STORED_HASHES" != "$CURRENT_HASHES" ]; then
        NEED_INSTALL=true
        INSTALL_REASON="Dependencies changed"
        echo_info "Stored hashes: $STORED_HASHES"
        echo_info "Current hashes: $CURRENT_HASHES"
    fi
fi

if [ "$NEED_INSTALL" = true ]; then
    echo_info "$INSTALL_REASON, installing dependencies..."
    
    # Backup yarn.lock if it exists (for rollback in case of failure)
    YARN_LOCK_BACKUP=""
    if [ -f "$YARN_LOCK" ]; then
        YARN_LOCK_BACKUP="/tmp/yarn.lock.backup"
        cp "$YARN_LOCK" "$YARN_LOCK_BACKUP"
        echo_info "Backed up yarn.lock"
    fi
    
    # Install dependencies
    echo_info "Running yarn install..."
    if yarn install --network-timeout 300000; then
        INSTALL_EXIT_CODE=0
        echo_success "Dependencies installed successfully"
        
        # Calculate new lock file hash
        NEW_LOCK_HASH=""
        if [ -f "$YARN_LOCK" ]; then
            NEW_LOCK_HASH=$(md5sum "$YARN_LOCK" | cut -d' ' -f1)
        fi
        
        # Save current state
        NEW_HASHES="$PACKAGE_HASH:$NEW_LOCK_HASH"
        echo "$NEW_HASHES" > "$HASH_FILE"
        echo_success "Saved dependency hashes: $NEW_HASHES"
        
        # Clean up backup
        if [ -n "$YARN_LOCK_BACKUP" ] && [ -f "$YARN_LOCK_BACKUP" ]; then
            rm "$YARN_LOCK_BACKUP"
        fi
        
    else
        INSTALL_EXIT_CODE=$?
        echo_error "Yarn install failed with exit code $INSTALL_EXIT_CODE"
        
        # Restore yarn.lock backup if installation failed
        if [ -n "$YARN_LOCK_BACKUP" ] && [ -f "$YARN_LOCK_BACKUP" ]; then
            echo_warning "Restoring yarn.lock backup due to installation failure"
            cp "$YARN_LOCK_BACKUP" "$YARN_LOCK"
            rm "$YARN_LOCK_BACKUP"
        fi
    fi
    
    # Save exit code for external monitoring
    echo "$INSTALL_EXIT_CODE" > "$INSTALL_RESULT_FILE"
    
    if [ $INSTALL_EXIT_CODE -eq 0 ]; then
        echo_success "Dependency installation completed successfully"
    else
        echo_error "Dependency installation failed"
        # Don't exit here - let the main process continue and handle the error
    fi
    
else
    echo_success "Dependencies are up to date, skipping installation"
    echo "0" > "$INSTALL_RESULT_FILE"
fi

# Additional health checks
echo_info "Performing health checks..."

# Check if critical packages are available
HEALTH_CHECK_FAILED=false

# For frontend services, check if Vue/React is available
if [ -f "/app/package.json" ]; then
    if grep -q '"vue"' /app/package.json; then
        if ! yarn list vue > /dev/null 2>&1; then
            echo_warning "Vue is listed in package.json but not found in node_modules"
            HEALTH_CHECK_FAILED=true
        fi
    fi
    
    if grep -q '"react"' /app/package.json; then
        if ! yarn list react > /dev/null 2>&1; then
            echo_warning "React is listed in package.json but not found in node_modules"
            HEALTH_CHECK_FAILED=true
        fi
    fi
fi

# Check if node_modules has reasonable content
NODE_MODULES_COUNT=$(find /app/node_modules -maxdepth 1 -type d | wc -l)
if [ "$NODE_MODULES_COUNT" -lt 5 ]; then
    echo_warning "Very few packages in node_modules ($NODE_MODULES_COUNT directories)"
    HEALTH_CHECK_FAILED=true
fi

if [ "$HEALTH_CHECK_FAILED" = true ]; then
    echo_warning "Health checks detected potential issues, but continuing..."
fi

# Display final status
echo_info "Dependency check completed!"
echo_info "Final status: $(cat $INSTALL_RESULT_FILE)"

# Continue with the original command that was passed to this script
if [ $# -gt 0 ]; then
    echo_info "Executing command: $@"
    exec "$@"
else
    echo_info "No command provided, dependency check complete"
fi