#!/usr/bin/env bash
# shellcheck shell=bash
set -euxo pipefail

DRY_RUN="${DRY_RUN:-0}"

released_versions="$(git tag --list | grep -E '^v[0-9]+\.[0-9]+\.[0-9]+(-rc\.[0-9]+)?$')"
cur_version="$(cargo pkgid hk | cut -d# -f2 | cut -d@ -f2)"
if ! echo "$released_versions" | grep -q "^v$cur_version$"; then
  echo "Releasing $cur_version"
  if [ "${DRY_RUN:-}" == 0 ]; then
    # Only create and push the tag - release workflow handles the GitHub release
    # and crates.io publishing.
    git tag "v$cur_version"
    git push --tags
  fi
  exit 0
fi

version="$(git cliff --bumped-version)"

if [ "$DRY_RUN" -ne 0 ]; then
  changelog="$(git cliff --bump --unreleased --strip all)"
  echo "version: $version"
  echo "changelog: $changelog"
  exit 0
fi

# If there is no new version to bump (i.e., equal to current), skip creating a release PR
if [ "$version" = "v$cur_version" ]; then
  echo "No unreleased changes detected for hk; skipping release PR creation."
  exit 0
fi

# Generate changelog using git-cliff (LLM editorialization happens in release.yml after merge)
git cliff --bump -o CHANGELOG.md

# Get the unreleased notes for PR body
# Strip version header since PR title already has version
PR_BODY="$(git cliff --bump --unreleased --strip all | tail -n +3)"

# Bump [package].version and refresh hk's own Cargo.lock entry. Plain sed
# instead of cargo-edit's `cargo set-version`, which has no prebuilt binary and
# cost every mise install a ~2 minute compile.
sed -i.bak "/^\[package\]/,/^\[/ s/^\(version[[:space:]]*=[[:space:]]*\)\"[^\"]*\"/\1\"${version#v}\"/" Cargo.toml
rm Cargo.toml.bak
# Resolving the workspace syncs hk's own Cargo.lock entry without upgrading
# any dependency, the same lockfile effect `cargo set-version` had.
cargo metadata --format-version 1 >/dev/null
# sed succeeds even when nothing matched; refuse to release a stale version.
new_version="$(cargo pkgid hk | cut -d# -f2 | cut -d@ -f2)"
if [ "$new_version" != "${version#v}" ]; then
  echo "error: Cargo.toml version is $new_version after bumping to ${version#v}" >&2
  exit 1
fi

git config user.name mise-en-dev
git config user.email 123107610+mise-en-dev@users.noreply.github.com

# Regenerate rendered artifacts (CLI docs, usage, etc.) for the release
# This must run BEFORE update-version since update-version needs the generated docs
mise run render

# Update version references in docs and source files
VERSION="${version#v}" mise run update-version
git add \
  Cargo.* \
  CHANGELOG.md \
  docs \
  hk.usage.kdl \
  hk.pkl \
  src

git checkout -B release
git commit -m "chore: release $version"
git push origin release --force
gh pr create --title "chore: release $version" --body "$PR_BODY" --label "release" ||
  gh pr edit --title "chore: release $version" --body "$PR_BODY"
