#!/usr/bin/env bash
# Open or update the ramp-rails refresh PR with the regenerated matrix + dumps.
# Required env: GH_TOKEN, DRIFT_SUMMARY (path to diff text). Optional: RUN_URL, BASE_BRANCH (default main).
set -euo pipefail

BRANCH="automation/ramp-rails-refresh"
BASE="${BASE_BRANCH:-main}"
DRIFT_SUMMARY="${DRIFT_SUMMARY:?DRIFT_SUMMARY required}"
RUN_URL="${RUN_URL:-}"
PATHS=(apps/sdp-api/.ramp-rails packages/sdp-types/src/generated/ramp-support.generated.ts)

git config user.name "github-actions[bot]"
git config user.email "41898282+github-actions[bot]@users.noreply.github.com"

git fetch origin "$BRANCH" 2>/dev/null || true
git checkout -B "$BRANCH"
git add "${PATHS[@]}"

if git diff --cached --quiet; then
  echo "::notice title=Ramp rails refresh::No matrix/dump changes to commit."
  exit 0
fi

TITLE="chore(ramp-rails): refresh supported corridor matrix"
BODY_FILE="$(mktemp)"
trap 'rm -f "$BODY_FILE"' EXIT
{
  echo "Automated live discovery refreshed the committed ramp dumps and/or support matrix."
  echo
  echo "Changed files:"
  echo '```'
  git diff --cached --stat
  echo '```'
  echo
  echo "Support-matrix drift:"
  echo '```'
  if [ -f "$DRIFT_SUMMARY" ]; then cat "$DRIFT_SUMMARY"; else echo "(drift summary unavailable)"; fi
  echo '```'
  echo
  if [ -n "$RUN_URL" ]; then echo "Generated by [this run]($RUN_URL)."; echo; fi
  echo "Review the diff and merge to bring the committed matrix back in sync. Do not auto-merge."
} >"$BODY_FILE"

git commit -m "$TITLE"
if git rev-parse --verify --quiet "refs/remotes/origin/$BRANCH" >/dev/null; then
  git push --force-with-lease origin "$BRANCH"
else
  git push origin "$BRANCH"
fi

existing="$(gh pr list --head "$BRANCH" --state open --json number --jq '.[0].number // empty' 2>/dev/null || true)"
if [ -n "$existing" ]; then
  gh pr edit "$existing" --title "$TITLE" --body-file "$BODY_FILE"
  echo "Updated existing refresh PR #$existing."
else
  gh pr create --base "$BASE" --head "$BRANCH" --title "$TITLE" --body-file "$BODY_FILE"
fi
