#!/usr/bin/env bash
#MISE description="Extract changelog section for a specific version"
#USAGE arg "<version>" help="Version to extract (e.g. '1.0.0')"
#USAGE flag "-o --output <file>" help="Output file path (default: stdout)"

set -euo pipefail

version="$usage_version"
output_file="${usage_output:-}"

echo "Extracting changelog for version: $version" >&2

# Extract changelog section for this version (including header)
changelog_content=$(awk -v version="$version" '
  /^## \[/ {
    if ($0 ~ "\\[" version "\\]") {
      found = 1
      print  # Include the version header
      next
    } else if (found) {
      exit
    }
  }
  found && /^## / { exit }
  found { print }
' CHANGELOG.md)

# Check if content was found
if [ -z "$changelog_content" ]; then
  echo "❌ No changelog entry found for version $version" >&2
  exit 1
fi

echo "✅ Found changelog entry for version $version" >&2

# Output to file or stdout
if [ -n "$output_file" ]; then
  echo "$changelog_content" > "$output_file"
  echo "📝 Changelog content written to: $output_file" >&2
else
  echo "$changelog_content"
fi
