#!/usr/bin/env bash
# pql: source .pql/hooks/post-checkout
_pql_hook="$(git rev-parse --show-toplevel)/.pql/hooks/post-checkout"; [ -f "$_pql_hook" ] && . "$_pql_hook"
# Post-checkout hook. Folds in pql's planning logic (its .pql/hooks installer is
# dead under core.hooksPath=.config/hooks).
#
# On a branch checkout (third arg == 1), keep the local planning cache (pql.db)
# in sync with the changelog. File-level checkouts ($3 == 0) are skipped.
# Args: <prev-HEAD> <new-HEAD> <branch-flag>.
#
# Only a real branch *switch* (prev-HEAD != new-HEAD) loads a different changelog
# and needs a rebuild. On a branch *creation* (`git checkout -b`) or no-op checkout
# (prev == new) the working-tree content is unchanged, so pql.db already holds the
# committed state AND any uncommitted ticket mutation set just before the branch was
# cut (e.g. a just-activated in_progress status) — so do NOTHING. A rebuild there
# would drop that mutation; the next commit's pre-commit hook flushes it normally.
# Doing nothing (rather than an eager `export --stage`) also avoids staging changelog
# rows mid-checkout — those could otherwise leak onto the wrong branch when a later
# switch rebuilds by replaying the working-tree changelog.
if [ "${3:-0}" = "1" ] && [ "$1" != "$2" ] && command -v pql >/dev/null 2>&1; then
    # Resolve the vault to THIS checkout explicitly. pql otherwise finds the vault
    # by walking up for a `.git` *directory* — but a linked worktree's `.git` is a
    # *file*, so a bare `pql` invoked from a worktree resolves to the MAIN checkout
    # and rebuilds main's pql.db, leaving the worktree's own empty (the symptom that
    # broke ticket/decision reads inside worktrees). `git rev-parse --show-toplevel`
    # returns this worktree's root; on the main checkout it is the repo root, so
    # this is a no-op there and a correctness fix in worktrees. (Upstream pql bug —
    # ~/Projects/pql/feature-request.md FR-4; drop the --vault once it lands.)
    vault="$(git rev-parse --show-toplevel 2>/dev/null)"
    if [ -n "$vault" ]; then
        pql --vault "$vault" plan rebuild >/dev/null 2>&1 || true
        pql --vault "$vault" decisions sync >/dev/null 2>&1 || true
    fi
fi
