#!/usr/bin/env bash
# ccsight pre-commit hook.
#
# Runs cargo test, cargo clippy, and the project lint before each commit. The
# full suite finishes in roughly a second on this codebase, so it is cheap
# enough to keep in an interactive hook. If you genuinely need to bypass it for
# a WIP commit, use `git commit --no-verify` sparingly.
#
# To install: `bash scripts/install-hooks.sh` (configures `core.hooksPath`).

set -e

# Locate repo root regardless of where git invokes the hook from.
REPO_ROOT="$(git rev-parse --show-toplevel)"
cd "$REPO_ROOT"

echo "[pre-commit] cargo fmt -- --check ..."
if ! cargo fmt -- --check 2>&1; then
    echo "[pre-commit] FAILED: formatter drift. Run 'cargo fmt' and re-stage."
    exit 1
fi

echo "[pre-commit] cargo test ..."
if ! cargo test --quiet 2>&1; then
    echo "[pre-commit] FAILED: cargo test reported failures."
    exit 1
fi

echo "[pre-commit] cargo clippy -- -D warnings ..."
if ! cargo clippy --quiet -- -D warnings 2>&1; then
    echo "[pre-commit] FAILED: clippy reported warnings/errors. Fix them or commit with --no-verify."
    exit 1
fi

echo "[pre-commit] bash scripts/lint.sh ..."
if ! bash scripts/lint.sh; then
    echo "[pre-commit] FAILED: project lint blocked the commit."
    exit 1
fi

# Optional: shellcheck on tracked scripts. `--severity=warning` skips the
# stylistic infos (SC2086 word-splitting where intended, SC2012 `ls`-vs-
# `find` etc.) and keeps only likely-bug-level findings (the kind that
# bit us with sed's `\n` non-handling on macOS earlier).
if command -v shellcheck >/dev/null 2>&1; then
    echo "[pre-commit] shellcheck --severity=warning scripts/*.sh scripts/hooks/* ..."
    if ! shellcheck --severity=warning scripts/*.sh scripts/hooks/* 2>&1; then
        echo "[pre-commit] FAILED: shellcheck reported warning-level issues."
        exit 1
    fi
else
    echo "[pre-commit] shellcheck not installed — skipped. Install via 'brew install shellcheck' (macOS) or 'apt install shellcheck' (Linux) to catch real bash bugs locally."
fi

# Optional: cargo-audit (security advisories for dependencies).
if command -v cargo-audit >/dev/null 2>&1; then
    echo "[pre-commit] cargo audit ..."
    if ! cargo audit --quiet 2>&1; then
        echo "[pre-commit] FAILED: cargo-audit found vulnerable dependencies."
        exit 1
    fi
else
    echo "[pre-commit] cargo-audit not installed — skipped. Install via 'cargo install cargo-audit' to catch dependency CVEs locally (CI runs it regardless)."
fi

echo "[pre-commit] OK"
