#!/usr/bin/env bash
# Preserve staged source on a verified task branch for the app session's normal PR.
# The build checkout, protected default branch and unrelated dirty files stay intact.
set -euo pipefail

if git diff --cached --quiet; then
  echo "commit_bot_changes: nothing staged, skipping"
  exit 0
fi

staged="$(git diff --cached --name-only)"
has_auto=0
has_bump=0
# autoupdate_check.sh deliberately does NOT stage .github/workflows/deploy.yml
# (GITHUB_TOKEN cannot push workflow-file changes), so we only need to detect
# action/ paths to classify the commit as an autoupdate.
if grep -qE '^\.github/actions/(swift-app|android-app)/' <<<"$staged"; then has_auto=1; fi
# marketing-version-auto-bump (mmv_floor_check) writes the bumped value
# into the project's source-of-truth (resolved by version_utils):
#   - xcodegen project.yml / project.yaml / Project.yml / Project.yaml
#   - *.xcconfig referenced by the project
#   - project.pbxproj (only when no xcodegen spec is present)
#   - Info.plist's CFBundleShortVersionString
# Any of those staged paths means a version bump rode along in this
# commit; surface it in the subject so reviewers see the version
# delta without diffing.
if grep -qE '(\.pbxproj|Info\.plist|(^|/)[Pp]roject\.ya?ml|\.xcconfig)$' \
    <<<"$staged"; then
  has_bump=1
fi

# Build a subject that lists every concern that actually fired. Avoids a
# 2^N case explosion by composing components in a stable order.
parts=()
if [[ $has_auto -eq 1 ]]; then parts+=("autoupdate app-ci"); fi
if [[ $has_bump -eq 1 ]]; then parts+=("bump MARKETING_VERSION"); fi
if [[ ${#parts[@]} -eq 0 ]]; then
  subject="ci: bot maintenance [skip ci]"
else
  joined=""
  for ((i = 0; i < ${#parts[@]}; i++)); do
    if [[ $i -eq 0 ]]; then joined="${parts[i]}"
    else joined="$joined + ${parts[i]}"
    fi
  done
  subject="ci: $joined [skip ci]"
fi

git config user.name  >/dev/null 2>&1 || git config user.name  "github-actions[bot]"
git config user.email >/dev/null 2>&1 || \
  git config user.email "41898282+github-actions[bot]@users.noreply.github.com"

exec python3 "$(dirname "$0")/source_maintenance.py" "$subject"
