#!/bin/bash
# Install Dependencies Script
# This script installs all required dependencies for the PunimTag Photo Viewer
# including npm packages, system dependencies, and Prisma clients

set -e  # Exit on error

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
PROJECT_DIR="$(cd "$SCRIPT_DIR/.." && pwd)"

cd "$PROJECT_DIR"

echo "🚀 Installing PunimTag Photo Viewer Dependencies"
echo "================================================"
echo ""

# Check Node.js version
echo "📋 Checking Node.js version..."
NODE_VERSION=$(node --version | cut -d'v' -f2 | cut -d'.' -f1)
if [ "$NODE_VERSION" -lt 20 ]; then
    echo "⚠️  Warning: Node.js 20+ is recommended (found v$NODE_VERSION)"
    echo "   Consider upgrading: nvm install 20 && nvm use 20"
    read -p "Continue anyway? (y/N) " -n 1 -r
    echo
    if [[ ! $REPLY =~ ^[Yy]$ ]]; then
        exit 1
    fi
else
    echo "✅ Node.js version: $(node --version)"
fi
echo ""

# Check for system dependencies
echo "📦 Checking system dependencies..."
MISSING_DEPS=()

# Check for libvips (optional but recommended)
if ! command -v vips &> /dev/null && ! dpkg -l | grep -q libvips-dev; then
    echo "⚠️  libvips-dev not found (optional, for image watermarking)"
    MISSING_DEPS+=("libvips-dev")
fi

# Check for FFmpeg (optional)
if ! command -v ffmpeg &> /dev/null; then
    echo "⚠️  FFmpeg not found (optional, for video thumbnails)"
    MISSING_DEPS+=("ffmpeg")
fi

if [ ${#MISSING_DEPS[@]} -gt 0 ]; then
    echo ""
    echo "Optional system dependencies not installed:"
    for dep in "${MISSING_DEPS[@]}"; do
        echo "  - $dep"
    done
    echo ""
    read -p "Install optional dependencies? (y/N) " -n 1 -r
    echo
    if [[ $REPLY =~ ^[Yy]$ ]]; then
        echo "Installing system dependencies..."
        if command -v apt-get &> /dev/null; then
            sudo apt-get update
            for dep in "${MISSING_DEPS[@]}"; do
                if [ "$dep" = "libvips-dev" ]; then
                    sudo apt-get install -y libvips-dev
                elif [ "$dep" = "ffmpeg" ]; then
                    sudo apt-get install -y ffmpeg
                fi
            done
        elif command -v brew &> /dev/null; then
            for dep in "${MISSING_DEPS[@]}"; do
                if [ "$dep" = "libvips-dev" ]; then
                    brew install vips
                elif [ "$dep" = "ffmpeg" ]; then
                    brew install ffmpeg
                fi
            done
        else
            echo "⚠️  Please install dependencies manually for your system"
        fi
    fi
else
    echo "✅ All system dependencies found"
fi
echo ""

# Install npm dependencies
echo "📦 Installing npm dependencies..."
npm install
echo "✅ npm dependencies installed"
echo ""

# Install build tools for Sharp (if needed)
if [ -d "node_modules/sharp" ]; then
    echo "🔧 Setting up Sharp image processing library..."
    
    # Check if Sharp can load
    if node -e "try { require('sharp'); console.log('OK'); } catch(e) { console.log('FAIL'); process.exit(1); }" 2>/dev/null; then
        echo "✅ Sharp is working correctly"
    else
        echo "⚠️  Sharp needs additional setup..."
        
        # Install build dependencies if not present
        if ! npm list node-gyp &> /dev/null; then
            echo "   Installing node-gyp..."
            npm install --save-dev node-gyp
        fi
        
        if ! npm list node-addon-api &> /dev/null; then
            echo "   Installing node-addon-api..."
            npm install --save-dev node-addon-api
        fi
        
        # Try to rebuild Sharp
        echo "   Attempting to rebuild Sharp..."
        npm rebuild sharp || echo "   ⚠️  Sharp rebuild failed, but wrapper script will handle library path"
    fi
    echo ""
fi

# Verify Sharp wrapper script exists
if [ ! -f "scripts/with-sharp-libpath.sh" ]; then
    echo "📝 Creating Sharp library path wrapper script..."
    cat > scripts/with-sharp-libpath.sh << 'EOF'
#!/bin/bash
# Helper script to set LD_LIBRARY_PATH for Sharp before running commands
# This ensures Sharp can find its bundled libvips library

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
PROJECT_DIR="$(cd "$SCRIPT_DIR/.." && pwd)"
SHARP_LIB_PATH="$PROJECT_DIR/node_modules/sharp/node_modules/@img/sharp-libvips-linux-x64/lib"

if [ -d "$SHARP_LIB_PATH" ]; then
  export LD_LIBRARY_PATH="$SHARP_LIB_PATH:${LD_LIBRARY_PATH:-}"
  exec "$@"
else
  echo "Warning: Sharp libvips library not found at $SHARP_LIB_PATH"
  echo "Sharp image processing may not work correctly."
  exec "$@"
fi
EOF
    chmod +x scripts/with-sharp-libpath.sh
    echo "✅ Sharp wrapper script created"
    echo ""
fi

# Generate Prisma clients
echo "🔧 Generating Prisma clients..."
if [ -f "prisma/schema.prisma" ]; then
    npm run prisma:generate
    echo "✅ Main Prisma client generated"
else
    echo "⚠️  prisma/schema.prisma not found, skipping Prisma generation"
fi

if [ -f "prisma/schema-auth.prisma" ]; then
    npm run prisma:generate:auth
    echo "✅ Auth Prisma client generated"
fi
echo ""

# Check for .env file
if [ ! -f ".env" ]; then
    echo "⚠️  .env file not found"
    echo "   Please create a .env file with the following variables:"
    echo "   - DATABASE_URL"
    echo "   - DATABASE_URL_AUTH (optional)"
    echo "   - NEXTAUTH_SECRET"
    echo "   - NEXTAUTH_URL"
    echo ""
else
    echo "✅ .env file found"
fi
echo ""

# Test Sharp if available
echo "🧪 Testing Sharp library..."
if node -e "
const path = require('path');
const libPath = path.join(__dirname, 'node_modules/sharp/node_modules/@img/sharp-libvips-linux-x64/lib');
process.env.LD_LIBRARY_PATH = libPath + ':' + (process.env.LD_LIBRARY_PATH || '');
try {
  const sharp = require('sharp');
  console.log('✅ Sharp loaded successfully');
  console.log('   Version:', require('sharp/package.json').version);
  console.log('   libvips:', sharp.versions.vips);
} catch(e) {
  console.log('⚠️  Sharp not available:', e.message.split('\n')[0]);
  console.log('   Image watermarking will be disabled');
  console.log('   The wrapper script will handle this at runtime');
}
" 2>/dev/null; then
    echo ""
else
    echo "⚠️  Sharp test failed, but wrapper script will handle it at runtime"
    echo ""
fi

echo "================================================"
echo "✅ Dependency installation complete!"
echo ""
echo "Next steps:"
echo "1. Configure your .env file with database connection strings"
echo "2. Run 'npm run dev' to start the development server"
echo "3. Run 'npm run check:permissions' to verify database access"
echo ""




