#!/bin/bash
set -euo pipefail

cd "$(dirname "$0")/.."

if command -v run-clang-tidy-22 >/dev/null 2>&1; then
  RUN_CLANG_TIDY=run-clang-tidy-22
elif [ -x /usr/lib/llvm-22/bin/run-clang-tidy ]; then
  RUN_CLANG_TIDY=/usr/lib/llvm-22/bin/run-clang-tidy
elif command -v run-clang-tidy >/dev/null 2>&1; then
  RUN_CLANG_TIDY=run-clang-tidy
else
  echo "Error: run-clang-tidy not found"
  exit 127
fi

[ -f cpp/build/compile_commands.json ] || { echo "Error: cpp/build/compile_commands.json not found, run tools/compile first"; exit 1; }

LOG_FILE="$(mktemp)"
trap 'rm -f "$LOG_FILE"' EXIT

"$RUN_CLANG_TIDY" -j 6 -header-filter='^.*/cpp/src/.*' -quiet -p cpp/build $(find cpp/src cpp/prog -type f -name "*.cpp" | sort) 2>&1 | tee "$LOG_FILE"

if grep -Eq '^[^:]+:[0-9]+:[0-9]+: (warning|error):' "$LOG_FILE"; then
  echo "Error: clang-tidy reported diagnostics"
  exit 1
fi
