name: durable-approval

on:
  pull_request_target:
    types: [opened, synchronize, reopened, ready_for_review]

permissions:
  contents: read

jobs:
  enforce:
    name: durable-approval / protected-base-enforce
    runs-on: ubuntu-latest
    steps:
      - name: Check out protected-base controls
        uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2
        with:
          ref: ${{ github.event.pull_request.base.sha }}
          path: trusted
          fetch-depth: 1
      - name: Select the untrusted candidate as data
        id: scope
        env:
          BASE_SHA: ${{ github.event.pull_request.base.sha }}
          PR_HEAD_SHA: ${{ github.event.pull_request.head.sha }}
          PR_NUMBER: ${{ github.event.pull_request.number }}
          CANDIDATE_PATH: docs/content_engine/artifacts/durable-approval-how/release-candidate-7.json
        run: |
          set -euo pipefail
          [[ "$BASE_SHA" =~ ^([0-9a-f]{40}|[0-9a-f]{64})$ ]]
          [[ "$PR_HEAD_SHA" =~ ^([0-9a-f]{40}|[0-9a-f]{64})$ ]]
          [[ "$PR_NUMBER" =~ ^[0-9]+$ ]]
          git -C trusted fetch --no-tags --depth=1 origin "pull/${PR_NUMBER}/head"
          test "$(git -C trusted rev-parse FETCH_HEAD)" = "$PR_HEAD_SHA"
          if git -C trusted diff --quiet "$BASE_SHA" "$PR_HEAD_SHA" -- "$CANDIDATE_PATH"; then
            echo "governed=false" >> "$GITHUB_OUTPUT"
            echo "PASS out_of_scope candidate_path=$CANDIDATE_PATH"
            exit 0
          fi
          mkdir -p candidate
          git -C trusted show "${PR_HEAD_SHA}:${CANDIDATE_PATH}" > candidate/release-candidate-7.json
          echo "governed=true" >> "$GITHUB_OUTPUT"
      - name: Enforce approval with protected-base controls
        if: steps.scope.outputs.governed == 'true'
        run: |
          python3 trusted/docs/content_engine/artifacts/durable-approval-how/approval_gate.py \
            --policy trusted/docs/content_engine/artifacts/durable-approval-how/authority-policy.json \
            --proposal trusted/docs/content_engine/artifacts/durable-approval-how/proposal.json \
            --candidate candidate/release-candidate-7.json \
            --approval trusted/docs/content_engine/artifacts/durable-approval-how/approval-approved.json
