#!/usr/bin/env bash
# SWE-agent ACI command: search_file <query> [file]
#
# Routes the classic SWE-agent "search a file for a string" slot to
# `prism grep <query>` (literal-first, a superset of grep per spec §9). The
# bundle is the agent's FRONT DOOR for search, so on any prism failure we FAIL
# OPEN to the real grep (spec §10 Step 4) — the agent never loses search.
#
# File scoping: `prism grep` has no file positional, so we `cd` into the file's
# directory before invoking it (narrows the working-tree scope). The real-grep
# fallback greps the file path directly.
#
# No `set -e`: a non-zero prism must fall through to the real tool, not abort.
set -u

query=${1:-}
target=${2:-.}

if [ -d "$target" ]; then
  scope_dir=$target
else
  scope_dir=$(dirname -- "$target")
fi

# Prefer prism when reachable AND it succeeds; otherwise fall back to grep.
if command -v prism >/dev/null 2>&1; then
  if (cd "$scope_dir" 2>/dev/null && prism grep "$query"); then
    exit 0
  fi
fi

# Fail-open: grep the file (or, for a dir, recurse) mirroring classic ACI.
if [ -d "$target" ]; then
  exec grep -rn -- "$query" "$target"
fi
exec grep -n -- "$query" "$target"
