name: Update Agent Templates Index

on:
  push:
    branches: [main]
    paths:
      - "agents/*.yaml"

jobs:
  update-index:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4

      - name: Generate index.json
        run: |
          cd agents
          echo '[' > index.json
          first=true
          for f in *.yaml; do
            [ "$f" = "*.yaml" ] && break
            $first || echo ',' >> index.json
            first=false
            # extract name from yaml
            name=$(grep '^name:' "$f" | sed 's/^name: *//')
            slug="${f%.yaml}"
            printf '  {"slug":"%s","name":"%s"}' "$slug" "$name" >> index.json
          done
          echo '' >> index.json
          echo ']' >> index.json

      - name: Commit index.json
        run: |
          git config user.name "github-actions[bot]"
          git config user.email "github-actions[bot]@users.noreply.github.com"
          git add agents/index.json
          git diff --cached --quiet && exit 0
          git commit -m "chore: update agent templates index"
          git push
