#!/usr/bin/env bash
# pre-push hook — blocks pushes when no task is in an edit-allowed phase.
#
# Install: cp this file to .git/hooks/pre-push && chmod +x .git/hooks/pre-push
# Or:      ln -sf ~/.automaton/scripts/git-hooks/pre-push .git/hooks/pre-push
#
# This catches commits that bypassed the pre-commit hook via --no-verify.
# Combined with disabling force-pushes on the remote, this makes it much
# harder to bypass automaton enforcement.

set -euo pipefail

STATUS_SCRIPT="$HOME/.automaton/scripts/status.py"

if [ ! -f "$STATUS_SCRIPT" ]; then
    exit 0
fi

PROJECT_ROOT="$(git rev-parse --show-toplevel 2>/dev/null || pwd)"

# Check if any commits in the push range were made without an active task.
# We use --can-edit to check if a task is currently active.
# If no task is in implement/doc_review, block the push.
python3 "$STATUS_SCRIPT" --can-edit --project "$PROJECT_ROOT" --json 2>/dev/null
EXIT_CODE=$?

if [ $EXIT_CODE -ne 0 ]; then
    echo ""
    echo "=== PUSH BLOCKED ==="
    echo "No task is in an implement or doc_review phase."
    echo "This prevents pushing commits that may have bypassed the pre-commit hook."
    echo ""
    echo "Create a task and transition it to implement before pushing:"
    echo ""
    echo "  python ~/.automaton/scripts/status.py --create-task my-feature --project $PROJECT_ROOT"
    echo "  python ~/.automaton/scripts/status.py --transition research --task my-feature --project $PROJECT_ROOT"
    echo "  python ~/.automaton/scripts/status.py --transition implement --task my-feature --project $PROJECT_ROOT"
    echo ""
    echo "To bypass this hook (NOT RECOMMENDED): git push --no-verify"
    echo "====================="
    exit 1
fi

exit 0
