name: Preview documents
on:
  pull_request_target:
    paths:
      - 'document/**'
  workflow_dispatch:

permissions:
  contents: read
  packages: write
  attestations: write
  id-token: write
  pull-requests: write

jobs:
  build-images:
    runs-on: ubuntu-latest

    steps:
      - name: Checkout
        uses: actions/checkout@v4
        with:
          ref: ${{ github.event.pull_request.head.sha }}

      - name: Get current datetime
        id: datetime
        run: echo "datetime=$(date +'%Y%m%d%H%M%S')" >> $GITHUB_OUTPUT

      - name: Docker meta
        id: meta
        uses: docker/metadata-action@v5
        with:
          # list of Docker images to use as base name for tags
          images: |
            ${{ secrets.ALI_IMAGE_NAME }}/fastgpt-docs
          tags: |
            ${{ steps.datetime.outputs.datetime }}
          flavor: latest=false

      - name: Login to Aliyun
        uses: docker/login-action@v3
        with:
          registry: registry.cn-hangzhou.aliyuncs.com
          username: ${{ secrets.ALI_HUB_USERNAME }}
          password: ${{ secrets.ALI_HUB_PASSWORD }}

      - name: Build and push Docker images
        uses: docker/build-push-action@v5
        with:
          context: ./document
          file: ./document/Dockerfile
          push: true
          tags: ${{ steps.meta.outputs.tags }}
          labels: ${{ steps.meta.outputs.labels }}
          build-args: |
            FASTGPT_HOME_DOMAIN=https://fastgpt.io
    outputs:
      tags: ${{ steps.datetime.outputs.datetime }}

  update-images:
    needs: build-images
    runs-on: ubuntu-24.04
    steps:
      - name: Checkout code
        uses: actions/checkout@v4
        with:
          ref: ${{ github.event.pull_request.head.sha }}

      # Add kubeconfig setup step to handle encoding issues
      - name: Setup kubeconfig
        run: |
          mkdir -p $HOME/.kube
          echo "${{ secrets.KUBE_CONFIG_CN }}" > $HOME/.kube/config
          chmod 600 $HOME/.kube/config

      - name: Update deployment image
        run: |
          kubectl set image deployment/fastgpt-docs-preview fastgpt-docs-preview=${{ secrets.ALI_IMAGE_NAME }}/fastgpt-docs:${{ needs.build-images.outputs.tags }}

      - name: Annotate deployment
        run: |
          kubectl annotate deployment/fastgpt-docs-preview originImageName="${{ secrets.ALI_IMAGE_NAME }}/fastgpt-docs:${{ needs.build-images.outputs.tags }}" --overwrite

      - name: '@finleyge/github-tools'
        uses: FinleyGe/github-tools@0.0.1
        id: print-image-label
        if: success()
        with:
          token: ${{ secrets.GITHUB_TOKEN }}
          tool: issue-comment
          title: 'Docs Preview:'
          body: |
            ---
            🚀 **FastGPT Document Preview Ready!**

            🔗 [👀 Click here to visit preview](https://pueuoharpgcl.sealoshzh.site)
