#!/bin/bash
# Pre-push hook to prevent direct pushes to master branch
# This hook enforces the PR workflow

# Colors for output
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
NC='\033[0m' # No Color

# Get the remote and URL
remote="$1"
url="$2"

# Get the current branch name
current_branch=$(git symbolic-ref HEAD 2>/dev/null | sed -e 's,.*/\(.*\),\1,')

# Protected branches
protected_branches=("master" "main")

# Check if we're pushing to a protected branch
for branch in "${protected_branches[@]}"; do
    if [ "$current_branch" = "$branch" ]; then
        echo -e "${RED}❌ Direct push to $branch branch is not allowed!${NC}"
        echo -e "${YELLOW}📋 Please follow the PR workflow:${NC}"
        echo "   1. Create a feature branch: git checkout -b feature/your-feature"
        echo "   2. Push your feature branch: git push origin feature/your-feature"
        echo "   3. Create a Pull Request on GitHub"
        echo "   4. Have your PR reviewed and approved"
        echo "   5. Merge via GitHub PR interface"
        echo ""
        echo -e "${GREEN}💡 Tip: You can push your current changes to a new branch:${NC}"
        echo "   git checkout -b feature/your-feature"
        echo "   git push origin feature/your-feature"
        exit 1
    fi
done

# Read stdin for push info
while read local_ref local_sha remote_ref remote_sha
do
    # Check if pushing to master/main remotely
    if [[ "$remote_ref" =~ ^refs/heads/(master|main)$ ]]; then
        echo -e "${RED}❌ Direct push to remote ${remote_ref#refs/heads/} branch is not allowed!${NC}"
        echo -e "${YELLOW}Please create a feature branch and submit a PR.${NC}"
        exit 1
    fi
done

exit 0