#!/usr/bin/env bash
set -euo pipefail

# Usage ------------------------------------------------------------------
usage() {
  cat <<EOF
Usage: $(basename "$0") <bump>

  bump      Version bump kind passed to 'uv version --bump'
            (patch, minor, major, etc.)

Examples:
  $(basename "$0") patch
  $(basename "$0") minor
EOF
  exit 1
}

if [[ $# -ne 1 ]]; then
  usage
fi

PROJECT_DIR="$(cd "$(dirname "$(realpath "${BASH_SOURCE[0]}")")/.." && pwd)"
cd "$PROJECT_DIR"

BUMP="$1"

# Helpers ----------------------------------------------------------------
is_jj() { [[ -d "$PROJECT_DIR/.jj" ]]; }

check_clean() {
  if is_jj; then
    if [[ -n "$(jj diff --summary 2>/dev/null)" ]]; then
      echo "error: working copy is not clean (jj diff shows changes)" >&2
      exit 1
    fi
  else
    if [[ -n "$(git status --porcelain)" ]]; then
      echo "error: working copy is not clean (git status shows changes)" >&2
      exit 1
    fi
  fi
}

read_version() {
  uv version --short
}

# 1. Lint & type-check ---------------------------------------------------
echo "==> Running linters and type checkers..."
just lint

# 2. Ensure working copy is clean -----------------------------------------
echo "==> Checking working copy is clean..."
check_clean

# 3. Bump version and check tag ------------------------------------------
# CHANGELOG.md is hand-authored; update it manually before running this
# script.
OLD_VERSION="$(read_version)"
echo "==> current version: $OLD_VERSION"

echo "==> Bumping version ($BUMP)..."
uv version --bump "$BUMP"

NEW_VERSION="$(read_version)"
TAG="v${NEW_VERSION}"
echo "    new version: $NEW_VERSION"
echo "    tag:         $TAG"

if git rev-parse -q --verify "refs/tags/$TAG" >/dev/null 2>&1; then
  echo "error: tag '$TAG' already exists" >&2
  exit 1
fi

# 4. Commit ---------------------------------------------------------------
COMMIT_MSG="chore(release): ${NEW_VERSION}"
echo "==> Committing: $COMMIT_MSG"

if is_jj; then
  jj commit -m "$COMMIT_MSG"
else
  git add pyproject.toml
  git commit -m "$COMMIT_MSG"
fi

# 5. Tag -----------------------------------------------------------------
echo "==> Tagging $TAG"
if is_jj; then
  jj git import 2>/dev/null || true
  git tag -a "$TAG" --cleanup=verbatim -m "Release ${TAG}"
  jj git import 2>/dev/null || true
else
  git tag -a "$TAG" --cleanup=verbatim -m "Release ${TAG}"
fi

echo ""
echo "Done! Created tag: ${TAG}"
echo "To publish, push the tag:  git push origin ${TAG}"
