#!/bin/bash
# Grid Program Start Hook
# Called when a Grid Program (subagent) is spawned via SubagentStart event
#
# This hook:
# - Logs program spawn to scratchpad
# - Increments active_programs counter in STATE.md
# - Checks budget before allowing spawn (blocks if exceeded)
#
# Exit codes:
#   0 = Success, allow spawn
#   2 = Block spawn (budget exceeded)

INPUT=$(cat)
PROGRAM_NAME=$(echo "$INPUT" | jq -r '.subagent_name // "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 Started: $PROGRAM_NAME" >> "$SCRATCHPAD"
    echo "Time: $TIMESTAMP" >> "$SCRATCHPAD"
fi

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

# Register in active programs tracking
ACTIVE_FILE=".grid/active-programs.json"
if [[ -f "$ACTIVE_FILE" ]]; then
    # Add this program to active list
    jq --arg name "$PROGRAM_NAME" --arg time "$TIMESTAMP" \
        '.programs += [{"name": $name, "started": $time}]' \
        "$ACTIVE_FILE" > "$ACTIVE_FILE.tmp" && mv "$ACTIVE_FILE.tmp" "$ACTIVE_FILE"
elif [[ -d ".grid" ]]; then
    # Create active programs file
    echo "{\"programs\": [{\"name\": \"$PROGRAM_NAME\", \"started\": \"$TIMESTAMP\"}]}" > "$ACTIVE_FILE"
fi

# Budget check (if budget.json exists and has limit)
BUDGET_FILE=".grid/budget.json"
if [[ -f "$BUDGET_FILE" ]]; then
    limit=$(jq -r '.limit // 0' "$BUDGET_FILE")
    spent=$(jq -r '.total_spent // 0' "$BUDGET_FILE")

    if [[ "$limit" != "0" ]] && (( $(echo "$spent >= $limit" | bc -l) )); then
        echo "BUDGET EXCEEDED: Spent \$$spent of \$$limit limit" >&2
        echo "Use /grid:budget to adjust or reset" >&2
        exit 2  # Block spawn
    fi
fi

exit 0
