#!/bin/sh
# Print ONE release's user-facing notes — the `## [<version>]` CHANGELOG section, verbatim, minus
# its own header line — on STDOUT. This exists so the release body is never a hand-typed temp path.
#
# WHY (v0.28.0, 2026-08-21): the body was produced by writing the slice to `/tmp/notes.md` from
# python and reading `/tmp/notes.md` from MSYS sh. Those are TWO DIFFERENT FILES on this platform —
# python resolves `/tmp` drive-relative (C:\tmp), MSYS maps it to %LOCALAPPDATA%\Temp — so `gh` read
# a STALE notes file left there by an unrelated release and published spt-core's notes onto a
# claude-spt release. The slice was verified by printing it back, but the file printed was the one
# written, not the one consumed. Piping removes the file, and the shared filesystem, from the path.
#
# Usage:  sh ci/publish/release-notes.sh 0.28.0 [--changelog CHANGELOG.md]
#         gh release create vX.Y.Z --notes-file - < "$(sh ci/publish/release-notes.sh X.Y.Z)"   # NO
#         sh ci/publish/release-notes.sh X.Y.Z | gh release create vX.Y.Z --notes-file - …       # yes
# [impl->REQ-RELEASE-NOTES-FROM-CHANGELOG]
set -u

VERSION="${1:-}"
[ -n "$VERSION" ] || { echo "usage: release-notes.sh <version> [--changelog PATH]" >&2; exit 2; }
VERSION="${VERSION#v}"
shift
CHANGELOG="CHANGELOG.md"
if [ "${1:-}" = "--changelog" ]; then CHANGELOG="${2:-}"; fi
[ -f "$CHANGELOG" ] || { echo "release-notes: no changelog at $CHANGELOG" >&2; exit 2; }

# awk, not sed ranges: a section runs from its own `## [<version>]` header to the NEXT `## [`
# header, and the header line itself is dropped (the release body is the section's content).
body=$(awk -v want="## [$VERSION]" '
  index($0, want) == 1 { inside = 1; next }
  inside && index($0, "## [") == 1 { exit }
  inside { print }
' "$CHANGELOG")

# FAIL LOUDLY, never publish an empty or wrong body. A missing section means the changelog step was
# skipped — which is exactly when a stale body would otherwise sail through.
if [ -z "$(printf '%s' "$body" | tr -d '[:space:]')" ]; then
  echo "release-notes: no non-empty '## [$VERSION]' section in $CHANGELOG — write the changelog first" >&2
  exit 1
fi

# Trim leading/trailing blank lines; keep everything between exactly as written.
printf '%s\n' "$body" | awk '
  { lines[NR] = $0 }
  END {
    first = 1; last = NR
    while (first <= NR && lines[first] ~ /^[[:space:]]*$/) first++
    while (last >= first && lines[last] ~ /^[[:space:]]*$/) last--
    for (i = first; i <= last; i++) print lines[i]
  }
'
