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

VERSION=${1:-}
if [[ ! "$VERSION" =~ ^v[0-9]+\.[0-9]+\.[0-9]+$ ]]; then
  echo "Usage: $0 v<major>.<minor>.<patch>" >&2; exit 1
fi

branch=$(git rev-parse --abbrev-ref HEAD)
if [[ "$branch" != "main" ]]; then
  echo "Must be on main (currently on $branch)" >&2; exit 1
fi
if ! git diff --quiet || ! git diff --cached --quiet; then
  echo "Working tree is not clean" >&2; exit 1
fi

echo "Checking latest CI run on main..."
gh run list --branch main --workflow CI.yml --limit 1 --json conclusion -q '.[0].conclusion' \
  | grep -q "success" || { echo "Latest CI run on main did not succeed" >&2; exit 1; }

git tag "$VERSION"
git push origin "$VERSION"
echo "Pushed tag $VERSION — waiting for publish workflow to start..."
run_id=""
while [[ -z "$run_id" ]]; do
  sleep 2
  run_id=$(gh run list --workflow publish.yml --limit 1 --json databaseId,headBranch -q ".[] | select(.headBranch == \"$VERSION\") | .databaseId")
done
echo "Watching run $run_id..."
gh run watch "$run_id" --exit-status
