#!/usr/bin/env bash
#
# Husky Pre-commit Hook
# Runs lint-fix and Build Architecture Guard on staged files
#
. "$(dirname -- "$0")/_/husky.sh"

echo "🔍 Running pre-commit hooks..."

# Run lint-fix first
echo "📝 Running lint-fix..."

# Capture git status before lint-fix to detect changes
git_status_before=$(git status --porcelain)

npm run lint-fix || {
    echo
    echo "❌ Linting failed. Please fix the issues and try again."
    echo "💡 To bypass this check for emergency commits, use:"
    echo "   git commit --no-verify"
    echo
    exit 1
}

# Check if lint-fix made any changes
git_status_after=$(git status --porcelain)

if [ "$git_status_before" != "$git_status_after" ]; then
    echo
    echo "⚠️  lint-fix made changes to your files!"
    echo "📋 Changes detected:"
    git diff --name-only
    echo
    echo "❓ What would you like to do?"
    echo "   [c] Continue commit without the new changes"
    echo "   [a] Abort commit (recommended - review and stage the changes)"
    echo
    printf "Choose [c/a]: "
    # The `< /dev/tty` is necessary to make read work in git's non-interactive shell
    read choice < /dev/tty
    
    case $choice in
        [Cc]* )
            echo "✅ Continuing commit without lint-fix changes..."
            sleep 3
            ;;
        [Aa]* | * )
            echo "🛑 Commit aborted. Please review the changes made by lint-fix."
            echo "💡 You can stage the changes with 'git add .' and commit again."
            exit 1
            ;;
    esac
fi

# Then run Build Architecture Guard

#echo "🏗️  Running Build Architecture Guard..."
#bash ./scripts/build-arch-guard.sh --staged || {
#    echo
#    echo "❌ Build Architecture Guard failed. Please fix the issues and try again."
#    echo "💡 To bypass this check for emergency commits, use:"
#    echo "   git commit --no-verify"
#    echo
#    exit 1
#}

echo "✅ All pre-commit checks passed!"

