name: Publish Docs

on:
  push:
    branches:
      - main
    paths:
      - "docs/**"
      - "scripts/generate-docs-index.mjs"
      - ".github/workflows/docs-pages.yml"
  workflow_dispatch:

permissions:
  contents: write

concurrency:
  group: "docs-pages"
  cancel-in-progress: true

jobs:
  publish:
    runs-on: ubuntu-latest
    steps:
      - name: Checkout
        uses: actions/checkout@v5

      - name: Build docs index
        run: node scripts/generate-docs-index.mjs

      - name: Prepare static site payload
        run: |
          mkdir -p site/docs
          cp -R docs/. site/docs/
          printf '%s\n' '<!doctype html><meta charset="utf-8"><meta http-equiv="refresh" content="0; url=https://dirtydishes.github.io/islandflow/docs/"><title>Islandflow Docs</title><a href="https://dirtydishes.github.io/islandflow/docs/">Continue to docs</a>' > site/index.html
          touch site/.nojekyll

      - name: Publish to gh-pages branch
        env:
          GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
        run: |
          set -euo pipefail
          rm -rf .gh-pages-tmp
          mkdir .gh-pages-tmp
          cp -R site/. .gh-pages-tmp/
          cd .gh-pages-tmp

          git init
          git checkout -b gh-pages
          git config user.name "github-actions[bot]"
          git config user.email "41898282+github-actions[bot]@users.noreply.github.com"
          git add -A
          git commit -m "publish docs from ${GITHUB_SHA}"

          git push --force "https://x-access-token:${GITHUB_TOKEN}@github.com/${GITHUB_REPOSITORY}.git" gh-pages:gh-pages
