name: Cookidoo API Discovery of Well Known HAL Endpoint

on:
  schedule:
    - cron: "0 3 * * *"   # täglich um 03:00 UTC
  workflow_dispatch:

permissions:
  contents: write
  pull-requests: write

env:
  python-version: "3.12"

concurrency: 
  group: "well-known-discovery" # Make sure, to not run multiple smoke tests at the same time
  cancel-in-progress: false

jobs:
  discover:
    runs-on: ubuntu-latest

    steps:
      - name: Checkout repository
        uses: actions/checkout@v6

      - name: Set up Python
        uses: actions/setup-python@v6
        with:
          python-version: ${{ env.python-version }}

      - name: Install dependencies
        run: |
          python -m pip install --upgrade pip
          pip install requests

      - name: Run discovery
        id: discovery
        run: |
          python scripts/well-known-discovery.py
        continue-on-error: true

      - name: Detect changes
        id: diff
        run: |
          git status --porcelain
          if [[ -n "$(git status --porcelain)" ]]; then
            echo "changed=true" >> $GITHUB_OUTPUT
          else
            echo "changed=false" >> $GITHUB_OUTPUT
          fi
      - name: Configure Git
        if: steps.diff.outputs.changed == 'true'
        run: |
          git config --global user.name "github-actions[bot]"
          git config --global user.email "github-actions[bot]@users.noreply.github.com"
      - name: Prepare PR body
        if: steps.diff.outputs.changed == 'true'
        run: |
          {
            echo "## 🔍 Change summary"
            echo
            echo '```json'
            cat diff-summary.json
            echo
            echo '```'
            echo
            echo '_This PR contains automated changes made by the 🤖 well-known-discovery workflow._'
          } > pr-body.md

      - name: Commit and push changes
        if: steps.diff.outputs.changed == 'true'
        run: |
          git checkout -b well-known-discovery-update-$(date +%Y%m%d%H%M%S)
          git add well-known-snapshots/latest.json
          git commit -m "🤖 update Cookidoo API discovery snapshot"
          git push origin HEAD
        env:
          GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}

      - name: Create pull request
        if: steps.diff.outputs.changed == 'true'
        run: |
          BRANCH_NAME=$(git rev-parse --abbrev-ref HEAD)
          gh pr create --base master --head $BRANCH_NAME --title '🤖 update Cookidoo API discovery snapshot' --body-file pr-body.md
          PR_NUMBER=$(gh pr view --json number -q ".number")
          gh pr edit $PR_NUMBER --add-label ":boom: breaking change"
        env:
            GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}