name: Documentation Build

on:
  push:
    paths:
      - 'docs/tutorial.adoc'
    branches:
      - master
  pull_request:
    paths:
      - 'docs/tutorial.adoc'
    branches:
      - master

jobs:
  build-docs:
    runs-on: ubuntu-latest
    steps:
      - name: Checkout
        uses: actions/checkout@v4
        with:
          token: ${{ secrets.GITHUB_TOKEN }}

      - name: Setup Ruby and install asciidoctor
        uses: ruby/setup-ruby@v1
        with:
          ruby-version: 3.1
          bundler-cache: false

      - name: Install asciidoctor
        run: gem install asciidoctor

      - name: Convert AsciiDoc to HTML
        run: |
          cd docs
          asciidoctor tutorial.adoc
          
      - name: Check if HTML was generated
        run: |
          if [ ! -f docs/tutorial.html ]; then
            echo "Error: tutorial.html was not generated"
            exit 1
          fi
          echo "tutorial.html successfully generated ($(stat -c%s docs/tutorial.html) bytes)"

      - name: Commit and push if changed
        run: |
          git config --local user.email "action@github.com"
          git config --local user.name "GitHub Action"
          git add docs/tutorial.html
          if git diff --staged --quiet; then
            echo "No changes to commit"
          else
            git commit -m "docs: auto-regenerate tutorial.html from tutorial.adoc

            Generated by GitHub Actions workflow"
            git push
          fi