#!/bin/sh
# Read the PUBLISHED release body back from GitHub and prove it is this version's changelog section.
# The mandatory last act of a release: what you wrote is not evidence of what you published.
#
# Usage:  sh ci/publish/verify-release-notes.sh v0.28.0 [--repo owner/repo]
# Exit 0 = the published body matches the changelog section; 1 = mismatch (diff on stderr);
# 2 = usage / unreachable release.
# [impl->REQ-RELEASE-NOTES-FROM-CHANGELOG]
set -u

TAG="${1:-}"
[ -n "$TAG" ] || { echo "usage: verify-release-notes.sh <vX.Y.Z> [--repo owner/repo]" >&2; exit 2; }
shift
REPO=""
if [ "${1:-}" = "--repo" ]; then REPO="${2:-}"; fi

ROOT=$(CDPATH= cd "$(dirname "$0")/../.." && pwd)
cd "$ROOT" || exit 2

expected=$(sh ci/publish/release-notes.sh "$TAG") || exit 1

if [ -n "$REPO" ]; then
  published=$(gh release view "$TAG" --repo "$REPO" --json body --jq .body 2>/dev/null)
else
  published=$(gh release view "$TAG" --json body --jq .body 2>/dev/null)
fi
[ -n "$published" ] || { echo "verify-release-notes: no body readable for $TAG (release missing, or gh not authed)" >&2; exit 2; }

# Compare ignoring CR and trailing whitespace only — the body is otherwise verbatim.
norm() { tr -d '\r' | sed 's/[[:space:]]*$//'; }
a=$(printf '%s\n' "$expected"  | norm)
b=$(printf '%s\n' "$published" | norm)

if [ "$a" = "$b" ]; then
  echo "ok   published body of $TAG matches the changelog section"
  exit 0
fi

echo "MISMATCH: the published body of $TAG is NOT this version's changelog section." >&2
echo "--- expected (CHANGELOG) / +++ published (GitHub) ---" >&2
printf '%s\n' "$a" > "$ROOT/dist/.notes-expected.$$" 2>/dev/null || true
printf '%s\n' "$b" > "$ROOT/dist/.notes-published.$$" 2>/dev/null || true
if [ -f "$ROOT/dist/.notes-expected.$$" ] && [ -f "$ROOT/dist/.notes-published.$$" ]; then
  diff -u "$ROOT/dist/.notes-expected.$$" "$ROOT/dist/.notes-published.$$" >&2
  rm -f "$ROOT/dist/.notes-expected.$$" "$ROOT/dist/.notes-published.$$"
else
  echo "(expected head) $(printf '%s' "$a" | head -c 200)" >&2
  echo "(published head) $(printf '%s' "$b" | head -c 200)" >&2
fi
echo "FIX: sh ci/publish/release-notes.sh $TAG | gh release edit $TAG ${REPO:+--repo $REPO} --notes-file -" >&2
exit 1
