name: Issue Form Labeler
on:
  issues:
    types: [ opened ]

jobs:
  label-issues:
    runs-on: ubuntu-latest
    permissions:
      issues: write
    steps:
      - uses: actions/checkout@v3

      - name: Parse bug report form
        id: bug-parser
        uses: stefanbuck/github-issue-parser@v3
        with:
          template-path: .github/ISSUE_TEMPLATE/bug-report.yml
        continue-on-error: true

      - name: Parse feature proposal form
        id: feature-parser
        uses: stefanbuck/github-issue-parser@v3
        with:
          template-path: .github/ISSUE_TEMPLATE/feature_proposal.yml
        continue-on-error: true

      - name: Apply labels from bug report
        uses: redhat-plumbers-in-action/advanced-issue-labeler@v3
        with:
          issue-form: ${{ steps.bug-parser.outputs.jsonString }}
          token: ${{ secrets.GITHUB_TOKEN }}
          config-path: .github/issue-labeler-config.yml
        continue-on-error: true

      - name: Apply labels from feature proposal
        uses: redhat-plumbers-in-action/advanced-issue-labeler@v3
        with:
          issue-form: ${{ steps.feature-parser.outputs.jsonString }}
          token: ${{ secrets.GITHUB_TOKEN }}
          config-path: .github/issue-labeler-config.yml
        continue-on-error: true

      - name: Clean up labeled sections
        uses: actions/github-script@v6
        with:
          github-token: ${{ secrets.GITHUB_TOKEN }}
          script: |
            const issueNumber = context.issue.number;
            const originalBody = context.payload.issue.body;
            const owner = context.repo.owner;
            const repo = context.repo.repo;

            const headingsToRemove = [
              '### What version of Selenium are you currently using?',
              '### The following statements are true',
              '### Did this work for you before?',
              '### If yes, what version of Selenium did it work with?',
              '### Operating System',
              '### Selenium Language Binding',
              '### Which browsers are you experiencing the issue with?',
              '### Are you using Selenium Grid?',
              '### Does this apply to specific language bindings?',
              '### What part(s) of Selenium does this relate to?'
            ];

            const form = JSON.parse(process.env.FORM_JSON || '{}');
            const lastGood = form?.["last-good"]?.trim();

            // Conditionally remove Debugging Logs
            const logs = form?.logs?.trim();
            const isLogsEmpty = !logs || logs === '```logs\n\n```' || logs === '```logs```';

            if (isLogsEmpty) {
              headingsToRemove.push('### Debugging Logs');
            }

            const lines = originalBody.split(/\r?\n/);
            const cleanedLines = [];

            let skip = false;
            for (let i = 0; i < lines.length; i++) {
              const line = lines[i];
              const trimmed = line.trim();

              if (headingsToRemove.includes(trimmed)) {
                skip = true;
                continue;
              }

              if (skip) {
                if (trimmed.startsWith('###')) {
                  skip = false;
                  i--; // Reprocess this heading
                }
                continue;
              }

              cleanedLines.push(line);
            }

            let finalBody = cleanedLines.join('\n').trim();

            if (lastGood) {
              finalBody += `\n\n---\nℹ️ **Last known working version:** \`${lastGood}\``;
            }

            await github.rest.issues.update({
              owner,
              repo,
              issue_number: issueNumber,
              body: finalBody
            });
        env:
          FORM_JSON: ${{ steps.bug-parser.outputs.jsonString }}

      - name: Get latest Selenium version
        id: get-version
        uses: actions/github-script@v6
        with:
          github-token: ${{ secrets.GITHUB_TOKEN }}
          script: |
            const { data: latestRelease } = await github.rest.repos.getLatestRelease({
              owner: 'SeleniumHQ',
              repo: 'selenium'
            });

            const latestTag = latestRelease.tag_name;
            const versionMatch = latestTag.match(/[vV]?(?:selenium-)?(\d+\.\d+(?:\.\d+)?)/);

            if (!versionMatch) {
              core.setFailed(`Couldn't parse version from tag: ${latestTag}`);
              return;
            }

            const fullVersion = versionMatch[1];
            const [major, minor] = fullVersion.split('.');
            const latestVersion = `${major}.${minor}`;

            console.log(`Latest version: ${latestVersion}`);
            core.setOutput('version', latestVersion);

      - name: Compare user version
        id: version-check
        uses: actions/github-script@v6
        with:
          script: |
            const form = JSON.parse(process.env.FORM_JSON || '{}');
            const userVersion = form?.["selenium-version"]?.trim() || "";
            const latest = process.env.LATEST_VERSION;

            const [umaj, umin] = userVersion.split('.').map(n => parseInt(n, 10));
            const [lmaj, lmin] = latest.split('.').map(n => parseInt(n, 10));

            const isOutdated = umaj < lmaj || (umaj === lmaj && umin < lmin);

            core.setOutput("user-version", userVersion);
            core.setOutput("latest-version", latest);
            core.setOutput("is-outdated", isOutdated);
        env:
          FORM_JSON: ${{ steps.bug-parser.outputs.jsonString }}
          LATEST_VERSION: ${{ steps.get-version.outputs.version }}

      - name: Comment if version is outdated
        id: comment-version
        if: steps.version-check.outputs.is-outdated == 'true'
        uses: peter-evans/create-or-update-comment@v4
        with:
          token: ${{ secrets.GITHUB_TOKEN }}
          issue-number: ${{ github.event.issue.number }}
          body: |
            ⚠️ You reported using Selenium version `${{ steps.version-check.outputs.user-version }}`, but the latest release is `${{ steps.version-check.outputs.latest-version }}`.

            Please verify that this issue still occurs with the latest version. If it no longer applies, you can close this issue or update your comment.

            *This issue will be marked "awaiting answer" and may be closed automatically if no response is received.*

      - name: Add label
        if: steps.version-check.outputs.is-outdated == 'true'
        uses: actions-ecosystem/action-add-labels@v1
        with:
          github_token: ${{ secrets.GITHUB_TOKEN }}
          labels: J-awaiting answer
      - name: Remove label
        if: steps.version-check.outputs.is-outdated == 'true'
        uses: actions-ecosystem/action-remove-labels@v1
        with:
          labels: A-needs-triaging
