#!/usr/bin/env bash
# Pre-commit hook: auto-format with gofmt and lint with golangci-lint.
# Installed via: git config core.hooksPath .githooks
# See also: make install (sets hooksPath automatically)

set -euo pipefail

# Only check staged Go files (Added, Copied, Modified)
staged_go_files=$(git diff --cached --name-only --diff-filter=ACM -- '*.go')
[ -z "$staged_go_files" ] && exit 0

# Use go run so golangci-lint is always built with the project's Go
# toolchain, avoiding version-mismatch panics from a stale global binary.
GOLANGCI_LINT="go run github.com/golangci/golangci-lint/v2/cmd/golangci-lint@v2.10.1"

# Auto-format and re-stage
echo "$staged_go_files" | xargs gofmt -w
echo "$staged_go_files" | xargs git add

# Lint changed code with auto-fix; block on remaining issues.
# CGO_ENABLED=0 avoids typecheck failures from CGO-only dependencies
# (e.g., dolthub/go-icu-regex) that require system headers not always present.
CGO_ENABLED=0 $GOLANGCI_LINT run --new-from-rev=HEAD --fix || exit 1

# Re-stage any auto-fixes from the linter
echo "$staged_go_files" | xargs git add
