#!/usr/bin/env bash
set -euo pipefail

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

git diff --cached --check

primary="$(scripts/detect-primary-branch.sh)"
current="$(git branch --show-current)"
git config --local "branch.$primary.mergeOptions" --no-ff

if [[ "$current" == "$primary" ]]; then
    merge_head="$(git rev-parse --git-path MERGE_HEAD)"
    [[ -e "$merge_head" ]] || {
        printf 'Direct commits on primary are not allowed: %s\n' "$primary" >&2
        exit 1
    }

    # Explicit --no-commit candidates and resolved conflicts both enter here.
    exec "$repo_root/.githooks/run-release-gate" run --index
fi

if [[ -x .venv/bin/python ]]; then
    python=.venv/bin/python
elif [[ -x .venv/Scripts/python.exe ]]; then
    python=.venv/Scripts/python.exe
else
    printf 'Create the local environment with scripts/rebuild-env.sh\n' >&2
    exit 1
fi
scope="$("$python" scripts/check_change_scope.py --index --base HEAD)"
case "$scope" in
    documentation) "$python" scripts/check-docs.py --index --base HEAD ;;
    full) scripts/check-fast.sh ;;
    *) printf 'Invalid check scope: %s\n' "$scope" >&2; exit 1 ;;
esac

# A pyproject.toml change receives the cheap staged-version policy here. The
# exact integration candidate receives the complete release gate before merge.
if ! git diff --cached --quiet -- pyproject.toml; then
    exec "$repo_root/.githooks/run-release-gate" pre-commit
fi

exit 0
