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

BASE_REF="${1:-origin/main}"
BASE_BRANCH="${BASE_REF#origin/}"

git fetch --no-tags --depth=1 origin "$BASE_BRANCH"

current_version="$(node -e 'const fs = require("fs"); const pkg = JSON.parse(fs.readFileSync("package.json", "utf8")); process.stdout.write(String(pkg.version || ""));')"
base_version="$(git show "$BASE_REF:package.json" | node -e 'let input = ""; process.stdin.setEncoding("utf8"); process.stdin.on("data", chunk => input += chunk); process.stdin.on("end", () => { const pkg = JSON.parse(input); process.stdout.write(String(pkg.version || "")); });')"

if [ -z "$current_version" ]; then
  echo "ERROR: package.json enthält kein version-Feld."
  exit 1
fi

if [ "$current_version" = "$base_version" ]; then
  echo "ERROR: package.json version wurde nicht geändert."
  echo "Base ($BASE_REF): $base_version"
  echo "Current: $current_version"
  echo "Bitte version in package.json erhöhen, bevor nach main gemerged wird."
  exit 1
fi

echo "package.json version changed: $base_version -> $current_version"
