#!/bin/bash
# Grid Program Stop Hook
# Called when a Grid Program (subagent) completes via SubagentStop event
#
# This hook:
# - Logs completion to scratchpad
# - Decrements active_programs counter in STATE.md
# - Records cost estimate to budget.json
# - Logs to spawn history for audit trail
# - Signals auto-verify for Executor completions
#
# Exit codes:
#   0 = Success (always returns 0 to not block completion)

INPUT=$(cat)
PROGRAM_NAME=$(echo "$INPUT" | jq -r '.subagent_name // "unknown"')
EXIT_STATUS=$(echo "$INPUT" | jq -r '.exit_status // "unknown"')
TIMESTAMP=$(date -u +"%Y-%m-%dT%H:%M:%SZ")

# Log to scratchpad
SCRATCHPAD=".grid/SCRATCHPAD.md"
if [[ -f "$SCRATCHPAD" ]]; then
    echo "" >> "$SCRATCHPAD"
    echo "## Program Completed: $PROGRAM_NAME" >> "$SCRATCHPAD"
    echo "Status: $EXIT_STATUS" >> "$SCRATCHPAD"
    echo "Time: $TIMESTAMP" >> "$SCRATCHPAD"
fi

# Update active programs count
STATE_FILE=".grid/STATE.md"
if [[ -f "$STATE_FILE" ]]; then
    current=$(grep -m1 "^active_programs:" "$STATE_FILE" | cut -d: -f2 | xargs)
    current=${current:-1}
    new=$((current - 1))
    [[ $new -lt 0 ]] && new=0
    sed -i '' "s/^active_programs:.*/active_programs: $new/" "$STATE_FILE" 2>/dev/null
fi

# Remove from active programs tracking
ACTIVE_FILE=".grid/active-programs.json"
if [[ -f "$ACTIVE_FILE" ]]; then
    jq --arg name "$PROGRAM_NAME" \
        '.programs = [.programs[] | select(.name != $name)]' \
        "$ACTIVE_FILE" > "$ACTIVE_FILE.tmp" && mv "$ACTIVE_FILE.tmp" "$ACTIVE_FILE"
fi

# Log to spawn history for audit trail
HISTORY_FILE=".grid/spawn-history.jsonl"
if [[ -d ".grid" ]]; then
    echo "{\"program\": \"$PROGRAM_NAME\", \"status\": \"$EXIT_STATUS\", \"completed\": \"$TIMESTAMP\"}" >> "$HISTORY_FILE"
fi

# Record cost estimate
BUDGET_FILE=".grid/budget.json"
if [[ -f "$BUDGET_FILE" ]]; then
    # Estimate cost based on program type
    case "$PROGRAM_NAME" in
        *planner*|*executor*) cost=0.15 ;;
        *recognizer*|*visual*) cost=0.05 ;;
        *scout*|*researcher*) cost=0.03 ;;
        *debugger*) cost=0.10 ;;
        *) cost=0.05 ;;
    esac

    # Update total spent
    current_spent=$(jq -r '.total_spent // 0' "$BUDGET_FILE")
    new_spent=$(echo "$current_spent + $cost" | bc)

    jq ".total_spent = $new_spent" "$BUDGET_FILE" > "$BUDGET_FILE.tmp" && mv "$BUDGET_FILE.tmp" "$BUDGET_FILE"
fi

# Auto-trigger Recognizer on Executor completion (if auto_verify enabled)
if [[ "$PROGRAM_NAME" == *executor* ]] && [[ "$EXIT_STATUS" == "success" ]]; then
    CONFIG_FILE=".grid/config.json"
    auto_verify=$(jq -r '.auto_verify // true' "$CONFIG_FILE" 2>/dev/null)

    if [[ "$auto_verify" == "true" ]]; then
        echo "AUTO_VERIFY: Executor completed successfully. Recognizer should verify."
        # Note: Actual Recognizer spawn happens in MC, this just signals
    fi
fi

exit 0
