#!/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)"

cargo set-version --package hk "${version#v}"

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"
