# PR quality gate — auto-labels shallow PRs for maintainer review
name: PR Quality Gate

on:
  pull_request:
    types: [opened]

permissions:
  pull-requests: write
  issues: write

jobs:
  check-quality:
    runs-on: ubuntu-latest
    steps:
      - name: Check PR quality
        uses: actions/github-script@v7
        with:
          script: |
            const pr = context.payload.pull_request;
            const body = pr.body || '';
            const title = pr.title || '';
            const additions = pr.additions || 0;
            const deletions = pr.deletions || 0;
            const totalChanges = additions + deletions;

            const issues = [];

            // Check for linked issue
            const hasIssueRef = /(?:fixes|closes|resolves)\s*#\d+/i.test(body) ||
                                /#\d+/.test(body);
            if (!hasIssueRef) {
              issues.push('- No linked issue found. PRs should reference an issue (`Fixes #123`).');
            }

            // Check for empty or template-only body
            const strippedBody = body
              .replace(/<!--[\s\S]*?-->/g, '')
              .replace(/#+\s*.*/g, '')
              .replace(/- \[ \].*/g, '')
              .replace(/\s/g, '');
            if (strippedBody.length < 50) {
              issues.push('- PR description is too short. Please describe what this PR does and how to test it.');
            }

            // Check for very small changes (likely typo/whitespace only)
            if (totalChanges < 3) {
              issues.push('- This PR has very few changes (' + totalChanges + ' lines). If this is a typo or whitespace fix, it may not be accepted.');
            }

            // Check for evidence of testing
            const hasTestEvidence = /terminal|output|screenshot|tested|test result/i.test(body) ||
                                    /```[\s\S]*```/.test(body);
            if (!hasTestEvidence) {
              issues.push('- No evidence of local testing found. Please include terminal output or screenshots.');
            }

            if (issues.length > 0) {
              // Add label
              await github.rest.issues.addLabels({
                owner: context.repo.owner,
                repo: context.repo.repo,
                issue_number: pr.number,
                labels: ['needs-work']
              });

              // Post comment
              const message = `Thanks for the PR. A few things need attention before we can review:\n\n${issues.join('\n')}\n\nPlease update your PR to address these points. Check the [PR template](../blob/main/.github/PULL_REQUEST_TEMPLATE.md) for guidance.\n\nPRs that don't meet minimum quality standards will be closed after 7 days.`;

              await github.rest.issues.createComment({
                owner: context.repo.owner,
                repo: context.repo.repo,
                issue_number: pr.number,
                body: message
              });
            }
