#!/usr/bin/env bash
#
# cross-review — have a *different* model review work, to catch blind spots.
#
# Different model families fail differently, so a second pair of eyes from
# Gemini (or GPT-OSS) on Claude's output catches bugs the author misses.
# Runs through bin/agy-task, so it inherits the async 10-min timeout.
#
# Usage:
#   cross-review <file>...                 # review specific files
#   cross-review --diff                    # review the current git diff
#   cross-review --diff --model smart      # deeper review with Gemini Pro
#   cross-review --board <task-id> <file>  # review + record verdict on the board
#
# Options:
#   --diff            review `git diff` instead of files
#   --model <preset>  fast | smart | any agy model id  (default: smart)
#   --board <id>      append the reviewer's verdict to that board task
#   --out <file>      write the review to a file (default: stdout)
#
set -euo pipefail

HERE="$(cd "$(dirname "$0")" && pwd)"
MODEL="smart"
BOARD_ID=""
OUT=""
USE_DIFF=0
FILES=()

while [[ $# -gt 0 ]]; do
  case "$1" in
    --diff)  USE_DIFF=1; shift ;;
    --model) MODEL="$2"; shift 2 ;;
    --board) BOARD_ID="$2"; shift 2 ;;
    --out)   OUT="$2"; shift 2 ;;
    -h|--help) grep '^#' "$0" | sed 's/^# \{0,1\}//'; exit 0 ;;
    *)       FILES+=("$1"); shift ;;
  esac
done

# Assemble the material under review.
if [[ "$USE_DIFF" -eq 1 ]]; then
  MATERIAL="$(git -C "$HERE/.." diff)"
  [[ -z "$MATERIAL" ]] && { echo "cross-review: git diff is empty" >&2; exit 1; }
  SUBJECT="the following git diff"
  CONTENT="$MATERIAL"
elif [[ ${#FILES[@]} -gt 0 ]]; then
  SUBJECT="the following file(s): ${FILES[*]}"
  CONTENT=""
  for f in "${FILES[@]}"; do
    CONTENT+=$'\n\n===== '"$f"$' =====\n'
    CONTENT+="$(cat "$f")"
  done
else
  echo "cross-review: pass files or --diff" >&2
  exit 2
fi

read -r -d '' PROMPT <<EOF || true
You are a senior reviewer from a different team than the author. Critically
review $SUBJECT for CORRECTNESS bugs, edge cases, security issues, and missing
error handling. Be specific and concrete: cite the exact line or construct.
Prefer a short list of real problems over generic praise. If it looks solid,
say so plainly and note the one thing you'd still double-check.

Format:
- **Verdict:** SHIP / FIX / BLOCK (one word)
- **Findings:** bullet list, most severe first (or "none")

Material under review:
$CONTENT
EOF

REVIEW="$(printf '%s' "$PROMPT" | "$HERE/agy-task" --model "$MODEL")"

if [[ -n "$OUT" ]]; then
  printf '%s\n' "$REVIEW" > "$OUT"
  echo "cross-review: written to $OUT"
else
  printf '%s\n' "$REVIEW"
fi

# Optionally record the verdict on the board.
if [[ -n "$BOARD_ID" ]]; then
  VERDICT="$(printf '%s' "$REVIEW" | grep -ioE 'SHIP|FIX|BLOCK' | head -1 || echo 'reviewed')"
  "$HERE/board" note "$BOARD_ID" "cross-review ($MODEL): $VERDICT" --by "agy:$MODEL" >/dev/null
  echo "cross-review: verdict '$VERDICT' recorded on $BOARD_ID"
fi
