name: Version Check

on:
  issues:
    types: [opened, edited]

permissions:
  issues: write

jobs:
  check-version:
    if: ${{ github.event_name == 'issues' && contains(github.event.issue.body, 'SF version') }}
    runs-on: ubuntu-latest
    steps:
      - name: Check SF version and comment if outdated
        uses: actions/github-script@v7
        with:
          script: |
            const body = context.payload.issue.body || '';
            const issueNumber = context.payload.issue.number;

            const match = body.match(/###\s+SF version\s*\n+\s*([^\s\n]+)/i);
            if (!match) {
              core.info('Could not find a SF version value in the issue body - skipping.');
              return;
            }

            const reportedVersion = match[1].trim().replace(/^v/, '');
            core.info('Reported version: ' + reportedVersion);

            const npmResponse = await fetch('https://registry.npmjs.org/singularity-forge/latest');
            if (!npmResponse.ok) {
              core.setFailed('npm registry request failed: ' + npmResponse.status);
              return;
            }
            const npmData = await npmResponse.json();
            const latestVersion = npmData.version;
            core.info('Latest version: ' + latestVersion);

            function parseVersion(v) {
              const parts = v.replace(/^v/, '').split('.').map(Number);
              return [parts[0] || 0, parts[1] || 0, parts[2] || 0];
            }

            function isOutdated(reported, latest) {
              const r = parseVersion(reported);
              const l = parseVersion(latest);
              if (r[0] !== l[0]) return r[0] < l[0];
              if (r[1] !== l[1]) return r[1] < l[1];
              return r[2] < l[2];
            }

            if (!isOutdated(reportedVersion, latestVersion)) {
              core.info('Version ' + reportedVersion + ' is current - no comment needed.');
              return;
            }

            const comments = await github.rest.issues.listComments({
              owner: context.repo.owner,
              repo: context.repo.repo,
              issue_number: issueNumber,
            });

            const botMarker = '<!-- sf-version-check -->';
            const alreadyCommented = comments.data.some(function (c) {
              return c.user.type === 'Bot' && c.body.indexOf(botMarker) !== -1;
            });

            if (alreadyCommented) {
              core.info('Version check comment already posted - skipping duplicate.');
              return;
            }

            const lines = [
              botMarker,
              '',
              'Thanks for filing this bug report!',
              '',
              'It looks like you are running **SF v' + reportedVersion + '**, but the latest release is **v' + latestVersion + '**.',
              '',
              'Before we investigate further, please upgrade and check whether the issue still occurs:',
              '',
              '```bash',
              'npm install -g singularity-forge@latest',
              'sf --version   # should print ' + latestVersion,
              '```',
              '',
              'Then re-run your reproduction steps. If the problem persists on **v' + latestVersion + '**, please update the **SF version** field in this issue and let us know.',
              '',
              '> **Why?** Many bugs are fixed in subsequent releases. Confirming on the latest version keeps the team focused on real, current issues.',
              '',
              '---',
              '*This is an automated check. If you are intentionally pinned to an older version, feel free to explain why and we will continue from there.*',
            ];
            const comment = lines.join('\n');

            await github.rest.issues.createComment({
              owner: context.repo.owner,
              repo: context.repo.repo,
              issue_number: issueNumber,
              body: comment,
            });

            await github.rest.issues.addLabels({
              owner: context.repo.owner,
              repo: context.repo.repo,
              issue_number: issueNumber,
              labels: ['needs-upgrade'],
            });

            core.info('Posted upgrade prompt for v' + reportedVersion + ' -> v' + latestVersion);
