#!/usr/bin/env bash
# PR security review automation — runs scanners and generates review template.
# Usage: bash scripts/review_pr.sh [--base main] [--head HEAD]
set -euo pipefail

BASE="${1:-main}"
HEAD="${2:-HEAD}"

echo "=== PR Security Review ==="
echo "Comparing: $BASE..$HEAD"
echo ""

echo "--- Changed Files ---"
CHANGED=$(git diff "$BASE..$HEAD" --name-only)
echo "$CHANGED" | head -20
TOTAL=$(echo "$CHANGED" | wc -l)
echo "Total files changed: $TOTAL"

echo ""
echo "--- Security-Relevant Changes ---"
echo "$CHANGED" | grep -iE 'auth|login|password|token|secret|crypto|permission|access|session|cookie|sql|api' || echo "  None detected by filename"

echo ""
echo "--- Secrets Scan ---"
if command -v gitleaks &>/dev/null; then
  gitleaks detect --source . --log-opts="$BASE..$HEAD" --no-banner 2>/dev/null && echo "  ✅ No secrets found" || echo "  🔴 Secrets detected!"
else
  echo "  ⚠️  gitleaks not installed"
fi

echo ""
echo "--- Dangerous Patterns ---"
git diff "$BASE..$HEAD" | grep -nE 'eval\(|exec\(|shell=True|dangerouslySetInnerHTML|pickle\.loads|yaml\.load\(' || echo "  ✅ No dangerous patterns found"

echo ""
echo "--- Hardcoded Credentials ---"
git diff "$BASE..$HEAD" | grep -niE 'password\s*=|secret\s*=|api_key\s*=|token\s*=' | grep -v 'test\|example\|placeholder\|TODO' || echo "  ✅ No hardcoded credentials"

echo ""
echo "--- New Dependencies ---"
git diff "$BASE..$HEAD" -- '**/package.json' '**/requirements*.txt' '**/go.mod' '**/Gemfile' '**/pyproject.toml' --stat 2>/dev/null || echo "  No dependency file changes"
