#!/bin/sh
# Auto-bumps the patch version in pyproject.toml on every commit, unless
# the commit already touches the version line itself (manual major/minor
# bumps aren't overridden). Installed via:
#   git config core.hooksPath scripts

set -e

PYPROJECT="pyproject.toml"
NPM_LAUNCHER="packaging/npm/launcher/package.json"

# The hook stages these files after updating them. Do not accidentally include
# unrelated working-tree edits in a commit that only staged other files.
if ! git diff --quiet -- "$PYPROJECT" "$NPM_LAUNCHER"; then
    echo "Version hook: stage or set aside unstaged metadata changes before committing." >&2
    exit 1
fi

# Resolve the interpreter before touching pyproject.toml. If it is missing we
# must fail with the reason and an untouched tree, not a half-bumped staged one.
if [ -f "$NPM_LAUNCHER" ]; then
    if ! python_command=$(command -v python3 || command -v python); then
        echo "Version hook: python3/python not found on PATH; cannot sync $NPM_LAUNCHER." >&2
        exit 1
    fi
fi

current=$(grep -m1 '^version = ' "$PYPROJECT" | sed -E 's/version = "([0-9]+)\.([0-9]+)\.([0-9]+)"/\1.\2.\3/' | tr -d '\r')

if git diff --cached -- "$PYPROJECT" | grep -q '^[+-]version = '; then
    # Manual bump: keep the version the commit sets, but still carry it
    # over to the npm launcher so the two never drift.
    next="$current"
else
    major=$(echo "$current" | cut -d. -f1)
    minor=$(echo "$current" | cut -d. -f2)
    patch=$(echo "$current" | cut -d. -f3)
    next="$major.$minor.$((patch + 1))"

    sed -E "s/^version = \"$current\"/version = \"$next\"/" "$PYPROJECT" > "$PYPROJECT.tmp"
    mv "$PYPROJECT.tmp" "$PYPROJECT"
    git add "$PYPROJECT"
fi

if [ -f "$NPM_LAUNCHER" ]; then
    # Updating the launcher's version alone leaves its five platform packages
    # on the old release. Parse JSON so formatting cannot hide stale pins.
    "$python_command" - "$NPM_LAUNCHER" "$next" <<'PY'
import json
import sys
from pathlib import Path

path = Path(sys.argv[1])
version = sys.argv[2]
original = path.read_text(encoding="utf-8")
manifest = json.loads(original)
manifest["version"] = version
for name in manifest.get("optionalDependencies", {}):
    if name.startswith("@omm-hippo/omm-"):
        manifest["optionalDependencies"][name] = version
updated = json.dumps(manifest, indent=2, ensure_ascii=False) + "\n"
if updated != original:
    temporary = path.with_name(path.name + ".tmp")
    temporary.write_text(updated, encoding="utf-8")
    temporary.replace(path)
PY
    git add "$NPM_LAUNCHER"
fi
