#!/usr/bin/env bash
# pre-commit-review — optional legacy nv review on staged changes
# Called by git pre-commit hook. NEVER blocks commits (always exits 0).

set -euo pipefail

# NVIDIA/nv is legacy/explicit-only for SaneApps. Normal Codex work uses
# Codex/GPT agents instead. Keep this hook inert unless explicitly requested.
if [ "${SANE_ENABLE_NV_REVIEW:-0}" != "1" ]; then
  exit 0
fi

# Skip if requested
if [ "${NV_SKIP_REVIEW:-0}" = "1" ]; then
  exit 0
fi

NV="/Users/sj/.local/bin/nv"

# Ensure nv exists
if [ ! -x "$NV" ]; then
  warn "pre-commit-review: nv not found at $NV, skipping review"
  exit 0
fi

# Get staged diff (only added/copied/modified/renamed files)
DIFF=$(git diff --cached --diff-filter=ACMR 2>/dev/null || true)

# Skip if diff is empty
if [ -z "$DIFF" ]; then
  exit 0
fi

# Skip if diff is huge (>50KB)
DIFF_SIZE=$(printf '%s' "$DIFF" | wc -c | tr -d ' ')
if [ "$DIFF_SIZE" -gt 51200 ]; then
  echo >&2 "[pre-commit-review] Diff is ${DIFF_SIZE} bytes (>50KB), skipping review."
  exit 0
fi

# Run the review
PROMPT="Review this git diff for bugs, race conditions, security issues, and logic errors. Be concise — only report real problems, not style nits. If no bugs found, say 'LGTM'."

echo >&2 "[pre-commit-review] Reviewing staged changes..."
REVIEW=$(printf '%s' "$DIFF" | "$NV" -m kimi-fast "$PROMPT" 2>&1) || true

# Print review output to stderr so the user sees it
if [ -n "$REVIEW" ]; then
  echo >&2 ""
  echo >&2 "--- Code Review ---"
  echo >&2 "$REVIEW"
  echo >&2 "-------------------"
  echo >&2 ""
fi

# Always allow the commit
exit 0
