#!/usr/bin/env bash
# verify-affected.sh — Universal verify gate for agents
# Agents MUST paste the output of this script before declaring done.
# Grep for "VERIFY GATE: PASS" or "VERIFY GATE: FAIL" in output.
set -euo pipefail

# Detect changed files: use args if provided, otherwise git diff
if [ $# -gt 0 ]; then
  CHANGED_FILES=("$@")
else
  mapfile -t CHANGED_FILES < <(git diff --name-only HEAD 2>/dev/null || true)
  if [ ${#CHANGED_FILES[@]} -eq 0 ]; then
    mapfile -t CHANGED_FILES < <(git diff --cached --name-only 2>/dev/null || true)
  fi
fi

if [ ${#CHANGED_FILES[@]} -eq 0 ]; then
  echo "No changed files detected."
  echo "VERIFY GATE: PASS"
  exit 0
fi

echo "Changed files:"
printf '  %s\n' "${CHANGED_FILES[@]}"
echo ""

FAILED=0

# Check if any Python files changed
HAS_PYTHON=false
HAS_RUST=false
for f in "${CHANGED_FILES[@]}"; do
  case "$f" in
    *.py) HAS_PYTHON=true ;;
    *.rs|Cargo.toml) HAS_RUST=true ;;
  esac
done

# --- Test command ---
run_tests() {
  echo "=== Tests ==="
  if $HAS_PYTHON; then
    if command -v pytest &>/dev/null; then
      echo "Running: pytest tests/ eab/tests/ -x --tb=short -q"
      pytest tests/ eab/tests/ -x --tb=short -q 2>&1 || return 1
    else
      echo "SKIP: pytest not installed. Run: pip install -e '.[dev]'"
    fi
  else
    echo "SKIP: No Python files changed."
  fi
}

# --- Lint command ---
run_lint() {
  echo "=== Lint ==="
  if $HAS_PYTHON; then
    if command -v ruff &>/dev/null; then
      echo "Running: ruff check eab/ tests/"
      ruff check eab/ tests/ 2>&1 || return 1
    else
      echo "SKIP: ruff not installed. Run: pip install ruff"
    fi
  else
    echo "SKIP: No Python files changed."
  fi
}

# --- Build command ---
run_build() {
  echo "=== Build ==="
  if $HAS_RUST; then
    if command -v cargo &>/dev/null; then
      echo "Running: cargo clippy in eab-probe-rs/"
      (cd eab-probe-rs && cargo clippy --all-targets 2>&1) || return 1
    else
      echo "SKIP: cargo not installed."
    fi
  fi
  if $HAS_PYTHON; then
    echo "Running: python -m py_compile on changed .py files"
    for f in "${CHANGED_FILES[@]}"; do
      if [[ "$f" == *.py ]] && [ -f "$f" ]; then
        python3 -m py_compile "$f" 2>&1 || return 1
      fi
    done
    echo "All Python files compile OK."
  fi
  if ! $HAS_RUST && ! $HAS_PYTHON; then
    echo "SKIP: No Python or Rust files changed."
  fi
}

# Run all gates
run_tests
if [ $? -ne 0 ]; then FAILED=1; fi

run_lint
if [ $? -ne 0 ]; then FAILED=1; fi

run_build
if [ $? -ne 0 ]; then FAILED=1; fi

echo ""
if [ "$FAILED" -ne 0 ]; then
  echo "VERIFY GATE: FAIL"
  exit 1
else
  echo "VERIFY GATE: PASS"
  exit 0
fi
