#!/bin/bash

# A Git pre-push hook to ensure that the pushed tag matches the version in pyproject.toml
# To install, run:
#   chmod +x scripts/pre-push.sh
#   ln -sf ../../scripts/pre-push.sh .git/hooks/pre-push

while read local_ref local_oid remote_ref remote_oid
do
    # Check if a tag starting with 'v' is being pushed
    if [[ "$remote_ref" == refs/tags/v* ]]; then
        # Extract the version from the tag (e.g., 'refs/tags/v1.0.0' -> '1.0.0')
        TAG_VERSION="${remote_ref#refs/tags/v}"
        
        # Extract the version from pyproject.toml
        # We assume Python 3.12 is available as per the project requirements
        if ! command -v python3 &> /dev/null; then
            echo "Error: python3 is not available. Skipping version check."
            exit 0
        fi
        
        PYPROJECT_VERSION=$(python3 -c "import tomllib, sys; print(tomllib.load(open('pyproject.toml', 'rb'))['project']['version'])" 2>/dev/null)
        
        if [ $? -ne 0 ] || [ -z "$PYPROJECT_VERSION" ]; then
            echo "Error: Could not parse version from pyproject.toml."
            exit 1
        fi
        
        if [ "$TAG_VERSION" != "$PYPROJECT_VERSION" ]; then
            echo ""
            echo "🚨 pre-push validation failed! 🚨"
            echo "You are trying to push tag 'v$TAG_VERSION', but pyproject.toml has version '$PYPROJECT_VERSION'."
            echo "Please fix the version in pyproject.toml, commit the change, and update the tag before pushing."
            echo ""
            exit 1
        fi
        
        echo "✅ Pre-push validation passed: Tag 'v$TAG_VERSION' matches pyproject.toml version."
    fi
done

exit 0