#!/usr/bin/env bash
#
# Generate Fish abbreviations from shared YAML source
# Usage: ./generate-fish-abbr.sh

set -euo pipefail

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"

# Load shared utilities
source "${SCRIPT_DIR}/generator-utils.sh"
YAML_FILE="${SCRIPT_DIR}/abbreviations.yaml"
OUTPUT_FILE="${SCRIPT_DIR}/../fish/.config/fish/abbreviations.fish"

if ! command -v yq >/dev/null 2>&1; then
  echo "Error: yq is required but not installed. Install it with: brew install yq"
  exit 1
fi

if [[ ! -f "${YAML_FILE}" ]]; then
  echo "Error: YAML file not found: ${YAML_FILE}"
  exit 1
fi

echo "Generating Fish abbreviations from ${YAML_FILE}..."

# Generate the header
cat >"${OUTPUT_FILE}" <<'EOF'
# Fish abbreviations - Generated from shared/abbreviations.yaml
# DO NOT EDIT THIS FILE DIRECTLY - Edit shared/abbreviations.yaml instead
# Regenerate with: bash shared/generate-fish-abbr.sh
#
# https://fishshell.com/docs/current/cmds/abbr.html

EOF

# Process each category in the YAML file
yq eval ". as \$root | keys | .[]" "${YAML_FILE}" | while read -r category; do
  # Skip shell-specific categories for Fish
  if should_skip_category "fish" "${category}"; then
    continue
  fi

  {
    echo "# $(to_title_case "${category}")"
    yq eval ".${category} | to_entries | .[] | \"abbr -a -g \" + .key + \" '\" + (.value.command // .value) + \"'\"" "${YAML_FILE}"
    echo ""
  } >>"${OUTPUT_FILE}"
done

# Add note about functions that replace some abbreviations
cat >>"${OUTPUT_FILE}" <<'EOF'

# Note: Some abbreviations have been replaced by smart functions:
# - gpum: Use gpum function (smart git push with upstream tracking)
# - grbm: Use grbm function (smart git rebase against default branch)
# - gcom: Use gcom function (smart git checkout default branch)
EOF

echo "✅ Generated Fish abbreviations: ${OUTPUT_FILE}"
echo "📊 Total abbreviations: $(grep -c '^abbr' "${OUTPUT_FILE}")"
