name: Vendoo Release Manifest Sync

on:
  push:
    branches:
      - 'release/*-production-update-v*'
  workflow_dispatch:

permissions:
  contents: write
  actions: write

concurrency:
  group: vendoo-release-manifest-sync-${{ github.ref }}
  cancel-in-progress: false

jobs:
  sync:
    name: Release-Manifest reproduzierbar synchronisieren
    runs-on: ubuntu-latest
    timeout-minutes: 10
    steps:
      - name: Release-Branch auschecken
        uses: actions/checkout@v6
        with:
          ref: ${{ github.ref }}
          fetch-depth: 0

      - name: Node.js 22 aktivieren
        uses: actions/setup-node@v4
        with:
          node-version: '22.x'

      - name: Release-Manifest erzeugen
        run: node tools/generate-release-manifest.mjs .

      - name: Geändertes Manifest committen
        id: manifest
        shell: bash
        run: |
          set -euo pipefail
          if git diff --quiet -- release-manifest.json; then
            echo "Release-Manifest ist bereits aktuell."
            echo "changed=false" >> "$GITHUB_OUTPUT"
            echo "head_sha=$(git rev-parse HEAD)" >> "$GITHUB_OUTPUT"
            exit 0
          fi
          git config user.name "vendoo-release-bot"
          git config user.email "vendoo-release-bot@users.noreply.github.com"
          git add release-manifest.json
          git commit -m "chore: Release-Manifest synchronisieren [manifest-sync]"
          git push origin HEAD:${GITHUB_REF_NAME}
          echo "changed=true" >> "$GITHUB_OUTPUT"
          echo "head_sha=$(git rev-parse HEAD)" >> "$GITHUB_OUTPUT"

      - name: Finalen Manifest-Head explizit validieren
        if: ${{ steps.manifest.outputs.changed == 'true' }}
        env:
          GH_TOKEN: ${{ github.token }}
        shell: bash
        run: |
          set -euo pipefail
          final_head="${{ steps.manifest.outputs.head_sha }}"
          remote_head="$(git ls-remote origin "refs/heads/${GITHUB_REF_NAME}" | awk '{print $1}')"
          if [[ -z "$remote_head" || "$remote_head" != "$final_head" ]]; then
            echo "Der gepushte Manifest-Head ist nicht stabil: lokal=$final_head remote=$remote_head" >&2
            exit 1
          fi
          gh workflow run ci.yml --repo "$GITHUB_REPOSITORY" --ref "$GITHUB_REF_NAME"
          gh workflow run sync-release-manifest.yml --repo "$GITHUB_REPOSITORY" --ref "$GITHUB_REF_NAME"
          echo "Vendoo CI und Manifest-Sync wurden für finalen Head $final_head explizit registriert."
