#!/usr/bin/env bash
# Pre-commit: fast checks only — lint, format, secrets on staged files.
# Heavier validation (make build drift, full test suite) is in pre-push.
# Install: make setup (uses core.hooksPath, no copy needed)
set -euo pipefail

echo "=== Pre-commit (fast) ==="

# Fast linters: ruff is sub-second, shellcheck/shfmt only run on staged files
make lint || {
	echo "FAIL: make lint — run 'make fmt' to auto-fix"
	exit 1
}

# Validate plugin frontmatter (fast, ~1s) — catches broken manifests early
make validate-config || {
	echo "FAIL: make validate-config"
	exit 1
}

# If anything under src/ is staged, rebuild dist/ so generated artifacts stay
# in sync with their canonical sources. Re-stage updated dist/ files so the
# commit includes the regenerated outputs.
if git diff --cached --name-only --diff-filter=ACMR | grep -qE '^src/'; then
	echo "src/ changed — running 'make build' to refresh dist/"
	make build || {
		echo "FAIL: make build"
		exit 1
	}
	regen_paths=(dist/ .claude-plugin/marketplace.json .agents/plugins/marketplace.json gemini-extension.json)
	if ! git diff --quiet -- "${regen_paths[@]}"; then
		git add -- "${regen_paths[@]}"
		echo "re-staged regenerated dist/ and root manifests"
	fi
fi

# Secret scan on staged changes only
if command -v gitleaks &>/dev/null; then
	gitleaks git --pre-commit --staged --verbose >/dev/null || {
		echo "FAIL: gitleaks (re-run with --verbose for detail)"
		exit 1
	}
else
	echo "(gitleaks not installed — skipping)"
fi

echo "=== Pre-commit passed (heavier checks run on push) ==="
