name: Deploy Documentation to GitHub Pages

on:
  push:
    branches:
      - main
    paths:
      - 'docs/**'
      - 'lib/**'
      - 'index.js'
      - 'package.json'
      - 'jsdoc.json'
      - '.github/workflows/**'
      - 'scripts/**'
  workflow_dispatch: # Allow manual trigger

permissions:
  contents: read
  pages: write
  id-token: write

jobs:
  build-and-deploy-docs:
    runs-on: ubuntu-latest
    environment:
      name: github-pages
      url: ${{ steps.deployment.outputs.page_url }}
    steps:
      - name: Checkout repository
        uses: actions/checkout@v4

      - name: Setup Node.js
        uses: actions/setup-node@v4
        with:
          node-version: 'lts/*'
          cache: 'npm'

      - name: Install Protocol Buffers Compiler and Plugins
        run: |
          sudo apt-get update
          sudo apt-get install -y protobuf-compiler
          sudo npm install -g google-protobuf
          sudo npm install -g protoc-gen-js
          protoc --version

      - name: Install dependencies
        run: npm ci

      - name: Make scripts executable
        run: |
          chmod +x ./scripts/clone-protos.sh
          chmod +x ./scripts/generate-protos.sh

      - name: Setup Protos
        run: npm run setup

      - name: List proto files
        run: find protos -name "*.proto" -type f

      - name: Build JSDoc API Documentation
        run: npm run docs:generate-api

      - name: Setup Ruby
        uses: ruby/setup-ruby@v1
        with:
          ruby-version: '3.2'
          bundler-cache: true
          working-directory: docs

      - name: Build Jekyll site
        run: |
          cd docs
          bundle install
          bundle exec jekyll build

      - name: Setup Pages
        uses: actions/configure-pages@v5

      - name: Upload GitHub Pages artifact
        uses: actions/upload-pages-artifact@v3
        with:
          path: ./docs/_site

      - name: Deploy to GitHub Pages
        id: deployment
        uses: actions/deploy-pages@v4
