name: Deploy Docs
on:
  workflow_run:
    workflows:
      - Build Docs
    types:
      - completed

permissions:
  deployments: write
  issues: write
  pull-requests: write
  statuses: write

env:
  UV_SYSTEM_PYTHON: 1

jobs:
  deploy-docs:
    runs-on: ubuntu-latest
    steps:
      - name: Dump GitHub context
        env:
          GITHUB_CONTEXT: ${{ toJson(github) }}
        run: echo "$GITHUB_CONTEXT"
      - uses: actions/checkout@v5
      - name: Set up Python
        uses: actions/setup-python@v6
        with:
          python-version: "3.11"
      - name: Setup uv
        uses: astral-sh/setup-uv@v7
        with:
          version: "0.4.15"
          enable-cache: true
          cache-dependency-glob: |
            requirements**.txt
            pyproject.toml
      - name: Install GitHub Actions dependencies
        run: uv pip install -r requirements-github-actions.txt
      - name: Deploy Docs Status Pending
        run: python ./scripts/deploy_docs_status.py
        env:
          GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
          COMMIT_SHA: ${{ github.event.workflow_run.head_sha }}
          RUN_ID: ${{ github.run_id }}
          STATE: "pending"
      - name: Clean site
        run: |
          rm -rf ./site
          mkdir ./site
      - uses: actions/download-artifact@v6
        with:
          path: ./site/
          pattern: docs-site-*
          merge-multiple: true
          github-token: ${{ secrets.GITHUB_TOKEN }}
          run-id: ${{ github.event.workflow_run.id }}
      - name: Deploy to Cloudflare Pages
        # hashFiles returns an empty string if there are no files
        if: hashFiles('./site/*')
        id: deploy
        env:
          PROJECT_NAME: fastapitiangolo
          BRANCH: ${{ ( github.event.workflow_run.head_repository.full_name == github.repository && github.event.workflow_run.head_branch == 'master' && 'main' ) || ( github.event.workflow_run.head_sha ) }}
        uses: cloudflare/wrangler-action@v3
        with:
          apiToken: ${{ secrets.CLOUDFLARE_API_TOKEN }}
          accountId: ${{ secrets.CLOUDFLARE_ACCOUNT_ID }}
          command: pages deploy ./site --project-name=${{ env.PROJECT_NAME }} --branch=${{ env.BRANCH }}
      - name: Deploy Docs Status Error
        if: failure()
        run: python ./scripts/deploy_docs_status.py
        env:
          GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
          COMMIT_SHA: ${{ github.event.workflow_run.head_sha }}
          RUN_ID: ${{ github.run_id }}
          STATE: "error"
      - name: Comment Deploy
        run: python ./scripts/deploy_docs_status.py
        env:
          GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
          DEPLOY_URL: ${{ steps.deploy.outputs.deployment-url }}
          COMMIT_SHA: ${{ github.event.workflow_run.head_sha }}
          RUN_ID: ${{ github.run_id }}
          STATE: "success"
