#!/bin/sh
[ -f "$(dirname "$0")/_/husky.sh" ] && . "$(dirname "$0")/_/husky.sh"

# Borrow node_modules/venv from the main clone in a light worktree, when
# lockfiles match -- lets this hook run with zero local installs. Resolve the
# helper relative to this hook file, not cwd: core.hooksPath may be absolute
# (hook file lives in the main clone) or relative (worktree's own checkout),
# and cwd is always the active worktree, which may not contain the helper.
HOOK_DIR="$(cd "$(dirname "$0")" && pwd)"
if [ -f "$HOOK_DIR/../bin/helpers/worktree-borrow.sh" ]; then
    . "$HOOK_DIR/../bin/helpers/worktree-borrow.sh"
    posthog_worktree_borrow
fi

# Skip lint-staged during merges — staged files include the entire merge diff,
# not just your changes, making it slow and pointless
[ -f "$(git rev-parse --git-path MERGE_HEAD 2>/dev/null)" ] && exit 0

# Auto-invoked formatter/linter calls during commit are not explicit user
# commands -- skip telemetry so the dashboard reflects intentional usage only.
export POSTHOG_TELEMETRY_OPT_OUT=1

# Fixture-provenance warning. Runs here rather than as a lint-staged task because
# lint-staged prints nothing for a task that succeeds, and this one always does.
# Never blocks: the question it raises is not one a script can answer.
if [ -x .github/scripts/check-fixture-provenance.sh ]; then
    .github/scripts/check-fixture-provenance.sh || true
fi

# Activate Flox environment if available and not already active
# This ensures lint-staged commands work in GUI Git clients (GitHub Desktop, etc.)
if command -v flox > /dev/null 2>&1 && [ -d ".flox/cache" ] && [ -z "$FLOX_ENV" ]; then
    # CI=true so pnpm in flox's on-activate hook doesn't ask for a TTY when
    # cleaning stale node_modules. Pre-commit has no TTY, same as real CI.
    exec env CI=true "$(command -v flox)" activate -- bash -c "POSTHOG_TELEMETRY_OPT_OUT=1 NODE_OPTIONS='--max-old-space-size=8192' pnpm lint-staged"
else
    # Fallback: run without Flox (for non-Flox users or if already activated)
    NODE_OPTIONS='--max-old-space-size=8192' pnpm lint-staged
fi
