# Most of this is inspired by the mypy primer
# See: https://github.com/hauntsaninja/mypy_primer
# This is the primer job that creates the comment on the PR
# It needs to trigger on workflow_run instead of pull_request
# as we need repository wide access to create a comment

name: Primer / Comment

on:
  workflow_run:
    workflows: [Primer / Run]
    types:
      - completed

env:
  # This needs to be the SAME as in the Main and PR job
  CACHE_VERSION: 4
  KEY_PREFIX: venv-primer
  DEFAULT_PYTHON: "3.13"

permissions:
  contents: read
  pull-requests: write

jobs:
  primer-comment:
    # Skip job if the workflow failed
    if: ${{ github.event.workflow_run.conclusion == 'success' }}
    name: Run
    runs-on: ubuntu-latest
    steps:
      - name: Check out code from GitHub
        uses: actions/checkout@v4.1.7
      - name: Set up Python ${{ env.DEFAULT_PYTHON }}
        id: python
        uses: actions/setup-python@v5.2.0
        with:
          python-version: ${{ env.DEFAULT_PYTHON }}
          check-latest: true

      # Restore cached Python environment
      - name: Restore Python virtual environment
        id: cache-venv
        uses: actions/cache@v4.2.0
        with:
          path: venv
          key:
            ${{ runner.os }}-${{ steps.python.outputs.python-version }}-${{
            env.KEY_PREFIX }}-${{ env.CACHE_VERSION }}-${{ hashFiles('pyproject.toml',
            'requirements_test.txt', 'requirements_test_min.txt',
            'requirements_test_pre_commit.txt') }}

      - name: Download outputs
        uses: actions/github-script@v7.0.1
        with:
          script: |
            // Download workflow pylint output
            const fs = require('fs');
            const artifacts_workflow = await github.rest.actions.listWorkflowRunArtifacts({
               owner: context.repo.owner,
               repo: context.repo.repo,
               run_id: ${{ github.event.workflow_run.id }},
            });

            // Get 'main' and 'PR' outputs and PR number
            const artifacts = artifacts_workflow.data.artifacts.filter((artifact) =>
              artifact.name.startsWith(`primer_output_main_${process.env.DEFAULT_PYTHON}`)
              || artifact.name.startsWith(`primer_output_pr_${process.env.DEFAULT_PYTHON}`)
              || artifact.name === 'pr_number'
            );
            for (const artifact of artifacts) {
              const downloaded = await github.rest.actions.downloadArtifact({
                owner: context.repo.owner,
                repo: context.repo.repo,
                artifact_id: artifact.id,
                archive_format: "zip",
              });
              fs.writeFileSync(`${artifact.name}.zip`, Buffer.from(downloaded.data));
            }

      - name: Unzip outputs
        run: |
          unzip primer_output_main_${{ env.DEFAULT_PYTHON }}_batch0.zip
          unzip primer_output_main_${{ env.DEFAULT_PYTHON }}_batch1.zip
          unzip primer_output_main_${{ env.DEFAULT_PYTHON }}_batch2.zip
          unzip primer_output_main_${{ env.DEFAULT_PYTHON }}_batch3.zip
          unzip primer_output_pr_${{ env.DEFAULT_PYTHON }}_batch0.zip
          unzip primer_output_pr_${{ env.DEFAULT_PYTHON }}_batch1.zip
          unzip primer_output_pr_${{ env.DEFAULT_PYTHON }}_batch2.zip
          unzip primer_output_pr_${{ env.DEFAULT_PYTHON }}_batch3.zip
          unzip pr_number.zip
      - name: Compare outputs
        run: |
          . venv/bin/activate
          python tests/primer/__main__.py compare \
          --commit=${{ github.event.workflow_run.head_sha }} \
          --base-file=output_${{ env.DEFAULT_PYTHON }}_main_BATCHIDX.txt \
          --new-file=output_${{ env.DEFAULT_PYTHON }}_pr_BATCHIDX.txt \
          --batches=4
      - name: Post comment
        id: post-comment
        uses: actions/github-script@v7.0.1
        with:
          script: |
            const fs = require('fs')
            const comment = fs.readFileSync('tests/.pylint_primer_tests/comment.txt', { encoding: 'utf8' })
            console.log("Comment to post:")
            console.log(comment)
            const prNumber = parseInt(fs.readFileSync("pr_number.txt", { encoding: "utf8" }))
            await github.rest.issues.createComment({
              issue_number: prNumber,
              owner: context.repo.owner,
              repo: context.repo.repo,
              body: comment
            })
            return prNumber
      - name: Hide old comments
        # Taken from mypy primer
        uses: kanga333/comment-hider@c12bb20b48aeb8fc098e35967de8d4f8018fffdf # v0.4.0
        with:
          github_token: ${{ secrets.GITHUB_TOKEN }}
          leave_visible: 1
          issue_number: ${{ steps.post-comment.outputs.result }}
