#!/usr/bin/env bash
# browser-preflight.sh — Generic pre_tool_call hook for agent harnesses.
#
# Intercepts two browser automation failure patterns before they reach the model:
#   1. browser_click with @e element refs (ephemeral refs expire during proxy latency)
#   2. browser_scroll loops (repeated scrolls with no progress)
#
# Protocol: reads JSON from stdin, writes JSON to stdout.
#   Pass-through: exit 0, no stdout
#   Block:        stdout → {"action": "block", "message": "..."}
#
# Compatible with any harness that supports a pre_tool_call hook (opencode,
# Claude Code, custom agent runners, etc.).

set -euo pipefail

input=$(cat)
tool_name=$(echo "$input" | python3 -c "import sys,json; d=json.load(sys.stdin); print(d.get('tool_name',''))" 2>/dev/null || echo "")

# ── 1. Block @e element refs in browser_click ─────────────────────────────────
if [[ "$tool_name" == "browser_click" ]]; then
  element=$(echo "$input" | python3 -c "
import sys, json
d = json.load(sys.stdin)
inp = d.get('tool_input', d.get('args', {}))
print(inp.get('element', inp.get('ref', inp.get('selector', ''))))
" 2>/dev/null || echo "")

  if [[ "$element" =~ ^@[a-z][0-9]*$ ]]; then
    python3 -c "
import json
msg = (
    'BLOCKED: @e element refs expire during processing (proxy adds ~6s latency). '
    'Use browser_evaluate with JavaScript to click by text instead:\n'
    '  Array.from(document.querySelectorAll(\"button\")).find(b => b.textContent.includes(\"Agree\"))?.click()\n'
    'Or: document.querySelector(\"button\").click()\n'
    'Do NOT retry with any @e ref. Call browser_evaluate with the JavaScript above.'
)
print(json.dumps({'action': 'block', 'message': msg}))
"
    exit 0
  fi
fi

# ── 2. Block browser_scroll loops ────────────────────────────────────────────
SCROLL_COUNTER="/tmp/llm_browser_scroll_count"

if [[ "$tool_name" == "browser_scroll" ]]; then
  count=0
  [[ -f "$SCROLL_COUNTER" ]] && count=$(cat "$SCROLL_COUNTER" 2>/dev/null || echo 0)
  count=$((count + 1))
  echo "$count" > "$SCROLL_COUNTER"

  if [[ $count -ge 5 ]]; then
    echo "0" > "$SCROLL_COUNTER"
    python3 -c "
import json
msg = (
    'BLOCKED: browser_scroll called 5+ times in a row — this is a scroll loop. '
    'Scrolling is not helping. Try a different approach:\n'
    '1. Use browser_evaluate with JavaScript to click the button:\n'
    '   Array.from(document.querySelectorAll(\"button\")).find(b => b.textContent.includes(\"Agree\"))?.click()\n'
    '2. Or use browser_evaluate to find all buttons:\n'
    '   JSON.stringify(Array.from(document.querySelectorAll(\"button\")).map(b => b.textContent.trim()))\n'
    '3. Do NOT continue scrolling.'
)
print(json.dumps({'action': 'block', 'message': msg}))
"
    exit 0
  fi
fi

# ── 3. Reset scroll counter on non-scroll tool calls ─────────────────────────
if [[ "$tool_name" != "browser_scroll" ]]; then
  echo "0" > "$SCROLL_COUNTER" 2>/dev/null || true
fi

exit 0
