#!/bin/bash
#
# PostToolUse Hook: Verify edits exist and have substantive content.
#
# Receives JSON via stdin with tool_input.file_path
# Exits 0 on success, non-zero on failure
#

set -e

# Get Grid directory
GRID_DIR="${CLAUDE_PROJECT_DIR:-.}/.grid"
SCRATCHPAD="$GRID_DIR/SCRATCHPAD.md"

# Helper: Log to scratchpad
log_scratchpad() {
    local timestamp=$(date +"%H:%M:%S")
    echo "" >> "$SCRATCHPAD" 2>/dev/null || true
    echo "[$timestamp] VERIFY: $1" >> "$SCRATCHPAD" 2>/dev/null || true
}

# Read JSON from stdin
INPUT=$(cat)

# Extract tool name and file path using grep/sed (portable)
TOOL_NAME=$(echo "$INPUT" | grep -o '"tool_name"[[:space:]]*:[[:space:]]*"[^"]*"' | head -1 | sed 's/.*"tool_name"[[:space:]]*:[[:space:]]*"\([^"]*\)".*/\1/')
FILE_PATH=$(echo "$INPUT" | grep -o '"file_path"[[:space:]]*:[[:space:]]*"[^"]*"' | head -1 | sed 's/.*"file_path"[[:space:]]*:[[:space:]]*"\([^"]*\)".*/\1/')

# Only verify Edit and Write operations
if [[ "$TOOL_NAME" != "Edit" && "$TOOL_NAME" != "Write" ]]; then
    exit 0
fi

# If no file path, skip
if [[ -z "$FILE_PATH" ]]; then
    exit 0
fi

# Expand ~ to home directory
FILE_PATH="${FILE_PATH/#\~/$HOME}"

# Check 1: File exists
if [[ ! -f "$FILE_PATH" ]]; then
    log_scratchpad "FAIL - File does not exist: $FILE_PATH"
    echo "Verification failed: File does not exist: $FILE_PATH" >&2
    exit 1
fi

# Check 2: File has substantive content (>5 lines)
LINE_COUNT=$(wc -l < "$FILE_PATH" | tr -d ' ')
if [[ "$LINE_COUNT" -lt 5 ]]; then
    log_scratchpad "WARN - File is a stub (<5 lines): $FILE_PATH ($LINE_COUNT lines)"
    echo "Warning: File may be a stub (only $LINE_COUNT lines): $FILE_PATH" >&2
    # Don't fail, just warn
fi

# Check 3: File is not empty
if [[ ! -s "$FILE_PATH" ]]; then
    log_scratchpad "FAIL - File is empty: $FILE_PATH"
    echo "Verification failed: File is empty: $FILE_PATH" >&2
    exit 1
fi

# Get file size for logging
FILE_SIZE=$(wc -c < "$FILE_PATH" | tr -d ' ')

log_scratchpad "OK - $TOOL_NAME verified: $FILE_PATH ($LINE_COUNT lines, $FILE_SIZE bytes)"

exit 0
