#!/usr/bin/env bash
# pre-commit hook — blocks commits when no task is in an edit-allowed phase.
# Also warns about stale/hollow tasks when autopilot is enabled.
#
# Install: cp this file to .git/hooks/pre-commit && chmod +x .git/hooks/pre-commit
# Or:      ln -s ~/.automaton/scripts/git-hooks/pre-commit .git/hooks/pre-commit
#
# This is a safety net. The primary enforcement is the harness pre-edit hook.
# Pre-commit catches changes that bypassed the harness (e.g., manual edits).

set -euo pipefail

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

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

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

python3 "$STATUS_SCRIPT" --can-edit --project "$PROJECT_ROOT" --json 2>/dev/null
EXIT_CODE=$?

if [ $EXIT_CODE -ne 0 ]; then
    echo ""
    echo "=== COMMIT BLOCKED ==="
    echo "No task is in an implement or doc_review phase."
    echo "Create a task and transition it to implement before committing:"
    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 "====================="
    exit 1
fi

# --- Autopilot awareness: warn about hanging/hollow tasks ---

AGENT_FILE=""
if [ -f "$PROJECT_ROOT/.automaton/.agent.md" ]; then
    AGENT_FILE="$PROJECT_ROOT/.automaton/.agent.md"
elif [ -f "$AUTOMATON_DIR/.agent.md" ]; then
    AGENT_FILE="$AUTOMATON_DIR/.agent.md"
fi

if [ -n "$AGENT_FILE" ] && grep -qi "Autopilot:\s*Enabled" "$AGENT_FILE" 2>/dev/null; then
    AUTOPILOT_ENABLED=true
else
    AUTOPILOT_ENABLED=false
fi

if $AUTOPILOT_ENABLED; then
    NON_TERMINAL=$(python3 "$STATUS_SCRIPT" --list --project "$PROJECT_ROOT" 2>/dev/null \
        | grep -v "complete" | grep -v "UNTRACKED" | grep -v "Phase" | grep -v "^--" \
        | grep -v "^$" | grep -v "^$" || true)

    if [ -n "$NON_TERMINAL" ]; then
        echo ""
        echo "=== AUTOPILOT WARNING ==="
        echo "Autopilot is enabled but non-terminal tasks exist:"
        echo ""
        echo "$NON_TERMINAL"
        echo ""
        echo "These tasks should be driven to completion. Run the orchestrator:"
        echo "  (agent should say 'orchestrate' or 'continue')"
        echo "========================="
    fi
fi

exit 0
