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

usage() {
  cat <<'USAGE'
Usage: scripts/release/cut_release_tag.sh <tag> [--push]

Create an annotated release tag from the current checkout.

Requirements:
- tag must match vX.Y.Z (optional suffix like -rc.1)
- working tree must be clean
- HEAD must match origin/master
- tag must not already exist locally or on origin

Options:
  --push   Push the tag to origin after creating it
USAGE
}

if [[ $# -lt 1 || $# -gt 2 ]]; then
  usage
  exit 1
fi

TAG="$1"
PUSH_TAG="false"
if [[ $# -eq 2 ]]; then
  if [[ "$2" != "--push" ]]; then
    usage
    exit 1
  fi
  PUSH_TAG="true"
fi

SEMVER_PATTERN='^v[0-9]+\.[0-9]+\.[0-9]+([.-][0-9A-Za-z.-]+)?$'
if [[ ! "$TAG" =~ $SEMVER_PATTERN ]]; then
  echo "error: tag must match vX.Y.Z or vX.Y.Z-suffix (received: $TAG)" >&2
  exit 1
fi

if ! git rev-parse --is-inside-work-tree >/dev/null 2>&1; then
  echo "error: run this script inside the git repository" >&2
  exit 1
fi

if ! git diff --quiet || ! git diff --cached --quiet; then
  echo "error: working tree is not clean; commit or stash changes first" >&2
  exit 1
fi

# Auto-sync all version references before tagging
SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
RELEASE_VERSION="${TAG#v}"
bash "$SCRIPT_DIR/bump-version.sh" "$RELEASE_VERSION"
if ! git diff --quiet; then
  git add -A
  git commit -m "chore: sync version references to $TAG"
  echo "Auto-committed version sync for $TAG"
fi

echo "Fetching origin/master and tags..."
git fetch --quiet origin master --tags

HEAD_SHA="$(git rev-parse HEAD)"
MASTER_SHA="$(git rev-parse origin/master)"
if [[ "$HEAD_SHA" != "$MASTER_SHA" ]]; then
  echo "error: HEAD ($HEAD_SHA) is not origin/master ($MASTER_SHA)." >&2
  echo "hint: checkout/update master before cutting a release tag." >&2
  exit 1
fi

if git show-ref --tags --verify --quiet "refs/tags/$TAG"; then
  echo "error: tag already exists locally: $TAG" >&2
  exit 1
fi

if git ls-remote --exit-code --tags origin "refs/tags/$TAG" >/dev/null 2>&1; then
  echo "error: tag already exists on origin: $TAG" >&2
  exit 1
fi

MESSAGE="kylinbot $TAG"
git tag -a "$TAG" -m "$MESSAGE"
echo "Created annotated tag: $TAG"

if [[ "$PUSH_TAG" == "true" ]]; then
  git push origin "$TAG"
  echo "Pushed tag to origin: $TAG"
  echo "Release Stable workflow will auto-trigger via tag push."
  echo "Monitor: gh workflow view 'Release Stable' --web"
else
  echo "Next step: git push origin $TAG"
  echo "This will auto-trigger the Release Stable workflow (builds, Docker, crates.io, website, Scoop, AUR, Homebrew, tweet)."
fi
