name: Version Docs on Tag

on:
  push:
    tags:
      - 'v*.*.*'
  workflow_dispatch:
    inputs:
      version:
        description: 'Version label to snapshot (e.g. v1.2.3)'
        required: true
        type: string
      source_ref:
        description: 'Optional git ref to build from (tag, branch, or SHA)'
        required: false
        type: string

permissions:
  contents: write

jobs:
  version-docs:
    runs-on: ubuntu-latest

    steps:
      - name: Checkout
        uses: actions/checkout@v5
        with:
          ref: ${{ github.event_name == 'workflow_dispatch' && github.event.inputs.source_ref || github.sha }}
          fetch-depth: 0

      - name: Setup pnpm
        uses: pnpm/action-setup@v6

      - name: Setup Node.js
        uses: actions/setup-node@v5
        with:
          node-version: lts/*
          cache: pnpm
          cache-dependency-path: docs-site/pnpm-lock.yaml

      - name: Install docs dependencies
        working-directory: docs-site
        run: pnpm install --frozen-lockfile

      - name: Snapshot docs version
        working-directory: docs-site
        env:
          VERSION: ${{ github.event_name == 'workflow_dispatch' && github.event.inputs.version || github.ref_name }}
        run: |
          set -euo pipefail
          if [ -f versions.json ] && grep -q "\"${VERSION}\"" versions.json; then
            echo "Version ${VERSION} already exists in versions.json; skipping docs:version"
          else
            pnpm docusaurus docs:version "${VERSION}"
          fi

      - name: Build docs
        working-directory: docs-site
        run: pnpm build

      - name: Commit docs snapshot
        id: commit_snapshot
        env:
          VERSION: ${{ github.event_name == 'workflow_dispatch' && github.event.inputs.version || github.ref_name }}
        run: |
          set -euo pipefail
          git config user.name "github-actions[bot]"
          git config user.email "41898282+github-actions[bot]@users.noreply.github.com"
          git add docs-site/versions.json docs-site/versioned_docs docs-site/versioned_sidebars
          if git diff --cached --quiet; then
            echo "No docs snapshot changes to commit"
            echo "committed=false" >> "$GITHUB_OUTPUT"
            exit 0
          fi
          git commit -m "docs: snapshot ${VERSION}"
          echo "committed=true" >> "$GITHUB_OUTPUT"

      - name: Push docs snapshot to main
        if: steps.commit_snapshot.outputs.committed == 'true'
        run: |
          set -euo pipefail
          SNAPSHOT_COMMIT="$(git rev-parse HEAD)"
          git fetch origin main
          git checkout -B docs-version-publish origin/main
          git cherry-pick "${SNAPSHOT_COMMIT}"
          git push origin HEAD:main
