#!/usr/bin/env bash
set -euo pipefail
source "$SHELLOPS_DIR/.envrc"
import "$SHELLOPS_DIR/lib/versions.api.sh"

USAGE="$(cat <<EOF
Remove orphaned tags whose commits are not reachable from any branch.

These typically result from force-pushes that rewrote the commits they
pointed to. They clutter the tag namespace and can cause version conflicts
in automated pipelines.

Usage: action git tags prune [options]

Options:
  --dry-run     Show what would be pruned without deleting
  -h, --help    Show this help text.
EOF
)"

function main() {
  local dry_run=false

  parse_args "$@"

  local pruned=0

  for tag in $(git tag); do
    local commit
    commit=$(git rev-list -n 1 "$tag" 2>/dev/null) || continue
    if ! git branch -a --contains "$commit" 2>/dev/null | grep -q .; then
      if [[ "$dry_run" == true ]]; then
        log "Would prune: $tag (commit ${commit:0:8} not on any branch)"
      else
        log "Pruning orphaned tag: $tag (commit ${commit:0:8})"
        git push origin ":refs/tags/$tag" 2>/dev/null || true
        git tag -d "$tag" 2>/dev/null || true
      fi
      pruned=$((pruned + 1))
    fi
  done

  if ((pruned == 0)); then
    log "No orphaned tags found."
  else
    local verb="Pruned"
    [[ "$dry_run" == true ]] && verb="Would prune"
    log "$verb $pruned orphaned tag(s)."
  fi
}

function parse_args() {
  while [[ $# -gt 0 ]]; do
    case "$1" in
      --dry-run) dry_run=true ;;
      -h|--help) log "$USAGE"; exit 0 ;;
      -*)
        error "Unknown option: $1"
        log "$USAGE"
        exit 1
        ;;
    esac
    shift
  done
}

if [[ "${BASH_SOURCE[0]}" == "$0" ]]; then
  main "$@"
fi
