name: Check Flux CRD Updates

on:
  schedule:
    # Run every Monday at 9 AM UTC
    - cron: '0 9 * * 1'
  workflow_dispatch:

permissions:
  contents: write
  pull-requests: write

jobs:
  check-crd-updates:
    name: Check for Flux CRD Updates
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@34e114876b0b11c390a56381ad16ebd13914f8d5 # v4
        with:
          token: ${{ secrets.GITHUB_TOKEN }}

      - name: Install Rust
        uses: dtolnay/rust-toolchain@stable

      - name: Install just and kopium
        run: cargo install just kopium

      - name: Fetch latest CRDs and regenerate models
        run: just update-flux

      - name: Run integration tests
        run: just test-integration

      - name: Check for changes
        id: changes
        run: |
          # Ignore lines that change every run regardless of CRD content:
          #   - kopium command: comment (contains random /tmp/tmp.XXXXX path)
          #   - generated_at timestamp in manifest.json
          if git diff -I 'kopium command:' -I '"generated_at":' --quiet; then
            echo "changed=false" >> "$GITHUB_OUTPUT"
            echo "No CRD or model changes detected."
          else
            echo "changed=true" >> "$GITHUB_OUTPUT"
            echo "Changed files:"
            git diff --name-only
          fi

      - name: Read updated versions from manifest
        if: steps.changes.outputs.changed == 'true'
        id: manifest
        run: |
          {
            echo "versions<<EOF"
            jq -r '.flux_versions | to_entries[] | "- \(.key): \(.value)"' manifest.json
            echo "EOF"
          } >> "$GITHUB_OUTPUT"

      - name: Create Pull Request
        if: steps.changes.outputs.changed == 'true'
        uses: peter-evans/create-pull-request@4e1beaa7521e8b457b572c090b25bd3db56bf1c5 # v5
        with:
          token: ${{ secrets.GITHUB_TOKEN }}
          commit-message: "chore: update Flux CRDs to latest versions"
          title: "chore: update Flux CRDs to latest versions"
          body: |
            This PR updates Flux CRDs to the latest versions and regenerates Rust models.

            **Updated components:**
            ${{ steps.manifest.outputs.versions }}

            **Files changed:**
            - `scripts/fetch-crds.sh` — updated version manifest
            - `crds/*.yaml` — updated CRD definitions
            - `src/models/_generated/` — regenerated Rust models
            - `manifest.json` — updated version manifest

            **Validation:**
            - ✅ CRDs fetched and models regenerated via `just update-flux`
            - ✅ Build verified via `cargo check`
            - ✅ Integration tests passing via `just test-integration`

            > Auto-generated by GitHub Actions
          branch: update-flux-crds
          delete-branch: true
