#!/bin/bash
set -e

echo "Starting enhanced build process..."

# Detect project type and build accordingly
if [ -f "package.json" ]; then
    echo "Detected Node.js project"
    
    # Install dependencies
    echo "Installing npm dependencies..."
    npm install
    
    # Run tests if available
    if grep -q "test" package.json; then
        echo "Running tests..."
        npm test || echo "Tests failed but continuing..."
    fi
    
    # Build if build script exists
    if grep -q "build" package.json; then
        echo "Running build..."
        npm run build
    fi
    
elif [ -f "requirements.txt" ]; then
    echo "Detected Python project"
    
    # Install dependencies
    echo "Installing Python dependencies..."
    pip install -r requirements.txt
    
    # Run tests if available
    if [ -f "pytest.ini" ] || [ -f "setup.py" ]; then
        echo "Running tests..."
        python -m pytest || echo "Tests failed but continuing..."
    fi
    
elif [ -f "pom.xml" ]; then
    echo "Detected Java Maven project"
    
    # Build with Maven
    echo "Building with Maven..."
    mvn clean install
    
elif [ -f "go.mod" ]; then
    echo "Detected Go project"
    
    # Download dependencies
    echo "Downloading Go dependencies..."
    go mod download
    
    # Build
    echo "Building Go project..."
    go build -o main .
    
elif [ -f "Dockerfile" ]; then
    echo "Detected Docker project"
    
    # Build Docker image
    echo "Building Docker image..."
    docker build -t ${PWD##*/} .
    
else
    echo "Unknown project type, attempting generic build..."
    
    # Try common build commands
    if [ -f "Makefile" ]; then
        make
    elif [ -f "CMakeLists.txt" ]; then
        mkdir -p build && cd build && cmake .. && make
    fi
fi

echo "Build completed successfully!"
