#!/usr/bin/env sh
#
# LocalAI pre-commit hook. Install it (once per clone) with:
#
#     make install-hooks
#
# Runs only the checks relevant to what's staged:
#   - Go files          -> make lint + make test-coverage-check
#   - core/http/react-ui -> make test-ui-coverage-check (Playwright e2e + gate)
# A commit touching neither is skipped entirely (docs/YAML/etc. can't change
# lint findings, Go coverage, or the UI).
#
# To bypass for a single commit (e.g. a WIP checkpoint): git commit --no-verify
set -eu

repo_root="$(git rev-parse --show-toplevel)"
cd "$repo_root"

staged="$(git diff --cached --name-only --diff-filter=ACMRD)"

go_changed=0
ui_changed=0
if echo "$staged" | grep -qE '\.go$'; then go_changed=1; fi
if echo "$staged" | grep -qE '^core/http/react-ui/'; then ui_changed=1; fi

if [ "$go_changed" -eq 0 ] && [ "$ui_changed" -eq 0 ]; then
	echo "pre-commit: no Go or React UI changes staged — skipping."
	exit 0
fi

if [ "$go_changed" -eq 1 ]; then
	# Resolve the ref golangci-lint's new-from-merge-base should compare
	# against. .golangci.yml pins origin/master, which is correct in CI
	# (origin == the canonical repo) but wrong from a fork clone, where
	# origin/master lags behind and lint would report the whole upstream
	# backlog. Prefer upstream/master, then origin/master, then master.
	lint_base=""
	for ref in upstream/master origin/master master; do
		if git rev-parse --verify --quiet "${ref}^{commit}" >/dev/null 2>&1; then
			lint_base="$ref"
			break
		fi
	done

	echo "pre-commit ▶ golangci-lint (make lint${lint_base:+, new-from $lint_base})"
	make lint LINT_NEW_FROM="$lint_base"

	echo "pre-commit ▶ coverage gate (make test-coverage-check) — builds and runs the"
	echo "             pkg/core suites plus tests/e2e; can take a few minutes."
	make test-coverage-check
fi

if [ "$ui_changed" -eq 1 ]; then
	echo "pre-commit ▶ React UI e2e + coverage gate (make test-ui-coverage-check) —"
	echo "             rebuilds the UI + ui-test-server, runs the Playwright specs, and"
	echo "             fails if line coverage regressed; can take a couple of minutes."
	make test-ui-coverage-check
fi

echo "pre-commit ✓ all relevant checks passed"
