name: Ensure base commit
description: Ensure a shallow checkout has enough history to diff against a base SHA.
inputs:
  base-sha:
    description: Base commit SHA to diff against.
    required: true
  fetch-ref:
    description: Branch or ref to deepen/fetch from origin when base-sha is missing.
    required: true
runs:
  using: composite
  steps:
    - name: Ensure base commit is available
      shell: bash
      env:
        BASE_SHA: ${{ inputs.base-sha }}
        FETCH_REF: ${{ inputs.fetch-ref }}
      run: |
        set -euo pipefail

        if [ -z "$BASE_SHA" ] || [[ "$BASE_SHA" =~ ^0+$ ]]; then
          echo "No concrete base SHA available; skipping targeted fetch."
          exit 0
        fi

        if git rev-parse --verify "$BASE_SHA^{commit}" >/dev/null 2>&1; then
          echo "Base commit already present: $BASE_SHA"
          exit 0
        fi

        for deepen_by in 25 100 300; do
          echo "Base commit missing; deepening $FETCH_REF by $deepen_by."
          if ! git fetch --no-tags --deepen="$deepen_by" origin "$FETCH_REF"; then
            echo "::warning title=ensure-base-commit fetch failed::Failed to deepen $FETCH_REF by $deepen_by while looking for $BASE_SHA"
          fi
          if git rev-parse --verify "$BASE_SHA^{commit}" >/dev/null 2>&1; then
            echo "Resolved base commit after deepening: $BASE_SHA"
            exit 0
          fi
        done

        echo "Base commit still missing; fetching full history for $FETCH_REF."
        if ! git fetch --no-tags origin "$FETCH_REF"; then
          echo "::warning title=ensure-base-commit fetch failed::Failed to fetch full history for $FETCH_REF while looking for $BASE_SHA"
        fi
        if git rev-parse --verify "$BASE_SHA^{commit}" >/dev/null 2>&1; then
          echo "Resolved base commit after full ref fetch: $BASE_SHA"
          exit 0
        fi

        echo "Base commit still unavailable after fetch attempts: $BASE_SHA"
