name: "Qleaner Health Guardian"

# Installs the published `qleaner` package from npm (see action.yml) and runs the global
# `qleaner` CLI — not `yarn start`. `tidy-extra-args: "-r"` captures per-step report tables in tidy_report.txt.
# PR report version is resolved from the installed package in pr-report.js.

# Runs as the GitHub Actions check named after the job id below (default: "hygiene-check").
# Branch protection → Required status checks must list that exact name once this workflow has run on a PR.
# If a required check stays "Expected — Waiting for status to be reported", the workflow did not run
# (e.g. wrong base branch, draft PR awaiting approval for first-time contributors, or workflow file not on default branch).

on:
  pull_request:
    types: [opened, synchronize, reopened, ready_for_review]
  workflow_dispatch:

jobs:
  hygiene-check:
    runs-on: ubuntu-latest
    permissions:
      contents: read
      pull-requests: write

    steps:
      - name: 1. Checkout Repository
        uses: actions/checkout@v4

      - name: 2. Run Qleaner from npm
        uses: ./
        with:
          qleaner-version: "1.5.1"
          scan-path: src/infisical-main/frontend
          image-assets-path: src/infisical-main/frontend/public
          image-code-path: src/infisical-main/frontend
          tidy-extra-args: "-r"
          image-extra-args: "-d -T 0.1"

      - name: 3. Build PR health report
        env:
          NO_COLOR: "1"
        run: |
          node .github/scripts/pr-report.js qleaner.stats.json health_summary.txt tidy_report.txt image_report.txt > pr_report.md

      - name: 4. Post PR Health Report
        if: always()
        uses: actions/github-script@v7
        with:
          script: |
            const fs = require('fs');
            if (!fs.existsSync('pr_report.md')) { return; }

            const body = fs.readFileSync('pr_report.md', 'utf8');
            const marker = '<!-- qleaner-report -->';

            const { data: comments } = await github.rest.issues.listComments({
              issue_number: context.issue.number,
              owner: context.repo.owner,
              repo: context.repo.repo,
              per_page: 100,
            });

            const existing = comments.find(c => c.body && c.body.startsWith(marker));

            if (existing) {
              await github.rest.issues.updateComment({
                comment_id: existing.id,
                owner: context.repo.owner,
                repo: context.repo.repo,
                body,
              });
            } else {
              await github.rest.issues.createComment({
                issue_number: context.issue.number,
                owner: context.repo.owner,
                repo: context.repo.repo,
                body,
              });
            }
