#!/usr/bin/env bash
# Pre-commit quality gate: fmt-check, clippy, duplication, cargo check, and
# doc-coverage. Run this before committing to catch fmt drift, clippy
# warnings, duplicate code, compile errors, and missing doc comments without
# waiting for the full test suite.
set -euo pipefail

SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
PROJECT_ROOT="$(cd "$SCRIPT_DIR/.." && pwd)"

echo "=== Checking Rust formatting ==="
cargo fmt --manifest-path "$PROJECT_ROOT/Cargo.toml" --all --check

echo "=== Running cargo clippy ==="
# clippy::cognitive_complexity is allow-by-default; -W activates it so that
# -D warnings turns violations into a hard failure. The threshold it's
# measured against lives in clippy.toml (committed, not passed ad hoc).
cargo clippy --manifest-path "$PROJECT_ROOT/Cargo.toml" --workspace --all-targets -- -W clippy::cognitive_complexity -D warnings

echo "=== Checking code duplication (jscpd) ==="
if ! command -v jscpd &>/dev/null; then
  echo "FAIL: jscpd is not installed. Install it with 'npm install -g jscpd' before running script/check." >&2
  exit 1
fi
# Duplication threshold lives in .jscpd.json (committed, not passed ad hoc).
# jscpd exits non-zero automatically when duplication exceeds that threshold.
jscpd --config "$PROJECT_ROOT/.jscpd.json" \
  "$PROJECT_ROOT/server/src" "$PROJECT_ROOT/frontend/src" "$PROJECT_ROOT/crates"

echo "=== Checking doc coverage on changed files ==="
cargo run --manifest-path "$PROJECT_ROOT/Cargo.toml" -p source-map-gen --bin source-map-check --quiet -- --worktree "$PROJECT_ROOT" --base master
