#!/bin/bash
# PreToolUse hook for Read: Blocks whole-file reads on large files
MIN_LINES="${SHUNT_MIN_LINES:-350}"
case "$MIN_LINES" in ''|*[!0-9]*) MIN_LINES=350 ;; esac

input=$(cat)

file_path=$(echo "$input" | jq -r '.tool_input.file_path // empty' 2>/dev/null)
offset=$(echo "$input" | jq -r '.tool_input.offset // empty' 2>/dev/null)
limit=$(echo "$input" | jq -r '.tool_input.limit // empty' 2>/dev/null)

# 1. Allow targeted reads (offset or limit set) — needed for surgical editing
if [ -n "$offset" ] || [ -n "$limit" ]; then
  echo '{"decision": "allow"}'
  exit 0
fi

# 2. Allow if file doesn't exist or is not a regular file
if [ -z "$file_path" ] || [ ! -f "$file_path" ]; then
  echo '{"decision": "allow"}'
  exit 0
fi

# 3. Allow small files (< threshold)
lines=$(wc -l < "$file_path" 2>/dev/null | tr -d ' ' || echo "0")
if [ "$lines" -le "$MIN_LINES" ]; then
  echo '{"decision": "allow"}'
  exit 0
fi

# 4. Block large whole-file reads and suggest bulk-read
BULK_READ="$(cd "$(dirname "$0")/../scripts" && pwd)/bulk-read"
echo "{\"decision\": \"block\", \"reason\": \"File '$file_path' is ${lines} lines (threshold: ${MIN_LINES}). To save tokens and preserve agent context window, delegate to bulk-read: '$BULK_READ' --question '<your question>' --paths '$file_path'. If you need exact lines for surgical editing, specify offset/limit parameters.\"}"
