name: Documentation Sync

on:
  pull_request:
    branches: [ master ]
    paths:
      - 'src/**/*.rs'
      - 'docs/**/*.md'

permissions:
  contents: write

jobs:
  sync-docs:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
        with:
          ref: ${{ github.head_ref }}
          fetch-depth: 0

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

      - name: Build Decapod
        run: cargo build

      - name: Get changed files
        id: changed-files
        run: |
          git fetch origin master
          FILES=$(git diff --name-only origin/master HEAD | xargs)
          echo "files=$FILES" >> $GITHUB_OUTPUT

      - name: Run Docs Build
        run: |
          FILES="${{ steps.changed-files.outputs.files }}"
          if [ -n "$FILES" ]; then
            ./target/debug/decapod docs build --touched $FILES
          else
            ./target/debug/decapod docs build
          fi

      - name: Commit and push changes
        run: |
          git config --global user.name "github-actions[bot]"
          git config --global user.email "github-actions[bot]@users.noreply.github.com"
          git add docs/agent/command-contracts.md docs/agent/config-schema.md
          if git diff --staged --quiet; then
            echo "No doc changes detected."
          else
            git commit -m "docs: autogenerate/sync command contracts"
            git push
          fi
