# SPDX-FileCopyrightText: Copyright (c) 2025 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
# SPDX-License-Identifier: Apache-2.0
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

name: Generate Documentation

on:
  push:
    branches:
      - main
      - release/*
  pull_request:
    paths:
      - 'docs/**'
      - 'container/Dockerfile.docs'
      - '.github/workflows/generate-docs.yml'

jobs:
  build-docs:
    name: Build Documentation
    runs-on: ubuntu-latest
    steps:
      - name: Checkout repository
        uses: actions/checkout@v4

      - name: Set up Docker Buildx
        uses: docker/setup-buildx-action@v3

      - name: Generate documentation
        run: |
          docker build -t docs-builder -f container/Dockerfile.docs .

      - name: Copy documentation out of container
        run: |
          docker create --name docs-container docs-builder
          docker cp docs-container:/workspace/dynamo/docs/build/html dynamo-docs/

      - name: Remove documentation container
        if: always()
        run: |
          docker rm docs-container || true

      - name: Upload documentation artifact
        uses: actions/upload-artifact@v4
        with:
          name: dynamo-docs-${{ github.run_id }}
          path: dynamo-docs
          retention-days: 15

  deploy:
    name: Deploy to private documentation repository
    needs: build-docs
    runs-on: ubuntu-latest

    # Deploy on PRs targeting release branches
    if: github.event_name == 'pull_request' && startsWith(github.base_ref, 'release')

    # Prevent multiple deployments from running simultaneously
    concurrency:
      group: deploy-docs-${{ github.base_ref }}
      cancel-in-progress: false

    env:
      DOCS_BASE_URL: "https://crispy-winner-3jnj38w.pages.github.io"
      DOCS_REPOSITORY: "ai-dynamo/dynamo-docs"
      DOCS_BRANCH: "main"
      DOCS_ARTIFACT_NAME: "dynamo-docs"

    steps:
      - name: Checkout source repo
        uses: actions/checkout@v4

      - name: Download documentation artifact
        uses: actions/download-artifact@v4
        with:
          name: ${{ env.DOCS_ARTIFACT_NAME }}-${{ github.run_id }}
          path: ${{ env.DOCS_ARTIFACT_NAME }}

      - name: Clean potentially stale metadata files (but preserve index)
        run: |
          rm -f ./${{ env.DOCS_ARTIFACT_NAME }}/CNAME
          rm -f ./${{ env.DOCS_ARTIFACT_NAME }}/_config.yml
          # Don't remove index.html - it's needed for navigation

      - name: Determine deployment directory
        id: deploy_dir
        run: |
          # For PRs, use consistent directory (latest commit overwrites previous)
          SHORT_SHA=$(echo "${{ github.sha }}" | cut -c1-8)
          echo "dir_name=${{ github.base_ref }}/pr-${{ github.event.number }}" >> $GITHUB_OUTPUT
          echo "commit_ref=${{ github.sha }}" >> $GITHUB_OUTPUT
          echo "short_sha=${SHORT_SHA}" >> $GITHUB_OUTPUT

      - name: Deploy to internal GitHub Pages
        uses: peaceiris/actions-gh-pages@v4
        with:
          personal_token: ${{ secrets.DOCS_TOKEN }}
          external_repository: ${{ env.DOCS_REPOSITORY }}
          publish_branch: ${{ env.DOCS_BRANCH }}
          publish_dir: ./${{ env.DOCS_ARTIFACT_NAME }}
          destination_dir: ${{ steps.deploy_dir.outputs.dir_name }}
          commit_message: 'Deploy documentation from ${{ github.repository }}@${{ steps.deploy_dir.outputs.commit_ref }} (branch: ${{ steps.deploy_dir.outputs.dir_name }})'
          keep_files: true

      - name: Comment on PR with docs link
        if: github.event_name == 'pull_request'
        uses: actions/github-script@v7
        with:
          script: |
            const docsUrl = `${{ env.DOCS_BASE_URL }}/${{ steps.deploy_dir.outputs.dir_name }}/`;
            const comment = `## 📚 Documentation Preview

            **📖 View Latest Documentation:** [${docsUrl}](${docsUrl})
            > **Latest Deployment:**
            > - **Commit:** [\`${{ steps.deploy_dir.outputs.short_sha }}\`](https://github.com/${{ github.repository }}/commit/${{ github.sha }}) *(latest push)*
            > - **Target:** \`${{ github.base_ref }}\`
            > - **Updated:** ${new Date().toLocaleString('en-US', { timeZone: 'UTC', timeStyle: 'short', dateStyle: 'short' })} UTC
            >
            > **Note:** This link always shows the documentation for the latest commit. It may take a few minutes for GitHub Pages to update after each push.
            ---

            *Auto-updated by the documentation deployment workflow*`;

            // Find and update existing comment, or create new one
            const { data: comments } = await github.rest.issues.listComments({
              owner: context.repo.owner,
              repo: context.repo.repo,
              issue_number: context.issue.number,
            });

            const botComment = comments.find(comment =>
              comment.user.type === 'Bot' &&
              comment.body.includes('📚 Documentation Preview')
            );

            if (botComment) {
              await github.rest.issues.updateComment({
                owner: context.repo.owner,
                repo: context.repo.repo,
                comment_id: botComment.id,
                body: comment
              });
            } else {
              await github.rest.issues.createComment({
                owner: context.repo.owner,
                repo: context.repo.repo,
                issue_number: context.issue.number,
                body: comment
              });
            }
