#!/usr/bin/env bash
#MISE description="Generate editorialized release notes with Claude Code"
#USAGE arg "<version>" help="Git tag/version to generate notes for"
#USAGE arg "<output_dir>" help="Directory to write title and notes files"
#USAGE arg "[prev_version]" help="Previous version"
set -euo pipefail

# shellcheck disable=SC2154
version="${usage_version}"
# shellcheck disable=SC2154
output_dir="${usage_output_dir}"
# shellcheck disable=SC2154
prev_version="${usage_prev_version:-}"

mkdir -p "$output_dir"

# Get the git-cliff changelog for context
# Use the tag range if prev_version provided, otherwise unreleased
if [[ -n $prev_version ]]; then
	changelog=$(git cliff --strip all "${prev_version}..${version}" 2>/dev/null || echo "")
else
	changelog=$(git cliff --unreleased --strip all 2>/dev/null || echo "")
fi

if [[ -z $changelog ]]; then
	echo "Error: No changes found for release" >&2
	exit 1
fi

output_file=$(mktemp /tmp/release-notes-XXXXXX.md)
stderr_file=$(mktemp)
trap 'rm -f "$stderr_file" "$output_file"' EXIT

# Build prompt safely using printf to avoid command substitution on backticks in changelog
prompt=$(
	printf '%s\n' "You are writing release notes for mise version ${version}${prev_version:+ (previous version: ${prev_version})}."
	printf '\n'
	printf '%s\n' "mise is a polyglot runtime manager (like asdf, nvm, pyenv, etc), environment manager, and task runner."
	printf '\n'
	printf '%s\n' "Here is the raw changelog from git-cliff:"
	printf '%s\n' "$changelog"
	printf '\n'
	cat <<'INSTRUCTIONS'
Write user-friendly release notes with a creative title:

FORMAT:
- First line: A short, creative release title (2-6 words, no version number, captures the theme of the release)
- Second line: Empty
- Rest: The release notes

TITLE GUIDELINES:
- Be creative and memorable (e.g., "The Great Backend Migration", "Conda Gets Cozy", "Monorepo Magic")
- Reference the main theme or biggest feature of the release
- Keep it fun but professional
- For smaller or less impactful releases, keep the title understated and modest

TONE CALIBRATION:
- Match the tone and length to the actual significance of the changes
- If the release is mostly small bug fixes or minor tweaks, be upfront about that—a sentence or two of summary is fine, don't write multiple paragraphs inflating the importance
- Reserve enthusiastic, detailed write-ups for releases with genuinely significant features or changes
- It's okay to say "This is a smaller release focused on bug fixes" when that's the case

RELEASE NOTES:
1. Start with a summary proportional to the significance of the changes
2. Organize into ### sections (Highlights, Bug Fixes, etc.)
3. Explain WHY changes matter to users
4. Include PR links and documentation links (https://mise.jdx.dev/)
5. Include contributor usernames (@username). Do not thank @jdx since that is who is writing these notes.
6. Skip internal changes

Output ONLY the title, blank line, and release notes - no other preamble.
INSTRUCTIONS
	printf '\n%s\n' "Write your output to the file: ${output_file}"
	printf '%s\n' "Do not output anything else — just write to the file."
)

# Use Claude Code to generate the release notes
# Claude writes to a temp file via the Write tool to avoid formatting artifacts from stdout
echo "Generating release notes with Claude..." >&2
echo "Version: $version" >&2
echo "Previous version: ${prev_version:-none}" >&2
echo "Changelog length: ${#changelog} chars" >&2

if ! printf '%s' "$prompt" | claude -p \
	--model claude-opus-4-6 \
	--permission-mode bypassPermissions \
	--allowedTools "Read,Grep,Glob,Write($output_file)" >/dev/null 2>"$stderr_file"; then
	echo "Error: Claude CLI failed" >&2
	if [[ -s $stderr_file ]]; then
		cat "$stderr_file" >&2
	else
		echo "(no stderr output from Claude CLI)" >&2
	fi
	exit 1
fi

# Validate the output file was created and is non-empty
if [[ ! -s $output_file ]]; then
	echo "Error: Claude did not write release notes to $output_file" >&2
	cat "$stderr_file" >&2
	exit 1
fi

output=$(cat "$output_file")

echo "Raw output:"
cat "$output_file"

# Parse title from first line and body from rest
title=$(printf '%s\n' "$output" | head -1)
body=$(printf '%s\n' "$output" | tail -n +3)

# Validate we got non-empty output
if [[ -z $body ]]; then
	echo "Error: Empty body after parsing" >&2
	exit 1
fi

# Write parsed results to output directory
printf '%s\n' "$title" >"$output_dir/title"
printf '%s\n' "$body" >"$output_dir/notes"
echo "Wrote title and notes to $output_dir"
