# shellcheck shell=bash

fh_verify_formula() {
  fh_log_info "📝 Step 1: Updating Homebrew formula with hanging fix..."
  if grep -q 'case "${1:-}"' install/homebrew/Formula/orchestra.rb; then
    fh_log_success "✓ Homebrew formula already contains the hanging fix"
  else
    fh_log_error "Homebrew formula needs to be manually updated with the hanging fix"
    exit 1
  fi
}

fh_commit_fix() {
  fh_log_info "💾 Step 2: Committing hanging fix to local repository..."
  git add install/homebrew/Formula/orchestra.rb
  if git diff --cached --quiet; then
    fh_log_info "No changes to commit (already up to date)"
  else
    git commit -m "Fix hanging issue in Homebrew formula wrapper

- Replace stdout capture with smart routing logic
- TUI operations run directly (no stdout capture)  
- CLI operations use temp file approach
- Fixes orchestra --help and orchestra hanging issues"
    fh_log_success "✓ Committed hanging fix"
  fi
}

fh_push_fix() {
  fh_log_info "🚀 Step 3: Pushing fixes to GitHub..."
  git push origin main
  fh_log_success "✓ Pushed to GitHub"
}

fh_update_homebrew_tap() {
  fh_log_info "🍺 Step 4: Updating Homebrew tap with fixed formula..."
  if ! ./install/scripts/update-homebrew-formula.sh 0.1.8; then
    fh_log_error "Failed to update Homebrew tap"
    exit 1
  fi
  fh_log_success "✓ Updated Homebrew tap repository"
}

fh_create_patch_release() {
  fh_log_info "📦 Step 5: Creating patch release v0.1.9 with hanging fix..."
  PATCH_VERSION=$(./install/scripts/get-next-version.sh patch)
  fh_log_info "Creating patch release: $PATCH_VERSION"

  if ! ./install/scripts/full-release-automation.sh "$PATCH_VERSION"; then
    fh_log_error "Failed to create patch release"
    exit 1
  fi

  fh_log_success "✓ Deployed patch release $PATCH_VERSION"
  export PATCH_VERSION
}

fh_summary() {
  local version="$PATCH_VERSION"
  echo
  fh_log_success "🎉 HANGING FIX DEPLOYED SUCCESSFULLY!"
  echo "===================================="
  fh_log_info "Patch Version: $version"
  fh_log_info "GitHub Release: https://github.com/humanunsupervised/orchestra/releases/tag/v$version"
  echo
  fh_log_success "Users can now get the fix with:"
  fh_log_success "  brew update"
  fh_log_success "  brew upgrade orchestra"
  fh_log_success "  orchestra --help  # Should work immediately!"
  echo
  fh_log_info "🧪 Test the fix yourself:"
  fh_log_info "  brew uninstall orchestra 2>/dev/null || true"
  fh_log_info "  brew update && brew install orchestra"
  fh_log_info "  orchestra --help  # Should work without hanging"
  echo
  fh_log_warn "⚠️  Note: It may take a few minutes for Homebrew to pick up the changes"
  fh_log_warn "    Users experiencing issues can force update with:"
  fh_log_warn "      brew untap humanunsupervised/orchestra"
  fh_log_warn "      brew tap humanunsupervised/orchestra"
  fh_log_warn "      brew install orchestra"
}
