name: docs-and-testcov

concurrency:
  group: ${{ github.workflow }}-${{ github.ref }}
  cancel-in-progress: true

on:
  push:
    branches: [main]
  # pull_request:
  #   branches: [main]
  workflow_dispatch:
  workflow_run:
    workflows: ["run-benchmarks"]
    types:
      - completed

permissions:
  contents: read
  id-token: write
  pages: write

jobs:
  pick-runner:
    runs-on: ubuntu-latest
    outputs:
      runner: ${{ steps.choose.outputs.use-runner }}
    steps:
      - uses: actions/checkout@v4

      - id: choose
        uses: ./.github/actions/runner-fallback
        with:
          primary-runner: "self-hosted"
          fallback-runner: "ubuntu-latest"
          github-token: ${{ secrets.CUSTOM_GH_TOKEN }}

  docs-and-testcov:
    needs: pick-runner
    runs-on: ${{ fromJson(needs.pick-runner.outputs.runner) }}

    steps:
      - uses: actions/checkout@v4

      - name: Set up Rust
        uses: actions-rs/toolchain@v1
        with:
          toolchain: stable
          override: true

      - name: Replace logo URL in README.md
        env:
          LOGO_URL: ${{ secrets.LOGO_URL }}
        run: |
          # replace  with EXAMPLE.COM/LOGO

          sed -i 's|.github/rustframe_logo.png|rustframe_logo.png|g' README.md

      - name: Build documentation
        run: cargo doc --no-deps --release

      - name: Prepare documentation for Pages
        run: |

      - name: Install Cargo binstall
        uses: cargo-bins/cargo-binstall@main

      - name: Install cargo-tarpaulin via binstall
        run: cargo binstall cargo-tarpaulin --no-confirm --locked

      - name: Generate coverage report
        run: |
          mkdir -p testcov
          cargo tarpaulin --engine llvm --out Html --out Json

      - name: Check for tarpaulin-report.html
        run: |
          if [ ! -f tarpaulin-report.html ]; then
            echo "tarpaulin-report.html not found!"
            exit 1
          fi

      - name: Export tarpaulin coverage badge JSON
        # extract raw coverage and round to 2 decimal places
        run: |
          coverage=$(jq '.coverage' tarpaulin-report.json)
          formatted=$(printf "%.2f" "$coverage")
          jq --arg message "$formatted" \
            '{schemaVersion:1,
              label:"tarpaulin-report",
              message:$message,
              color:"blue"}' \
            tarpaulin-report.json \
          > tarpaulin-badge.json

      - name: Save last commit date JSON
        run: |
          last_commit_date=$(git log -1 --format=%cd --date=short)
          jq --arg date "$last_commit_date" \
            '{schemaVersion:1,
              label:"last-commit-date",
              message:$date,
              color:"blue"}' \
            <(echo '{}') \
          > last-commit-date.json

      - name: Download last available benchmark report
        env:
          GH_TOKEN: ${{ secrets.CUSTOM_GH_TOKEN }}
        run: |
          artifact_url=$(
            curl -sSL \
              -H "Accept: application/vnd.github+json" \
              -H "Authorization: Bearer ${GH_TOKEN}" \
              "https://api.github.com/repos/${{ github.repository }}/actions/artifacts" \
            | jq -r '
                .artifacts[]
                | select(.name | startswith("benchmark-reports"))
                | .archive_download_url
              ' \
            | head -n 1
          )

          if [ -z "$artifact_url" ]; then
            echo "No benchmark artifact found!"
            mkdir -p benchmark-report
            echo '<!DOCTYPE html><html><head><title>No Benchmarks</title></head><body><h1>No benchmarks available</h1></body></html>' > benchmark-report/index.html
            exit 0
          fi

          curl -L -H "Authorization: Bearer ${GH_TOKEN}" \
          "$artifact_url" -o benchmark-report.zip

          # Print all files in the current directory
          echo "Files in the current directory:"
          ls -al

          # check if the zip file is valid
          if ! unzip -tq benchmark-report.zip; then
            echo "benchmark-report.zip is invalid or corrupted!"
            exit 1
          fi

          unzip -q benchmark-report.zip -d benchmark-report

          # echo "<meta http-equiv=\"refresh\" content=\"0; url=report/index.html\">" > benchmark-report/index.html

      - name: Copy files to output directory
        run: |
          # mkdir docs
          mkdir -p target/doc/docs
          mv target/doc/rustframe/* target/doc/docs/

          echo "<meta http-equiv=\"refresh\" content=\"0; url=../docs/index.html\">" > target/doc/rustframe/index.html

          mkdir output
          cp tarpaulin-report.html target/doc/docs/
          cp tarpaulin-report.json target/doc/docs/
          cp tarpaulin-badge.json target/doc/docs/
          cp last-commit-date.json target/doc/docs/
          # cp -r .github target/doc/docs
          cp .github/rustframe_logo.png target/doc/docs/
          # echo "<meta http-equiv=\"refresh\" content=\"0; url=docs\">" > target/doc/index.html
          touch target/doc/.nojekyll

          # copy the benchmark report to the output directory
          cp -r benchmark-report target/doc/

      - name: Add index.html to output directory
        run: |
          cp .github/htmldocs/index.html target/doc/index.html
          cp .github/rustframe_logo.png target/doc/rustframe_logo.png

      - name: Upload Pages artifact
        # if: github.event_name == 'push' || github.event_name == 'workflow_dispatch'
        uses: actions/upload-pages-artifact@v3
        with:
          path: target/doc/

      - name: Deploy to GitHub Pages
        # if: github.event_name == 'push' || github.event_name == 'workflow_dispatch'
        uses: actions/deploy-pages@v4
