#!/usr/bin/env bash
#
# Git credential helper that uses GitHub CLI (gh) for authentication.
# Falls back through multiple installation methods to find gh.

# Enable debug logging with GH_CREDENTIAL_DEBUG=1
debug() {
  if [[ "${GH_CREDENTIAL_DEBUG:-}" == "1" ]]; then
    echo "DEBUG: $*" >&2
  fi
}

# Show help if requested
if [[ "${1:-}" == "-h" || "${1:-}" == "--help" ]]; then
  cat >&2 << 'EOF'
Git credential helper for GitHub CLI (gh)

This script attempts to use 'gh auth git-credential' through various
installation methods:
1. gh in PATH
2. gh via mise tool manager
3. gh via mise in ~/.local/bin/mise
4. gh via mise shims

Environment variables:
  GH_CREDENTIAL_DEBUG=1    Enable debug output

Configuration example for .gitconfig:
  [credential "https://github.com"]
      helper = !gh-git-credential-helper
  [credential "https://gist.github.com"]
      helper = !gh-git-credential-helper
EOF
  exit 0
fi

if command -v gh > /dev/null 2>&1; then
  debug "Using gh from PATH"
  exec gh auth git-credential "$@"
elif command -v mise > /dev/null 2>&1; then
  debug "Using gh via mise from PATH"
  exec mise x gh -- gh auth git-credential "$@"
elif [ -f "${HOME}/.local/bin/mise" ]; then
  debug "Using gh via mise from ~/.local/bin/mise"
  exec "${HOME}/.local/bin/mise" x gh -- gh auth git-credential "$@"
elif [ -f "${HOME}/.local/share/mise/shims/gh" ]; then
  debug "Using gh from mise shims"
  exec "${HOME}/.local/share/mise/shims/gh" auth git-credential "$@"
else
  echo "ERROR: GitHub CLI (gh) not found via any method" >&2
  exit 1
fi
