name: screenshots

on:
  workflow_run:
    workflows: ["Test and Build"]
    types: [completed]
  workflow_dispatch:

jobs:
  deploy-screenshots-master:
    name: Deploy master screenshots to external repo
    runs-on: ubuntu-latest
    # Only for push to master, and only if CI succeeded
    if: github.event.workflow_run.event == 'push' && github.event.workflow_run.head_branch == 'master' && github.event.workflow_run.conclusion == 'success'
    permissions:
      contents: read
      actions: read
    steps:
      - name: Download screenshots artifact
        uses: dawidd6/action-download-artifact@v6
        with:
          workflow: build.yml
          run_id: ${{ github.event.workflow_run.id }}
          name: screenshots
          path: .
          github_token: ${{ github.token }}

      - name: Deploy to GitHub Pages
        uses: peaceiris/actions-gh-pages@v3
        with:
          personal_token: ${{ secrets.SCREENSHOTS_PAT }}
          external_repository: benjajaja/mdfried-screenshots
          publish_dir: ./result
          publish_branch: gh-pages

  comment-pr-diffs:
    name: Upload diffs and comment on PR
    runs-on: ubuntu-latest
    if: github.event.workflow_run.event == 'pull_request' && github.event.workflow_run.conclusion == 'success'
    permissions:
      pull-requests: write
      actions: read
    steps:
      - name: Download screenshots artifact
        uses: dawidd6/action-download-artifact@v6
        with:
          workflow: build.yml
          run_id: ${{ github.event.workflow_run.id }}
          name: screenshots
          path: .
          github_token: ${{ github.token }}

      - name: Get PR number
        run: |
          if [ ! -f pr_number.txt ]; then
            echo "pr_number.txt not found"
            exit 1
          fi
          echo "PR_NUMBER=$(cat pr_number.txt)" >> $GITHUB_ENV

      - name: Upload images to catbox.moe
        run: |
          declare -A URL_MAP
          for file in result/diffs/*.png result/images/*.png; do
            if [ -f "$file" ]; then
              echo "Uploading $file..."
              url=$(curl -s -F "reqtype=fileupload" -F "userhash=${{ secrets.CATBOX_USERHASH }}" -F "fileToUpload=@$file" https://catbox.moe/user/api.php)
              relpath="${file#result/}"
              URL_MAP["$relpath"]="$url"
              echo "  -> $url"
            fi
          done
          cp result/body.html comment.html
          for relpath in "${!URL_MAP[@]}"; do
            sed -i "s|IMAGE_BASE_URL/${relpath}|${URL_MAP[$relpath]}|g" comment.html
          done

      - name: Comment on PR
        uses: marocchino/sticky-pull-request-comment@v2
        with:
          number: ${{ env.PR_NUMBER }}
          path: comment.html
