#!/bin/bash
set -euo pipefail

OUT_FILE="${1:-changed_files.txt}"
touch "$OUT_FILE"

# Fetch quietly; repo might be shallow in CI
git fetch --all --quiet || true

if [[ -n "${CHANGE_TARGET:-}" ]]; then
  # Multibranch PR build: compare against target branch
  git fetch origin "${CHANGE_TARGET}" --quiet || true
  BASE="origin/${CHANGE_TARGET}"
  echo "[INFO] PR build detected, diffing against ${BASE}..."
  git diff --name-only --diff-filter=ACMRT "${BASE}...HEAD" > "$OUT_FILE" || true
else
  # Branch build: diff from previous successful commit (best effort), else last commit
  if [[ -n "${GIT_PREVIOUS_SUCCESSFUL_COMMIT:-}" ]]; then
    BASE="${GIT_PREVIOUS_SUCCESSFUL_COMMIT}"
    echo "[INFO] Diffing against previous successful commit ${BASE}..."
    git diff --name-only --diff-filter=ACMRT "${BASE}" "HEAD" > "$OUT_FILE" || true
  else
    echo "[INFO] No previous successful commit found; using last commit diff (HEAD~1..HEAD)..."
    git diff --name-only --diff-filter=ACMRT "HEAD~1" "HEAD" > "$OUT_FILE" || true
  fi
fi

# Clean blank lines, ensure file exists
sed -i '/^\s*$/d' "$OUT_FILE" || true
touch "$OUT_FILE"

COUNT=$(wc -l < "$OUT_FILE" | tr -d ' ')
echo "[INFO] Changed files: ${COUNT}"