#!/bin/bash
#
# Pre-push hook to prevent manual version tag pushes
# Installed by: /plinth:git-workflow-hooks
#
# This hook prevents accidentally pushing version tags without using releaserator,
# which ensures proper changelog generation, version bumping, and release notes.
#
# To bypass this hook in emergencies, use: git push --no-verify

# ANSI color codes
RED='\033[0;31m'
YELLOW='\033[1;33m'
NC='\033[0m' # No Color

# Read stdin (contains: local_ref local_sha remote_ref remote_sha)
while read local_ref local_sha remote_ref remote_sha; do
    # Check if this is a tag push
    if [[ "$remote_ref" =~ refs/tags/ ]]; then
        tag_name="${remote_ref#refs/tags/}"

        # Check if tag looks like a version tag (v*.*.* pattern)
        if [[ "$tag_name" =~ ^v[0-9]+\.[0-9]+\.[0-9]+ ]]; then
            # Extract version number from tag (remove 'v' prefix)
            version="${tag_name#v}"

            # Check if this is a releaserator-created tag by examining the last commit
            last_commit_msg=$(git log -1 --pretty=%s 2>/dev/null)

            # Allow if last commit is "chore: bump version to X.Y.Z"
            # This indicates releaserator created the tag properly
            if [[ "$last_commit_msg" == "chore: bump version to $version" ]]; then
                # This is a releaserator-created tag, allow it
                continue
            fi

            # Block manual tag push
            echo -e "${RED}❌ Blocked: Manual version tag push detected${NC}"
            echo ""
            echo -e "Tag: ${YELLOW}$tag_name${NC}"
            echo ""
            echo "Version tags should be created using:"
            echo -e "  ${YELLOW}/plinth:releaserator${NC}"
            echo ""
            echo "Releaserator ensures:"
            echo "  • Proper version bumping based on conventional commits"
            echo "  • CHANGELOG.md generation and updates"
            echo "  • GitHub release creation with release notes"
            echo "  • Consistent release workflow"
            echo ""
            echo "If you absolutely must push this tag manually (not recommended):"
            echo -e "  ${YELLOW}git push --no-verify${NC}"
            echo ""
            exit 1
        fi
    fi
done

# Allow push
exit 0
