#!/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]+)?$' || true)"
cur_version="$(cargo pkgid fnox | cut -d# -f2 | cut -d@ -f2)"
if [ -z "$released_versions" ] || ! echo "$released_versions" | grep -q "^v$cur_version$"; then
  echo "Releasing $cur_version"
  if [ "${DRY_RUN:-}" == 0 ]; then
    # Only create and push the tag - let the release workflow handle creating the release
    git tag "v$cur_version"
    git push --tags
    # Publish fnox-core first; fnox depends on it via path + version, so the
    # binary publish requires fnox-core at this version to be on crates.io.
    # Modern cargo waits for the index to update before returning.
    cargo publish -p fnox-core
    cargo publish -p fnox
  fi
  exit 0
fi

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

if [ "$DRY_RUN" -ne 0 ]; then
  echo "version: $version"
  echo "changelog: $(git cliff --bump --unreleased --strip all | tail -n +3)"
  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 fnox; skipping release PR creation."
  exit 0
fi

# Bump the workspace version; both `fnox` and `fnox-core` inherit it via
# `version.workspace = true`, and the path-dep version pin in fnox's
# Cargo.toml is updated automatically.
cargo set-version --workspace "${version#v}"

git config user.name mise-en-dev
git config user.email 123107610+mise-en-dev@users.noreply.github.com
mise run render ::: lint-fix

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

git add \
  Cargo.* \
  CHANGELOG.md \
  docs \
  fnox.usage.kdl

git checkout -B release
git commit -m "chore: release $version"
git push origin release --force

# Try to create PR, if it already exists then edit it
if ! gh pr create --title "chore: release $version" --body "$PR_BODY"; then
  echo "Failed to create PR, attempting to update existing PR"
  gh pr edit release --title "chore: release $version" --body "$PR_BODY" || true
fi
