#!/bin/sh

# Robust dependency installation script for Docker builds
# Handles both npm ci (with lock file) and npm install (fallback) scenarios

echo "=== Starting dependency installation ==="
echo "Current directory: $(pwd)"
echo "Files in current directory:"
ls -la

# Check if package.json exists
if [ ! -f "package.json" ]; then
    echo "ERROR: package.json not found!"
    exit 1
fi

echo "✓ package.json found"

# Check if package-lock.json exists
if [ -f "package-lock.json" ]; then
    echo "✓ package-lock.json found"
    echo "File size: $(ls -lh package-lock.json | awk '{print $5}')"
    echo "First few lines of package-lock.json:"
    head -10 package-lock.json
    
    # Try npm ci first
    echo "Attempting npm ci..."
    if npm ci; then
        echo "✓ npm ci succeeded"
        exit 0
    else
        echo "⚠ npm ci failed, falling back to npm install..."
    fi
else
    echo "⚠ package-lock.json not found, using npm install..."
fi

# Fallback to npm install
echo "Running npm install..."
if npm install; then
    echo "✓ npm install succeeded"
    # Generate package-lock.json if it doesn't exist
    if [ ! -f "package-lock.json" ]; then
        echo "✓ package-lock.json generated by npm install"
    fi
    exit 0
else
    echo "ERROR: npm install failed"
    exit 1
fi
