#!/usr/bin/env bash
# Pre-commit hook: require UNRELEASED.md when staging src/ or tests/ changes.
# Skipped during rebase or amend operations — those rewrite existing history
# rather than introducing new user-facing changes, so a new UNRELEASED entry
# is not warranted (any user-facing entry was added by the original commit
# being rewritten).

# Skip during interactive or non-interactive rebase
if [ -d .git/rebase-merge ] || [ -d .git/rebase-apply ]; then
    exit 0
fi

# Skip during amend (reflog action set by git when amending)
case "$GIT_REFLOG_ACTION" in
    *amend*) exit 0 ;;
esac

staged=$(git diff --cached --name-only)

has_src=false
for f in $staged; do
    case "$f" in
        src/*|tests/*) has_src=true; break ;;
    esac
done

if $has_src; then
    if ! echo "$staged" | grep -q '^UNRELEASED\.md$'; then
        echo "ERROR: src/ or tests/ files are staged but UNRELEASED.md is not."
        echo "Add changelog entries to UNRELEASED.md before committing."
        exit 1
    fi
fi
