#!/usr/bin/env bash
# post-commit hook — reminds agent to drive tasks when autopilot is enabled.
#
# Install: cp this file to .git/hooks/post-commit && chmod +x .git/hooks/post-commit
# Or:      ln -s ~/.automaton/scripts/git-hooks/post-commit .git/hooks/post-commit

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)"

# Check if autopilot is enabled
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 [ -z "$AGENT_FILE" ] || ! grep -qi "Autopilot:\s*Enabled" "$AGENT_FILE" 2>/dev/null; then
    exit 0
fi

# Autopilot is enabled — check for non-terminal tasks
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 "^Task" || true)

if [ -z "$NON_TERMINAL" ]; then
    exit 0
fi

COUNT=$(echo "$NON_TERMINAL" | wc -l)

echo ""
echo "=== AUTOPILOT: Tasks Awaiting Completion ==="
echo "$COUNT non-terminal task(s) found:"
echo ""
echo "$NON_TERMINAL"
echo ""
echo "Drive them to completion by saying 'orchestrate' or 'continue'."
echo "=============================================="
