#!/bin/sh

# --- helpers ---

die() { printf '%s\n' "error: $*" >&2; exit 1; }

usage() {
    printf 'Usage: pyproject-version-commit\n'
    printf '\n'
    printf 'Stage and commit pyproject.toml and VERSION with a version bump message.\n'
    printf 'Aborts if any other tracked files have uncommitted changes.\n'
}

case ${1-} in --help|-h) usage; exit 0 ;; esac

# --- script ---

# Verify we're inside a git repository
git rev-parse --git-dir >/dev/null 2>&1 || die "not inside a git repository"

# Check for tracked changes to files other than pyproject.toml and VERSION.
# git status --porcelain lines: "XY path" — skip untracked (??) entries.
other_changes=$(git status --porcelain | grep -v '^??' | grep -vE '^.. (pyproject\.toml|VERSION|uv\.lock)$')

if [ -n "$other_changes" ]; then
    printf 'error: uncommitted changes to other files detected:\n' >&2
    printf '%s\n' "$other_changes" >&2
    printf '\nOnly pyproject.toml, VERSION, and uv.lock may have changes before running this command.\n' >&2
    exit 1
fi

# Ensure at least one target file actually has changes to commit
target_changes=$(git status --porcelain | grep -v '^??' | grep -E '^.. (pyproject\.toml|VERSION|uv\.lock)$')
if [ -z "$target_changes" ]; then
    die "no changes found in pyproject.toml or VERSION — nothing to commit"
fi

# Read the version for a descriptive commit message
version=''
if [ -f VERSION ]; then
    version=$(cat VERSION)
fi

# Stage only the target files
git add -- pyproject.toml VERSION uv.lock || die "failed to stage files"

# Build commit message
if [ -n "$version" ]; then
    msg="chore: bump version to ${version}"
else
    msg="chore: update pyproject.toml and VERSION"
fi

git commit -m "$msg" || die "git commit failed"
printf 'committed: %s\n' "$msg"
