#!/usr/bin/env bash
#
# tidalDB pre-commit hook (tracked). Activate per-clone with:
#     git config core.hooksPath hooks
# or run scripts/install-hooks.sh once.
#
# Gates: Rust fmt/clippy/test (only when Rust is staged), the documentation
# consolidation guard (always), and site eslint (when node_modules exist).

set -uo pipefail
ROOT="$(git rev-parse --show-toplevel)"
cd "$ROOT" || exit 2

staged() { git diff --cached --name-only --diff-filter=ACM; }
rust_staged=$(staged | grep -E '\.rs$' || true)
site_staged=$(staged | grep -E '^site/.*\.(ts|tsx|js|jsx|mjs)$' || true)

# --- Rust (engine crate) ----------------------------------------------------
if [ -n "$rust_staged" ]; then
  echo "pre-commit: cargo fmt"
  cargo fmt -p tidaldb || { echo "cargo fmt failed" >&2; exit 1; }
  # re-stage any files fmt rewrote
  echo "$rust_staged" | while IFS= read -r f; do [ -f "$f" ] && git add "$f"; done
  echo "pre-commit: cargo clippy -p tidaldb -D warnings"
  cargo clippy -p tidaldb --all-targets -- -D warnings || exit 1
  echo "pre-commit: cargo test -p tidaldb --lib"
  cargo test -p tidaldb --lib || exit 1
fi

# --- Documentation consolidation guard (always) -----------------------------
bash scripts/check-docs.sh || exit 1

# --- Marketing site ---------------------------------------------------------
if [ -n "$site_staged" ] && [ -d site/node_modules ]; then
  echo "pre-commit: eslint (site)"
  ( cd site && npx --no-install eslint . ) || exit 1
fi

exit 0
