name: Benchmark Reports

on:
  pull_request:
    branches: "main"
    types:
      - opened
      - reopened
      - synchronize
      - ready_for_review
  merge_group:
  workflow_dispatch:

env:
  CARGO_TERM_COLOR: always
  NODE_VERSION: "22.14.0"
  PYTHON_VERSION: "3.11"
  RUST_TOOLCHAIN_VERSION: "1.93"
  RUST_TOOLCHAIN_COMPONENTS: rustfmt clippy

jobs:
  runMemoryProfile:
    if: ${{ !github.event.pull_request.draft }}
    name: run memory profile
    runs-on: ubuntu-latest
    permissions:
      contents: read
      pull-requests: write
    steps:
      - uses: actions/checkout@v6
        with:
          ref: main
      - uses: actions/cache@v4
        with:
          path: |
            ~/.cargo/bin/
            ~/.cargo/registry/index/
            ~/.cargo/registry/cache/
            ~/.cargo/git/db/
            target/
          key: ${{ runner.os }}-cargo-${{ hashFiles('**/Cargo.lock') }}
      - run: |
          MAIN_MEASUREMENT=$(cargo run --bin memtest)
          echo "MAIN_MEASUREMENT<<EOF" >> $GITHUB_ENV
          echo "$MAIN_MEASUREMENT" >> $GITHUB_ENV
          echo "EOF" >> $GITHUB_ENV
      - run: |
          echo "${{env.MAIN_MEASUREMENT}}"
          echo $MAIN_MEASUREMENT

      - uses: actions/checkout@v6
      - run: |
          BRANCH_MEASUREMENT=$(cargo run --bin memtest)
          echo "BRANCH_MEASUREMENT<<EOF" >> $GITHUB_ENV
          echo "$BRANCH_MEASUREMENT" >> $GITHUB_ENV
          echo "EOF" >> $GITHUB_ENV
      - run: |
          echo "${{env.BRANCH_MEASUREMENT}}"
          echo $BRANCH_MEASUREMENT
      - uses: actions/github-script@v8
        with:
          script: |
            if (${{ env.BRANCH_MEASUREMENT }} !== ${{ env.MAIN_MEASUREMENT }}) {
              const difference = ${{ env.BRANCH_MEASUREMENT }} - ${{ env.MAIN_MEASUREMENT }};
              try {
                await github.rest.issues.createComment({
                  issue_number: context.issue.number,
                  owner: context.repo.owner,
                  repo: context.repo.repo,
                  body: `_Change in memory usage detected by benchmark._
            ## Memory Report for ${{ github.sha }}

            | Test                        | This Branch | On Main  | Difference |
            |-----------------------------|-------------|----------| ---------- |
            | compile core + standard lib | ${{ env.BRANCH_MEASUREMENT }} bytes | ${{ env.MAIN_MEASUREMENT }} bytes | ${difference} bytes`
                })
              } catch (err) {
                core.warning(`Failed writing comment on GitHub issue: ${err}`)
              }
            } else {
              console.log("no change in memory usage detected by benchmark");
            }
        if: ${{ github.base_ref != null }}
