#!/bin/bash

echo "🔧 Setting up local dev environment..."

# Exit immediately on error
set -e

# Ensure script is run from project root
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
PROJECT_ROOT="$SCRIPT_DIR/../.."

CONFIG_PATH="$PROJECT_ROOT/node_modules/@josiahrarebird/code-formatting/config/"
DEST_PATH="$PROJECT_ROOT/.prettierrc.json"

# 1. Install Node dependencies
if [ -f "$PROJECT_ROOT/package.json" ]; then
    echo "📦 Installing Node dependencies..."
    cd "$PROJECT_ROOT"
    npm install
fi

# 2. Install Prettier if not present
if ! npx prettier --version &> /dev/null; then
    echo "✨ Installing Prettier..."
    npm install --save-dev prettier
else
    echo "✅ Prettier already installed."
fi

# 3. Install Laravel Pint if not present
if ! [ -f "$PROJECT_ROOT/vendor/bin/pint" ]; then
    echo "🧼 Installing Laravel Pint..."
    composer require laravel/pint --dev
else
    echo "✅ Laravel Pint already installed."
fi

# Copy shared config files if not already present
echo "🧩 Linking shared configuration files..."

# Prettier
[ ! -f .prettierrc.json ] && echo "Copying .prettierrc.json..." && cp "$CONFIG_PATH/.prettierrc.json" .prettierrc.json

# Pint
[ ! -f pint.json ] && cp "$CONFIG_PATH/pint.json" pint.json

# EditorConfig
[ ! -f .editorconfig ] && cp "$CONFIG_PATH/.editorconfig" .editorconfig

echo "✅ Setup complete!"
